Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to return a default widget structure if not enough input arguments are passed?

조회 수: 3 (최근 30일)
Zachary Reyes
Zachary Reyes 2018년 11월 8일
마감: MATLAB Answer Bot 2021년 8월 20일
function res = createWidget(typeArg, matArg, prongsArg, massArg)
if (HELP HERE)
res.type = '';
res.material = '';
res.prongs = 0;
res.mass = 0;
else
res.type = typeArg;
res.material = matArg;
res.prongs = prongsArg;
res.mass = massArg;
end
end
How would I go about creating that empty default structure if, say, only three input arguments are passed instead of the four? Thanks!

답변 (1개)

Nick
Nick 2018년 11월 8일
편집: Nick 2018년 11월 9일
This is easily solved using nargin: https://nl.mathworks.com/help/matlab/ref/nargin.html.
A small example
function res = createWidget(typeArg, matArg, prongsArg, massArg)
% set default values
res.type = '';
res.material = '';
res.prongs = 0;
res.mass = 0;
% set parameters based on number of inputs
for ii = 1:nargin % if nargin is 0 loop gets bypassed
switch ii
case 1
res.type = typeArg;
case 2
res.material = matArg;
case 3
res.prongs = prongsArg;
case 4
res.mass = massArg;
end
end
end
  댓글 수: 2
Guillaume
Guillaume 2018년 11월 8일
You don't even need the if nargin>0 since the loop will be entirely bypassed anyway if nargin is 0.
Nick
Nick 2018년 11월 9일
You are absolutely right. I never tried to give an empty vector to a for loop before so i assumed it would give an error. I updated my answer to match your comment. Thanks

이 질문은 마감되었습니다.

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by