1

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.

Community
  • 1
  • 1
niceman
  • 2,653
  • 29
  • 57

1 Answers1

4

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))
    
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • @niceman They work. Both. With the example you provided. Paste this in Matlab command line: `A=[2 3;4 1]; B={[2 2;1 1] [2 3;4 1] [1 1;1 1]}; find(cellfun(@(x) isequal(x,A), B)), find(all(all(bsxfun(@eq, A, cat(3, B{:})),1),2))`. Both solutions return `2` – Luis Mendo May 18 '15 at 10:38
  • silly me, I confused A with B :), anyway the second is way much faster – niceman May 18 '15 at 10:44
  • @niceman For greater speed, store the matrices directly as a 3D array, not as a cell array of matrices. That way you avoid using `cat` – Luis Mendo May 18 '15 at 10:51