2

You can do in matlab something like this:

>> fh = @(x) x^2
fh = 
   @(x)x^2

and then

>> fh(3)
ans =
    9

Now I look for a way to create the anonymous function and call it in one line, like this (it does not work):

@(x) x^2 (3) <-- This code does not work!

Is there a way to do it?

  • Is there a reason why `fh=@(x)x^2; fh(3)` is not a good enough solution? Doing `@(x) x^2 (3)` in one line, even if it was a valid syntax, is really equivalent to doing `3^2`. You are creating a function handle for no reason, since you are not storing it in a variable. – Kavka Dec 10 '11 at 04:29

2 Answers2

7

feval( @(x) x^2, 3) is what you need.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64
6

This would work (it works also with matrixes):

arrayfun(@(x) x^2,3)

Oli
  • 15,935
  • 7
  • 50
  • 66