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

Réponses (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

Catégories

En savoir plus sur Surfaces, Volumes, and Polygons 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!

Translated by