Search code examples
matlabanonymous-functioncell-arrayfunction-handle

Apply Function Handle to Multiple Input Arguments


I have a matrix and a vector in MATLAB defined:

A=rand(3);
x=rand(3,1);

And a function that takes these types of input arguments:

b = MacVecProd(A,x);

However, I'd like to use this function's function handle in order to apply it to my values. I thought that I could use cellfun for this, but:

v = {A,x};
cellfun(@MatVecProd_a, v{:})

Gives the error:

Error using cellfun
Input #2 expected to be a cell array, was double instead.

How do I do this correctly?


Solution

  • You could define your own, special function to call anonymous functions with given parameters, e.g.:

    % define special function to call function handles
    myfuncall = @(fh, v) fh(v{:});
    
    % execute MacVecProd using myfuncall
    b = myfuncall(@MacVecProd, v)
    

    Based on your comment that you have array of functions and you want to execute them for your input arguments, you could do as follows:

      % cell array of function handles
      myFunctioins = {@MacVecProd, @MacVecProd2, @MacVecProd3};
    
      % execute each function with v parameters
      % I assume you want to execute them for the same input v
      resultCell = cellfun(@(fh) fh(v{:}), myFunctioins, 'UniformOutput', 0);