MATLAB: Running a summation for a loop for different values of N.

convergencematlab functionsummation

Hello,
I have written a function that basically uses a for loop to solve a summation from 1 to N values. I am trying to run this function for different values of N and plot the results on the same plot to compare convergence. So I would like to run the function for N=5, N=20, and N=100 and plot. What is the best way to run this function to solve for each of the different values of N and store them, so they can be plotted together? I was thinking something like:
a=1:N
b=2
c=4
for N=5
e=func(a,b,c,N)
end
for N=20
f=func(a,b,c,N)
end
for N=100
g=func(a,b,c,N)
end
plot(a,e,a,f,a,g)
Where a is length N and will be the x-axis of the plot. Is there a more efficient or better way to do this?

Best Answer

N = [5, 20, 100];
result = zeros(1, length(N)); % Or what ever matchs your output
for iN = 1:length(N)
result(iN) = func(a, b, c, N(iN))
end
plot(a, result(1), a, result(2), a, result(3));
Perhaps you want something like:
result(iN, :) = func(a, b, c, N(iN))
% or
result(:, iN) = func(a, b, c, N(iN))
with a corresponding pre-allocation and modifications in the PLOT line.