I am writing a piece of code that is supposed to find the rows in Nx3 matrix E
that contains the values of Mx3 matrix T
, but they are not necessarily in the same order. I wrote something which is working, but I am not happy with the style and wish to apply logical operations on the matrices using ismember
and find, rather than the loop I am using:
E = [7 36 37; 9 1 5; 4 34 100; 4 12 33; 4 34 33];
T = [37 7 36; 4 34 33];
for i=1:size(T,1)
T(i,:) = sort(T(i,:));
end
for i=1:size(E,1)
E(i,:) = sort(E(i,:));
end
res = zeros(size(T,1),1);
for i=1:size(T,1)
a = ismember(E,t(i,:));
res(i,1) = find(sum(a,2)==3);
end
My idea was to sort each row of E
and T
, so they will be in the same order and then compare each row with a loop. However, I am trying to learn to write my code in a more MATLAB-style and wish to apply ismember
and maybe find to do the same operation. Something like this:
a = sum(ismember(E,T(1,1))~=0,2);
b = sum(ismember(E,T(1,2))~=0,2);
c = sum(ismember(E,T(1,3))~=0,2);
r = find(a&b&c);
Any more graceful solutions?
Thank you!
ismember(A,B,'rows')
or perhapssetdiff
? Any solution based on sorting is probably going to be a little obfuscated, even if it's performant. – Joshua Barr