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에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!