Partial Sums Using For Loop: Plotting Only First Output?

I'm trying to plot that function in relation to M, where M is the vector 1:10. For some reason it's only plotting the first output value (2) no matter what the x value is.
I know it needs to iterate through M, so I've tried to do that with an index i here, but to no avail:
function g = Pset0_P5_fxn(x,M)
g = 0; % Initialize g
i = 1:10;
for n = M(i)
a = ((x.^n)./(factorial(n)));
g = g + a;
end
end

回答(1 个)

You have to subscript ‘g’ if you want to plot all the values in the loop summation:
Your function:
function g = Pset0_P5_fxn(x,M)
g(1) = 0; % Initialize g
k = 1:M;
for n = 1:length(k)
a = ((x.^n)./(factorial(n)));
g(n+1) = g(n) + a;
end
end
Then calling your function and plotting ‘g’:
gexp = Pset0_P5_fxn(1, 10); % Calculate ‘Pset0_P5_fxn(1,10)’
figure(1)
plot([1:length(gexp)], gexp)
grid

类别

帮助中心File Exchange 中查找有关 Surfaces, Volumes, and Polygons 的更多信息

提问:

2015-2-6

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by