# for loops and storing values

1 ビュー (過去 30 日間)
hussain askar 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 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?

サインインしてコメントする。

### カテゴリ

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by