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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by