Extract variable in nested for loop that otherwise gets replaced
Ältere Kommentare anzeigen
I have several for loops that look something like this
p=rand(....)
h=rand(....)
for i:100
HCPV(i)=p(i)*h(i)
n=29
for j=1:n
cum_CO2inj(j)=function(p(i), HCPV(i),j) %I simplify here this is not actually the full code
%I want to generate/save cum_CO2inj here (which is a vector of length 30) for every iteration of i (outer most loop)?
end
end
cum_CO2inj otherwise just rewrites it self every time we iterate over i - instead I would like to see the output of 100 cum_CO2inj vectors of size 30 or a matrix of size 100 by 30? Can anyone help me with this please?
Akzeptierte Antwort
Weitere Antworten (1)
p=rand(....)
h=rand(....)
HCPV=p.*h;
for i = 1:100
for j = 1:29
cum_CO2inj(i,j) = function(p(i), HCPV(i), j);
end
end
Of course there might be further possible optimisations, as John BG suggests. You can vectorise your function such that you can ultimately write
cum_CO2inj = function(p, HCPV, 1:29);
It may be clearer, depending on your further tasks, to rewrite your function to take p and h as inputs, rather than HPCV that containes and compute HCPV inside your function:
cum_CO2inj = function(p, h, 1:29);
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
