-1

I would like to know if there is a way to vectorize the calls of different function handles, which are stored in a cell array and have of course input values themselves. I basically have a model, which looks like:

    MyModel=cell(2,1);
    MyModel{1}=@(a,b) a+b;
    MyModel{2}=@(a,b) a-b;
    a=[1,2];
    b=[2,1];
    ModelNumber=[1,2];

Now I would like to call MyModel{ModelNumber(1)} at a(1) and b(1) and MyModel{ModelNumber(2)} at a(2) and b(2). Of course it can be done with a for loop. However, the real thing will take a lot of time, if I use a loop. So is there a way to vectorize the problem in a way that something like

    MyModel{ModelNumber(:)}(a(:),b(:))

works? I already looked at cellfun, but couldn't find an answer.

Thanks in advance! Ingo

Ingo
  • 1
  • 1
  • There is probably no reason to use cellfun here http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit-loop-in-matlab-why – Daniel Dec 01 '15 at 10:10
  • Thanks for your reply. However, I cannot see where structfun may help. Both, `cellfun` and `structfun` apply a function to all elements of a cell or struct. But i have a load of different functions. – Ingo Dec 01 '15 at 10:12
  • @ingo: your original title had a typo in it, there you wrote functions in a struct while the question is about functions in cells. I corrected the title. Structfun probably won't help here. – Daniel Dec 01 '15 at 10:18
  • @Daniel, Oh sorry, of course I was talking about cells,thanks – Ingo Dec 01 '15 at 10:22
  • @Daniel `cellfun` is just nice as shorthand. This doesn't look like performance is a major issue. – Dan Dec 01 '15 at 10:34
  • @Ingo try using `cellfun` like so: http://stackoverflow.com/a/33144578/1011724 – Dan Dec 01 '15 at 10:35
  • @dan: performance seems to be the issue here "However, the real thing will take a lot of time, if I use a loop.". Don't see cellfun solving this. – Daniel Dec 01 '15 at 10:45
  • 1
    @Daniel I did not read properly. Sure, `cellfun` is not going to outperform a loop! – Dan Dec 01 '15 at 10:57

1 Answers1

0

As discussed in the comments, simply using cellfun won't increase the performance over a simple for loop. Thus a for loop is the best solution for the generic case you described above.

I would expect a good performance from a for loop in this case, thus if your solution is to slow you may put it into the question and we will see if it could be improved.

Daniel
  • 36,610
  • 3
  • 36
  • 69