for loops and storing values
2 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Stephen23
on 28 Oct 2021
Edited: Stephen23
on 28 Oct 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 Comments
See Also
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!