Defining function handles in MATLAB
显示 更早的评论
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.
Thanks.
2 个评论
Leia Sofia Mendez
2017-7-26
编辑:Walter Roberson
2017-7-26
This was the code I was trying to write:
a= 0.0009
a= convtime([1],'samples','seconds')
This code gave an error saying that my function (convtime) was undefined. How you define a function in MATLAB?
Walter Roberson
2017-7-26
Leia Sofia Mendez:
convtime appears to be from the File Exchange https://www.mathworks.com/matlabcentral/fileexchange/28204-time---rate-unit-conversion-function .
You should go to that link, and click the download button, and download the .zip file. You should unzip to a directory that is not under your MATLAB installation directory. You would then use pathtool in MATLAB to add that directory to your MATLAB path.
采纳的回答
更多回答(3 个)
Walter Roberson
2012-1-8
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.
1 个评论
Salaheddin Hosseinzadeh
2014-3-13
I rather this anonymous way of defining a function! It's way easier. I also know another way of doing this, surprisingly nobudy mentioned that so far! lol I'm gonna put it in the answers.
Junaid
2012-1-8
Dear Richard,
To define a function in matlab you can do following syntax of given function:
function n = F(x)
n= 2*x^3+7*x^2+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.
> f = @(x) 2*x^3+7*x^2+x;
> f(0)
0
surprising no one mentioned anonymous functions...
1 个评论
Salaheddin Hosseinzadeh
2014-3-21
@ Cyril
Walter did, just make sure you checked the other answers and comments!
类别
在 帮助中心 和 File Exchange 中查找有关 Function Handles 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
