for loops and storing values

4 次查看(过去 30 天)
hussain askar
hussain askar 2021-10-28
编辑: Stephen23 2021-10-28
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

回答(1 个)

Stephen23
Stephen23 2021-10-28
编辑:Stephen23 2021-10-28
"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?

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by