Search code examples
matlabcell-array

Using a cell as logical mask (Matlab)


I'm trying to use a cell in matlab as logical mask for another cell (as generalisation for the matrix case).

F.i.:

A = cellfun(@logical,{[1 0]; [0 1; 1 1]},'UniformOutput',false);
B = {[2 8]; [5 3; 2 9]};

Then I would like to use A as mask for B, so that C = B(A) is the column matrix:

C = [2; 2; 3; 9];

Unfortunately this can't be done with C=B(A) as in the matrix case, so I wondered if there was an easy way to do this for cells too.


Solution

  • If I understand what you are aiming for correctly, you could achieve this by giving a two-argument anonymous function for use with cellfun:

    C_cell = cellfun(@(x,y)x(y), B, A, 'UniformOutput', false);
    C = cat(1,C_cell{:});