how to store values from loop in vector

117 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Cris LaPierre
Cris LaPierre il 24 Set 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

Più risposte (1)

DGM
DGM il 24 Set 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)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by