Is there any better alternative of four nested loops?
14 views (last 30 days)
Show older comments
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:
R=[e1(i1,:)+e2(j1,:)+e3(k1,:), i1, j1, k1];
Is there any short cut? Please help me.
Thank you in advance.
Constantino Carlos Reyes-Aldasoro on 7 Feb 2023
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]';
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:
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.
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!