Is there any better alternative of four nested loops?
10 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Constantino Carlos Reyes-Aldasoro
on 7 Feb 2023
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]
b = [2 3 4 2 1]';
a==repmat(b,[1 4])
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]))
find(all(a==repmat(b,[1 4])))
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.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!