What is wrong with this command line?
Afficher commentaires plus anciens
function y = cos_maclaurin(x,n)
%%This function will iterate through the values in the array x and for each
%%x-value it will perform a series summation for the cosine function using
%%n-terms in the series. The function will then output corresponding
%%y-values for each x-value.
y = 0;
for h = 0:n
a = (-1)^(h)*((x^(2*h))/(factorial(2*h)));
y = a + y;
end
line 3 = ???Undefined function or variable h
3 commentaires
Greg Heath
le 12 Sep 2012
Factorials take a lot of time for large n.
What is your error message?
Star Strider
le 13 Sep 2012
Modifié(e) : Star Strider
le 13 Sep 2012
Well, for a start you didn't define n or x. When I defined n = 15 and x various values from (0 2*pi), it produced acceptable values for cos(x).
I assume that's what you want it to do.
Image Analyst
le 13 Sep 2012
Modifié(e) : Image Analyst
le 13 Sep 2012
Well, you don't need the semicolon at the end of the "for" line of code. And you have some unnecessary parentheses, and you have inconsistent use of spaces around mathematical operators. But none of those are really wrong - just a bit sloppy. If you were trying to do a Maclaurin series for cosine, see my demo below.
Réponse acceptée
Plus de réponses (1)
Image Analyst
le 13 Sep 2012
Brian, I think this is what you were trying to achieve:
clc;
clearvars;
format compact
workspace;
y = 0;
numberOfTerms = 10;
index = 1;
for x = 0 : 0.1 : (3 * pi)
theSum = 0;
for h = 0 : numberOfTerms
thisTerm = (-1) ^ h * (x ^ (2 * h)) / factorial(2 * h)
theSum = theSum + thisTerm
end
y(index) = theSum;
index = index + 1;
end
x = 0 : 0.1 : (3 * pi);
plot(x, y, 'bo-', 'LineWidth', 2);
hold on;
plot(x, cos(x), 'r-', 'LineWidth', 2);
grid on;
title('Maclaurin Series for Cosine', 'FontSize', 20);
xlabel('x', 'FontSize', 20);
ylabel('y', 'FontSize', 20);
legend('Maclaurin Estimate', 'Cosine');
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!