Is there any better alternative of four nested loops?

10 ビュー (過去 30 日間)
Sheet
Sheet 2023 年 2 月 7 日
編集済み: DGM 2023 年 2 月 8 日
Hi,
I have certain matrices e1, e2, e3 & e4 corresponding to u1, u2, u3 & u4 of sizes h1, h2, h3, & h4 respectively. I have to search for
(a row of e1)+(a row of e2)+ (a row of e3) = -(a row of e4)
and report corresponding rows of u1, u2, u3 & u4 with name A, B, C & D. Here is my code:
for i1=1:h1(1,1)
for j1=1:h2(1,1)
for k1=1:h3(1,1)
R=[e1(i1,:)+e2(j1,:)+e3(k1,:), i1, j1, k1];
for z=1:h4(1,1)
if e4(z,:)==-R(1:(length(R)-3))
A=u1(R(1,length(R)-2),:)
B=u2(R(1,length(R)-1),:)
C=u3(R(1,length(R)),:)
D=u4(z,:)
end
end
end
end
end
Is there any short cut? Please help me.
Thank you in advance.
  5 件のコメント
Sheet
Sheet 2023 年 2 月 8 日
Thank you.
Can we implement genetic algorithm or any other search method into it? How?
DGM
DGM 2023 年 2 月 8 日
編集済み: DGM 2023 年 2 月 8 日
I don't know. I wouldn't be the one to ask about GA stuff.
If the values in the arrays have some sort of order to them, there might be simplifications.

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

回答 (1 件)

Constantino Carlos Reyes-Aldasoro
Constantino Carlos Reyes-Aldasoro 2023 年 2 月 7 日
Hi
In Matlab, if you think in matrices you can avoid many many many loops. For example, if you want to find if a column of a certain matrix (call that a) is equal to a different matrix (call that b), you can do that directly in a single command:
a = [1 2 3 4; 2 3 4 5; 3 4 5 6; 1 2 3 9;0 1 0 1]
a = 5×4
1 2 3 4 2 3 4 5 3 4 5 6 1 2 3 9 0 1 0 1
b = [2 3 4 2 1]';
a==repmat(b,[1 4])
ans = 5×4 logical array
0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1
So, I compared matrix b with all the columns of a, to do that I repeated b (repmat) 4 times. You will see that all the elements of the second column are the same as those elements of b and thus all are 1. In the fourth column, there is just one element that is the same. So, what I want is all the elements to be the same, so I will use all, and eventually, what I want is to know which column is the one that matches, so I will use find:
all(a==repmat(b,[1 4]))
ans = 1×4 logical array
0 1 0 0
find(all(a==repmat(b,[1 4])))
ans = 2
So without any loops, I have found which column of a matches b. Use these ideas and you may still need one loop but in general using matrices and matrix operations is much faster and efficient than using loops.

カテゴリ

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