Output of every loop calculation to be used as vector.
Show older comments
Dear Friends,
I want an output element of every loop calculation, which can be used as a separate vector. Following is an example:
Suppose, after very loop(if-else or for) calculation, gives the value of some variable, say x. After coming out of loop, I want to use all the calculated values of x, as a separate vector, say y, so that the vector y will be
y=[1st value of x in 1st loop 2nd value of x in 2nd loop & so on...];
Can any of you please help me to get such output???...
Answers (1)
Sean de Wolski
on 23 Jun 2011
y = zeros(n,1);
for ii = 1:n
y(ii) = some_value_of_x(possibly(ii))
end
6 Comments
Timo Baumann
on 14 Feb 2020
Does this also work for nested for loops? Can't really get it to work unfortunatelly :/
Stephen23
on 14 Feb 2020
"Does this also work for nested for loops?"
Of course:
y = zeros(m,n);
for ii = 1:m
for jj = 1:n
y(ii,jj) = yourScalarValue;
end
end
Timo Baumann
on 14 Feb 2020
Thank you for your quick response :)
Timo Baumann
on 14 Feb 2020
ok sry to bother you again here, but I think I didn't get it right.
I'd like to store the vectors of cs, wsmax, thetas and Wnutz in seperate vectors, that I can call independetly later in the code.
wsmin = 2*pi*nsmin;
for eS = 0.4:0.1:eSg
for ds = 0.3:0.1:dsg
for hs = 0.01:0.01:hsg
cs = sqrt(1-eS);
wsmax = wsmin/cs;
thetas = 2*pi*rhos*hs*0.25*(ds/2)^2;
Wnutz = 0.5*thetas*(wsmax^2-wsmin^2);
end
end
end
Could you please help me with that?
Stephen23
on 14 Feb 2020
"Could you please help me with that?"
LIke the examples on this page show, you should loop over indices, not data values.
"I'd like to store the vectors of cs, wsmax, thetas and Wnutz in seperate vectors"
You could use a cell array for that, although I strongly recommend putting indentically-sized numeric data into one numeric array rather than storing it as separate vectors.
Timo Baumann
on 14 Feb 2020
Ok thanks :)
The reason I'd like to store everything in seperate vectors is that I'd like to display every variable depending of another one as I want in order to see the influence of each variable individually.
Thanks again for your help.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!