1

I have the following:

cellMat = cell(3,1);
cellMat{1} = rand(3);
cellMat{2} = rand(3);
cellMat{3} = rand(3);

and I want to loop through them and get the (1,1) element of each rand matrix. I tried...

cellMat{:}(1,1);

but I get "Bad cell reference operation". But the following...

cellMat{1}(1,1);

will return the correct value.

Is there a nice way I can get this to work? I'd really like to avoid using a for loop.

Thanks!

Jon
  • 117
  • 1
  • 8

2 Answers2

3

You can use cellfun with a simple anonymous function to retrieve the element:

cellfun(@(x) x(1,1), cellMat)
Rafael Monteiro
  • 4,509
  • 1
  • 16
  • 28
1

If you really want to avoid a for loop, you should know that using cellfun is essentially the same as a loop; and can even be slower (see here and here).

If all the matrices in your cell array have two dimensions and the same size, as in your example, you could concatenate them along a third dimension and get the desired values easily:

array = cat(3,cellMat{:});
result = squeeze(array(1,1,:));
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147