How do I "use structures for function arguments"?

조회 수: 2 (최근 30일)
Leslie
Leslie 2019년 5월 23일
편집: per isakson 2019년 5월 23일
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
  댓글 수: 2
madhan ravi
madhan ravi 2019년 5월 23일
'cmapB)' - probably you meant 'cmapB' , perhaps?
per isakson
per isakson 2019년 5월 23일
편집: per isakson 2019년 5월 23일
Indeed. Fixed it. Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by