1
votes

I'm trying to figure out a matrix-oriented way to perform the ismember function by row in MATLAB. That is, if I have matrices

[1 2 3 4 5 6]
[7 8 9 10 11 12]

And I put in

[3 4 5]
[10 11 12]

Into some ismember-ish function, I'd like it to return

[0 0 1 1 1 0]
[0 0 0 1 1 1]

Other than looping over each row of the matrix in a for loop, is there a way to do this?

2
Are [1 2 3 4 5 6] [7 8 9 10 11 12] 2 rows of the same matrix? - Franck Dernoncourt
@FranckDernoncourt: good question - if the answer's yes, the solution is a lot simpler. - Jonas
Does this need to match the ordered pattern, of the second input, or only the elements. That is, would the answer be different if you put in [5 4 3], rather than [3 4 5]? - Pursuit

2 Answers

4
votes

Assuming that your data are available as matrices A and B

A = [
    1 2 3 4 5 6
    7 8 9 10 11 12
    ];

B = [
    3 4 5
    10 11 12];

you can convert them to cells and then use cellfun

cellA = mat2cell(A, ones(1, size(A,1)), size(A,2));
cellB = mat2cell(B, ones(1, size(B,1)), size(B,2));

membership = cell2mat(cellfun(@ismember, cellA, cellB, 'UniformOutput',  false));

This returns

membership =

     0     0     1     1     1     0
     0     0     0     1     1     1
0
votes
A = [5 3 4 2]; B = [2 4 4 4 6 8];
[Lia1,Locb1] = ismember(A,B)

Lia1 =

 1     1     1     1     0     0


 Locb1 =

 4     3     3     3     0     0