Running a summation for a loop for different values of N.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Jan
am 13 Jun. 2013
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 Kommentar
Weitere Antworten (1)
Andrei Bobrov
am 13 Jun. 2013
Bearbeitet: Andrei Bobrov
am 13 Jun. 2013
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{:});
2 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!