How might I define a function handle?
For example, I want to define a function f(x)=2*x^3+7*x^2+x
I want MATLAB to evaluate f(x) at random values x. I have heard of feval and fhandles, but I don't know how to do it.
First, you need to create a new m-file then type this code
function y = f(x) y = 2 * (x^3) + 7 * (x^2) + x;
Save with filename 'f.m'
Then create a new m-file and type this code
x = randi(7); y = f(x)
randi will generate random number
To define a function in matlab you can do following syntax of given function:
function n = F(x)
that is it. You can put end at the end of function. But it is also acceptable not to put to various matlab versions. If you put end for one function then you have to put for all function in single m file.
then you can generate random numbers, either integer or double, and can get the values of this function.
Function handle version:
f = @(x) 2*x^3+7*x^2+x;
Then f is already the function handle, and you can call f(3.7) (for example)
There is no need to use feval() for this, but you could.
> f = @(x) 2*x^3+7*x^2+x; > f(0) 0
surprising no one mentioned anonymous functions...