transforming an m-file to an anonymous or inline function
1 次查看(过去 30 天)
显示 更早的评论
Hi, I have the following function
function out=myfun(x,y,z)
aa=h1(x,y,z);
dd=h2(x,y,z);
out=[x(1)+y(2)
x(3)+z(2)
x(1)+aa
x(3)+dd*y(1)];
Is there any way I can write this function either as inline or anonymous? that is without writing an m-file?
Thanks, J.
0 个评论
采纳的回答
Daniel Shub
2011-8-24
You need to get rid of the temp variables aa and dd:
aa = @(x,y,z)(h1(x,y,z));
dd = @(x,y,z)(h1(x,y,z));
fcn = @(x,y,z)([x(1)+y(2); x(3)+z(2); x(1)+aa(x,y,z); x(3)+dd(x,y,z)*y(1)]);
2 个评论
Daniel Shub
2011-8-24
See my edit. You can keep splitting up h1 and h2 into functions that are whatever size you want. The key is you cannot have any temp variables.
更多回答(1 个)
Fangjun Jiang
2011-8-24
It is not recommended to use anonymous function due to the fact that the function has so many characters. If you wan to make it in line, just remove the first line 'function out=myfun(x,y,z)' and copy the rest of the code into your other M-script or M-function.
4 个评论
Fangjun Jiang
2011-8-24
Should be subfunctions in my previous comments. Search subfunctions in document for details.
Daniel Shub
2011-8-24
If your m-file is a script and you want to use a function that requires a function handle (e.g., fminsearch) then you need a second m-file with your function or an anonymous function.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!