0

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?

TShiong
  • 1,257
karlabos
  • 1,257
  • You might find this post on SO to be helpful. – Ben Grossmann Mar 12 '23 at 18:32
  • 1
    I am not in front of a computer with Matlab, but, you can try a couple of things; for example: F=@(A) (@(x) x.^2 +A). If Matlab doesn't like that nested syntax, you can make function f = myfun(A) f = @(x) x.^2+A – Alex K Mar 12 '23 at 18:39

1 Answers1

1

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

ConvexHull
  • 504
  • 3
  • 10