Search code examples
matlabscilab

What is the equivalent of cellfun(@(x) x/sum(x(:)), y, 'UniformOutput',0)?


How to replace Matlab functions cellfun

y = cellfun(@(x) x/sum(x(:)), y, 'UniformOutput',0);
y = cellfun(@sqrt, y, 'UniformOutput',0);

with loops. I'd like to convert this code into Scilab but I don't understand what cellfun does with x. Could you write some equivalent code in a C or Java, (or other languages) form?


Solution

  • It performs

    yout=cell(size(y));
    for k=1:numel(y)
       yout{k}=sqrt(y{k}/sum(y{k}(:)));
    end
    y=reshape(yout,size(y));
    

    Explanation: the first call the cellfun will go over each element of y, your original cell, then apply the function @(x) x/sum(x(:)) to each element of your cell (i.e. it will normalize each cell element such that their respective elementwise sum equals to 1). The result is stored in the corresponding element of the output cell. The second call does the same with the sqrt function, so we can unite the two operations in the same command in the loop.

    Some proof:

    y={[1 2], [3 4]; [5 6], [7 8]; [9 10], [11 12]};
    
    yout1 = cellfun(@(x) x/sum(x(:)), y, 'UniformOutput',0);
    yout1 = cellfun(@sqrt, yout1, 'UniformOutput',0);
    
    yout2=cell(size(y));
    for k=1:numel(y)
       yout2{k}=sqrt(y{k}/sum(y{k}(:)));
    end
    yout2=reshape(yout2,size(y));
    
    isequal(yout1,yout2) %returns 1