Running a summation for a loop for different values of N.
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Jan
2013-6-13
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.
更多回答(1 个)
Andrei Bobrov
2013-6-13
编辑:Andrei Bobrov
2013-6-13
N = [5 20 100]
b = 2;
c = 4;
f = arrayfun(@(x)[(1:x)',reshape(func((1:x)',b,c,x),[],1)],N,'un',0);
plot(f{:});
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!