1
$\begingroup$

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

1 Answers 1

4

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