2

I wish to use cellfun similarly to how I would use bsxfun for applying a function on nx1 cell and 1x1 cell i.e for bsxfun,

multi = bsxfun(@times, rand(1,10), 2)

However, when doing something like this in cellfun it complains that the cells are not the same size. How can I resolve this?

To use for a Cell Example:

My actual problem is pretty simple and I can see some other ways around this but my initial instincts were to use cellfun. Not being able brought me here. Here is my actual problem,

use_var = {[0,1,0,1,1,1,1,0]}; rule_dep = {[1,3],[1,2,4],[3,5,7],[5],[4,8]};

I now wish to indexuse_var by each individual rule_dep. My first try was,

use_rule = cellfun(@(x,y) y{x}, rule_depend, use_var, 'Uniformoutput', false);

but throws up dimension problems.

Little Bobby Tables
  • 4,466
  • 4
  • 29
  • 46

1 Answers1

5

The trick is to define a function handle which returns the expected result for any element of rule_dep

use_var = [0,1,0,1,1,1,1,0] %must be a array, not cell
use_rule = cellfun(@(x) use_var(x), rule_dep,  'Uniformoutput', false)

Something like singleton dimension expansion is not available in cellfun. Keep it mind that cellfun and arrayfun are often slower than a for-loop. The best solution might be a simple loop.

Community
  • 1
  • 1
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • This worked beautifully, thank you. I was not aware of the potential speed difference. I have already written a one line loop so shall time both in this instance and see which is fastest. – Little Bobby Tables Aug 14 '15 at 12:19
  • cellfun - Elapsed time is 0.009932 seconds. loop - Elapsed time is 0.010384 seconds. I guess it makes the difference on larger matrices. – Little Bobby Tables Aug 14 '15 at 12:21