for loops and storing values
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (1)
Stephen23
am 28 Okt. 2021
Bearbeitet: Stephen23
am 28 Okt. 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?
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!