Search code examples
matlabcell-array

MATLAB: Apply cellfun to specific columns of every cell


I am trying to apply a function to specific columns of every cell in a cell array. I am familiar with cellfun, however, I am simply struggling with the correct syntax for identifying the specific columns (i.e. what's the correct way of passing the cellArray into cellfun (2nd input argument))?

Here's my toy example. I would like to multiply the second column of every cell by 100 while the first column should be unaffected.

cellArray = cell(2,2);
cellArray{1,1} = [1,1 ; 2,2 ; 3,3];
cellArray{1,2} = [1,4 ; 2,5 ; 3,6];
cellArray{2,1} = [1,7 ; 2,8 ; 3,9];
cellArray{2,2} = [1,10 ; 2,11 ; 3,12];

result = cellfun(@times, cellArray, repmat({100}, 2, 2), 'UniformOutput', false);

With simply passing the whole cellArray into cellfun, all columns will be multiplied by 100. That's not what I want.


Solution

  • Here's how:

    result = cellfun(@(x) [x(:,1) x(:,2)*100], cellArray, 'un', 0);
    

    cellfun and other *funs (except bsxfun) are wrappers for a loop. Think of 'em as a loop and you'd know how to apply.