Matlab - How to make function handle depending on data?

48 Views Asked by At

So when you do something like @$(x) x^2+2$ you get the function handle of $f(x) = x^2+2$ in Matlab, and this can be used for calling the function on some solvers, but when you do

function $[y] =$ xsquareplustwo(x)

$y = x^2 + 2$;

end

you get the function, which can only be used to evaluate the function on the point $x$, so basically it's not really a function but only an evaluation.

Now the advantage of the function is that it can depend on input arguments, so I wonder... Is there a way to get a handle depending also on input arguments? Because the @ thing looks like it only specifies the ourput arguments, which are inside the @($\cdot$).

I should specify that I'm not looking for something in simple lines of code like

$A=2$;

myfunction = @$(x) x^2 - A$;

This would only work if the expression after the @ was simple enough, but it won't work for something more complicated like when the function has several loops of code before returning the output. So I would really want some way of making a big function similar to the "function (...) end" file, except that instead of returning the function applied on particular values it returned the handle, is that possible?

1

There are 1 best solutions below

0
On

You simply can use the vectorized math operations in Matlab.

For your example this would be the element-wise multiplication operation (Hadamard product):

function [y] = xsquareplustwo(x)

  y = x.^2 + 2;

end