2

Let's say I want to store the function y(x) = x + 2 in a variable.

Is there any way to save y = x + 2, and access as y(x)? For example, y(2)?

1
  • For functions with generic names like y the anonymous functions seem to be the way to go. However, for most you may want to just create regular functions. Note that you can have many functions in 1 file for easy handling. Commented Jan 31, 2014 at 14:33

1 Answer 1

4

An anonymous function is what you're looking for:

>> y = @(x) x+2;
>> y(2)

ans =

     4
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Technically, the anonymous function is the right-hand side @(x) x+2, and y is a function handle to that anonymous function
@LuisMendo For general knowlage - for define this function, should I syms x first?
@user1798362 No, the x in the anonymous function's definition is an ordinary variable, not a symbolic variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.