transforming an m-file to an anonymous or inline function

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.

 採用された回答

Daniel Shub
Daniel Shub 2011 年 8 月 24 日

1 投票

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 件のコメント

Junior
Junior 2011 年 8 月 24 日
The very reason I am post the question is because I don't want to insert for aa and dd, which are themselves very complicated expressions. For simplicity, I just defined them as h1(x,y,z) and h2(x,y,z). Thanks, J.
Daniel Shub
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
Fangjun Jiang 2011 年 8 月 24 日

0 投票

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 件のコメント

Junior
Junior 2011 年 8 月 24 日
Is there any restrictions on the number of characters for an inline function? And about your suggestion of just removing the first line, what to do about the definitions of "aa" and "dd"?
thanks for answering,
J.
Fangjun Jiang
Fangjun Jiang 2011 年 8 月 24 日
What do you mean inline function? You either insert your code above wihtout the function line in-line with your main function (or main script), or you create a function for it.
Anonymous function is no different than ordinary function. If the function is short, you can use anonymous function so you don't have to give it a name and you don't need to create a separate file.
If your main program is also a function, you can make the code above a sun-function in your main function .m file. You don't need to create a separate .m file for it. For example, open importdata.m file, at the top, it is the importdata() function itself. At the bottom, there are many functions that are only available for use by the importdata() function.
Fangjun Jiang
Fangjun Jiang 2011 年 8 月 24 日
Should be subfunctions in my previous comments. Search subfunctions in document for details.
Daniel Shub
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.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeFunction Creation についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by