MATLAB: How to extract matrix elements corresponding to row and column subscripts stored in cell arrays

cell arraysindexing

Hi all,
I am stuck with cell arrays and indexing. I have a matrix M and I want to extract only those elements with specific row- and column- indices. These indices are stored in cell arrays: C1 (for row subscripts) and C2 for column subscripts.
This is the way I did it:
my1Func = @(x,y) M(x,y);
Sub_M = cellfun(@(x,y) myFunc(x,y), C1, C2, 'UniformOutput', false);
However, the result is not what I want. I only need to take same-index values from C1 and C2: Sub_M {4} should have only those elements of M with the row and column subscripts having the same index in the respective arrays. For example, Sub_M (2,2) should be:
M(C1{4}(2),C2{4}(2));
I do not know how to do that. Note: cells in C1 have different size, same for cells in C2. But the first cell in C1 has the same size as the first in C2, the second in C1 as the second in C2 and so on…
Can you help me?
Thank you!

Best Answer

First, note that with your code you've got an anonymous function wrapped inside an anonymous function. Either of the following would be simpler:
my1Func = @(x, y) M(x, y);
Sub_M = cellfun(My1Func, C1, C2, 'UniformOutput', false);
or
Sub_M = cellfun(@(x, y) M(x, y), C1, C2, 'UniformOutput', false);
Anyway, If I understood correctly:
sub_M = cellfun(@rows, cols) M(sub2ind(size(M), rows, cols)), C1, C2, 'UniformOutput', false);