how to store values from loop in vector

114 vues (au cours des 30 derniers jours)
Manora Mony
Manora Mony le 24 Sep 2021
Réponse apportée : DGM le 24 Sep 2021
hi
i wrote a code reprated from p = -20 to 30 and each loop gives result 'rate' ,
how i can draw rate from each loop with p
or how i can store rates in vector to draw it with p (vector)
thanks in advance

Réponse acceptée

Cris LaPierre
Cris LaPierre le 24 Sep 2021
See Ch 13 of MATLAB Onramp (Programming) for an interactive introduction to using for loops. You can also find some examples of how to store values calculated in each loop in the documentation of for loops:
s = 3;
H = zeros(s);
for c = 1:s
for r = 1:s
H(r,c) = 1/(r+c-1);
end
end
H
H = 3×3
1.0000 0.5000 0.3333 0.5000 0.3333 0.2500 0.3333 0.2500 0.2000

Plus de réponses (1)

DGM
DGM le 24 Sep 2021
Not knowing what exactly you're doing, it's hard to give an exact or potentially simplified answer, but here's an example.
p = -20:30; % if you need p outside the loop, save it
rate = zeros(size(p)); % preallocate vector
for k = 1:numel(p)
rate(k) = k.^2 + 100*sin(p(k)/2); % store each result
end
plot(p,rate)
Of course, the above example can be simplified, so keep that in mind.
p = -20:30;
rate = (1:numel(p)).^2 + 100*sin(p/2);
plot(p,rate)

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!

Translated by