Reputation: 3744
Say I have a matrix, M:
9.89E+10 3.12E+10 29
8.88E+10 8.16E+10 9
9.97E+10 8.31E+10 22
8.10E+10 6.55E+10 94
2.17E+10 8.11E+09 53
6.34E+10 8.84E+10 54
5.69E+10 7.07E+10 8
9.23E+10 8.24E+10 38
8.88E+10 5.81E+10 27
And I have another array, A:
A=8.88E+10, 9.23E+10
I want all the entries in M that contain all the entries in A. That is, my output should be a matrix, N:
8.88E+10 8.16E+10 9
9.23E+10 8.24E+10 38
8.88E+10 5.81E+10 27
I can do this using a code like:
count=1;
for i=1:size(A,1)
for j=1:size(M,1)
if M(j,1)==A(i,1)
extracted(count,:)=M(j,:);
count=count+1;
end
end
end
But I guess there could be a one liner code in MATLAB to do this. Is there any?
Upvotes: 1
Views: 41
Reputation: 5822
One Liner Solution
N = M(sum(ismember(M,A),2)>0,:);
Explanation
The ismember function generates a binary matrix of the same size of M, which contains 1 for each value in M which exists in A and 0 otherwise.
We use sum function to sum each row in that matrix. rows which sum up to a value which is bigger than 0 are rows which contains values from A.
Last, we generate the out matrix by taking all the rows from M which fits to the constraint from previous stage.
Result
N =
8.88E+10 8.16E+10 9
9.23E+10 8.24E+10 38
8.88E+10 5.81E+10 27
Upvotes: 2