for loops and storing values

3 visualizzazioni (ultimi 30 giorni)
hussain askar
hussain askar il 28 Ott 2021
Modificato: Stephen23 il 28 Ott 2021
I'm adding a constraint to my problem, the two constraints are the ones inside c. I want my c output to be 46 x 4 = 184 values. However, when i run my code, as the two “for loops” are completed, the value of “c” is replaced. In other words, the old value of “c” is forgotten when the loop takes different values of “i” and “h” and only the last value of “c” for h=23 and i=4 are returned to the main routine. what can i do to solve this?
for h= 1:23
for i =1:4
c = [-DR(i)-p(h+1,i)+p(h,i);p(h+1,i)-p(h,i)-UR(i)];
end
end

Risposte (1)

Stephen23
Stephen23 il 28 Ott 2021
Modificato: Stephen23 il 28 Ott 2021
"what can i do to solve this?"
Use indexing into a preallocated array:
c = nan(46,4); % <--- preallocate!
for h = 1:23
for i = 1:4
c(2*h-[1,0],i) = [-DR(i)-p(h+1,i)+p(h,i);p(h+1,i)-p(h,i)-UR(i)];
end % ^^^^^^^^^^^ indexing!
end
Given the simplicity of those constraint calculations, it is possible that loops are not required: have you looked at vectorizing your code?

Categorie

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

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by