Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm a newbie to matlab and wonder how to create a function (i.e., $f(x) = 2*x+1$ ) get the value of $f(x)$ given $x$.

In the above example, say $x=2$, I'd expect the result to be $5$ (yep, trivial example) :-)


share|cite|improve this question

The typical way to do this is to create a MATLAB .m file to implement your function. Open the MATLAB Editor with a blank file (File>New>Script), and in the blank file, type the following:

function y = myfun(x)
    y = 2*x+1;

Then save the file as myfun.m.

At the MATLAB command line, now type

>> myfun(2)
ans =

That would be the typical thing to do if you need to reuse the function a few times. If you need a more throwaway function, you can at the command line just type

>> f = @(x)2*x+1;
>> f(2)
ans =
share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.