MATLAB: Return subscripts of common rows for multi-dimensional matrix

findmatricesmatrix

I have a 8×2 matrix, A, and a 133x2x5 matrix, B. I want to return the the layer in B in which a row in A matches a row in B. How can I do that? I tried using intersect and ismember but have not had any luck thus far. Having a hard time with the matrix being multi-dimensional.

Best Answer

[row, layer] = ind2sub([size(B, 1), size(B, 3)], find(ismember(reshape(permute(B, [1 3 2]), [], size(B, 2)), A, 'rows')))
If you want just the layers in which any row matches any row of A:
layer = unique(layer)
edit: By the way the logic of this is to reshape B into a two column matrix by vertically concatenating the layers. Then use the traditional ismember(..., 'rows') and finally convert the matched rows back into (row, layer) coordinate.
Another way, avoiding the sub2ind would be:
layer = unique(ceil(find(ismember(reshape(permute(B, [1 3 2]), [], size(B, 2)), A, 'rows')) / size(B, 1)))