Search code examples
arraysmatlabmatrixcell-array

Find index of element in cell array of matrices


I want to find the index(that's in row and column) of a specific matrix in a cell array of matrices, for example if I have

A = [2 3;4 1]

and

B = {[2 2;1 1] [2 3;4 1] [1 1;1 1]}

then I want to return 2(because B{2}==A).

I want to solve this without for, although I don't have to, the cell array is basically small, but I want to do it without for anyway.

I searched for this and found this and this on SO but their solution only work for strings which I don't have here.

So how to solve this without for-loop ?

Note

A is an ordinary matrix not a single element cell array, B is a cell array of matrices.


Solution

  • Some possibilities:

    • Use cellfun with isequal to test each element of B for equality:

      find(cellfun(@(x) isequal(x,A), B))
      
    • If all matrices have the same size: concatenate into a 3D array (or better yet, use a 3D array from the beginning), and use bsxfun for the comparison:

      find(all(all(bsxfun(@eq, A, cat(3, B{:})),1),2))