How do I "use structures for function arguments"?
1 回表示 (過去 30 日間)
古いコメントを表示
The MATLAB Stye Guidelines 2.0 (Johnson 2014) contains the following advice:
Use structures for function arguments.
Usability of a function decreases as the number of arguments grows, especially when some arguments are optional. Consider using structures whenever arguments lists exceed three.
Structures can allow a change to the number of values passed to or from the function that is compatible with existing external code.
Structures can remove the need for arguments to be in fixed order. Structures can be more graceful for optional values than having a long and ordered list of variables.
-----
I don't know how to implement this advice!
If I have
function [y1,y2] = myfun(x1,x2,text1,cmap1,cmap2,cmap3,cmapA,...
cmapH,text2,x3,x4,x5)
end
how do I put all those real variables (x's), integer arrays of various dimensions, character arrays, etc. into a structure?
How would doing this "allow a change to the number of values passed" or "remove the need for arguments to be in a fixed order"?
0 件のコメント
採用された回答
per isakson
2019 年 5 月 23 日
編集済み: per isakson
2019 年 5 月 23 日
Try this
S.x1 = 17 ;
S.x2 = 18 ;
S.text1 = 'ABC';
S.cmap1 = magic(3);
S.cmap2 = magic(3);
S.cmap3 = magic(3);
S.cmapA = magic(3);
S.cmapH = magic(3);
S.text2 = 'DEF';
S.x3 = 19 ;
S.x4 = 20 ;
S.x5 = 21 ;
%
[y1,y2] = myfun( S );
%
function [y1,y2] = myfun( S )
if not( isfield( S, 'cmapB' ) )
S.cmapB = rand(3); % default value
end
y1 = S.x1;
y2 = S.x2;
end
2 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!