Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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) :-)

Thanks

share|improve this question
add comment

1 Answer 1

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 =
     5

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 =
     5
share|improve this answer
add comment

Your Answer

 
discard

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.