Running a summation for a loop for different values of N.
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Jan
le 13 Juin 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 commentaire
Plus de réponses (1)
Andrei Bobrov
le 13 Juin 2013
Modifié(e) : Andrei Bobrov
le 13 Juin 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 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!