Is there any better alternative of four nested loops?
Ältere Kommentare anzeigen
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 Kommentare
DGM
am 7 Feb. 2023
How large are the arrays? What class are they? If they are floating point, to what tolerance must they match?
Sheet
am 7 Feb. 2023
Let's simplify for sake of example. Let's say you wanted to check rowofe1 + rowofe2 == rowofe3 (only two terms in the sum). Let's say each array is 10x5.
% integer-valued
h = 10;
w = 5;
e1 = randi([0 9],h,w);
e2 = randi([0 9],h,w);
e3 = randi([0 9],h,w);
% generate sum by implicit array expansion
e1pluse2 = e1 + permute(e2,[3 2 1]);
e1pluse2 = reshape(permute(e1pluse2,[1 3 2]),[],w);
% find matching rows
[matches idx] = ismember(e1pluse2,e3,'rows');
size(e1pluse2)
So the size of the array holding all possible row sums between N 2D arrays is rows^N x cols.
In your case, that would be 43578^3 x 8. You don't have enough memory.
Sheet
am 8 Feb. 2023
Antworten (1)
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.
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!