Running a summation for a loop for different values of N.
조회 수: 1 (최근 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!