Search code examples
functionmatlabmatrixvector

Evaluating a vector-variate function at multiple points in MATLAB


Suppose that I have a vector-variate function, e.g.,

f = @(x)(x(1)+x(2));

I want to evaluate f at points x = [1; 1], [2; 2] and [3; 3]. These points are given in a matrix as:

x = [1 2 3;1 2 3]

I want to have the evaluations in a vector as:

[f([1;1]), f([2;2]), f([3;3])]

but I am not sure how to do that. Writing f(x) gives only one value.


Solution

  • Assuming you can change the definition of you function, f, you just need to do this to vectorize over all of the columns:

    f = @(x)(x(1,:)+x(2,:));
    

    Then, when you call f(x) you'll obtain [2 4 6].

    You can learn more about the colon operator in the documentation here.