Loop "for" optimization

1 回表示 (過去 30 日間)
Aleksei
Aleksei 2023 年 12 月 10 日
コメント済み: Dyuman Joshi 2023 年 12 月 16 日
Hello.
I have a code and need to optimize loop "for". I need make one "for" instead of two. How to make less then 99*99 itaration?
f =[6; 6; 30; 2; 13; 8; 21;
14; 1; 24; 28; 25; 24; 7;
18; 9; 26; 30; 25; 8; 13;
24; 25; 11; 18; 23; 12; 29;
26; 19; 29; 16; 4; 27; 24;
19; 14; 7; 15; 24; 6; 21 ];
g =[43; 28; 21; 15; 20; 47; 48;
47; 32; 15; 39; 31; 20; 19;
42; 23; 33; 14; 35; 26; 32;
10; 43; 24; 37; 39; 24; 31;
17; 31; 9; 28; 46; 25; 12;
17; 43; 19; 20; 49; 16; 22];
AA = zeros(1, 99);
a_k=1;
BB = zeros(1, 99);
b_k=1;
for v = 0.01:0.01:0.99
for u = 0.01:0.01:0.99
if (v+u == 1)
D=(v*f)+(u*g);
B = round(D);
E = reshape(B,7,6);
[X,K] = linprog(E,[],[],Aeq,beq,lb);
A = round(X);
H = reshape(A,7,6);
Optim_plan_A = H';
N =A'*f;
L =A'*g;
AA(a_k)=N;
BB(b_k)=L;
a_k=a_k+1;
b_k=b_k+1;
end
end
end
figure
plot (AA,BB, 'g')

回答 (1 件)

Atsushi Ueno
Atsushi Ueno 2023 年 12 月 10 日
After 99*99 iterations, v+u==1 is satisfied only 99 times.
The same thing can be done without repeating the double nested loop by calclating u as u=1-v.
f = [6; 6; 30; 2; 13; 8; 21; 14; 1; 24; 28; 25; 24; 7; 18; 9; 26; 30; 25; 8; 13; 24; 25; 11; 18; 23; 12; 29; 26; 19; 29; 16; 4; 27; 24; 19; 14; 7; 15; 24; 6; 21 ];
g = [43; 28; 21; 15; 20; 47; 48; 47; 32; 15; 39; 31; 20; 19; 42; 23; 33; 14; 35; 26; 32; 10; 43; 24; 37; 39; 24; 31; 17; 31; 9; 28; 46; 25; 12; 17; 43; 19; 20; 49; 16; 22];
AA = zeros(1,99); a_k = 1;
BB = zeros(1,99); b_k = 1;
for v = 0.01:0.01:0.99
u = 1 - v;
D = (v*f)+(u*g);
B = round(D);
E = reshape(B,7,6);
[X,K] = linprog(E,[],[],Aeq,beq,lb);
A = round(X);
H = reshape(A,7,6);
Optim_plan_A = H';
N = A'*f;
L = A'*g;
AA(a_k) = N;
BB(b_k) = L;
a_k = a_k + 1;
b_k = b_k + 1;
end
figure
plot (AA,BB,'g')
  2 件のコメント
Aleksei
Aleksei 2023 年 12 月 10 日
Thank you very much!
Dyuman Joshi
Dyuman Joshi 2023 年 12 月 16 日
Hello @Aleksei, if this answer solved your problem, please consider accepting the answer.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by