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"?

采纳的回答

per isakson
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by