cellfun is just like looping through the cell matrix and
executing specified function separately on each cell.
It's usually faster than doing the same thing explicitly
in loop, but the basic difference is that its easy to
write and read - its immediately clear what the call is
doing. But you could just as well write the loop yourself.
In your specific case you could use cellfun this way:
mean_a = mean(cellfun(@(x) mean(x(:)), a));
If you have thousands of cells and you want to do something
to each of them you either use a loop or a cellfun
BTW: @(x) means that you want the content of each cell
to be understood as x so that mean(x(:)) gives you what
you want - mean of the whole matrix content of the cell.
Cellfun... shall I use it?
Calling a function option using cellfun
Explanation of cellfun()
image processing - How do I apply a function with multiple parameters using `cellfun` (MATLAB)? - Stack Overflow
cellfun is just like looping through the cell matrix and
executing specified function separately on each cell.
It's usually faster than doing the same thing explicitly
in loop, but the basic difference is that its easy to
write and read - its immediately clear what the call is
doing. But you could just as well write the loop yourself.
In your specific case you could use cellfun this way:
mean_a = mean(cellfun(@(x) mean(x(:)), a));
If you have thousands of cells and you want to do something
to each of them you either use a loop or a cellfun
BTW: @(x) means that you want the content of each cell
to be understood as x so that mean(x(:)) gives you what
you want - mean of the whole matrix content of the cell.
It of course depends in what you want to do. cellfun is intended to act separately on each cell in your cell array. If you want to take a global mean of your cell array values, and insist on using cellfun then this should work:
mean_a = mean(cell2mat(cellfun(@mean, a,'UniformOutput',0)))
Hi everyone,
Lately I am using functions like cellfun, arrayfun, etc. all the time to avoid writing loops. I was wondering if this is a good practise.
Is it better or simple loop which is much easier to write and read is a better approach?
In addition a for loop can run in parallel later.
You can do this using an anonymous function that calls myfun with the two additional arguments:
cellfun(@(x) myfun(x,const1,const2), cellarray)
Another trick is to use ARRAYFUN on the indices:
arrayfun(@(k) myfun(cellarray{k},const1,const2), 1:numel(cellarray))
if the return values of myfun are not scalars, you might want to set the 'UniformOutput',false option.