Why am I able to leave out the right-most arguments in a call to a function that doesn't need them under certain circumstances?

조회 수: 1 (최근 30일)
I am running R2018b - home use because I am working at home during the pandemic. Normally I would be using my licenced versions of MATLAB at NIST under the user email jon.geist@nist.gov. I have received permission from MATLAB to do this.
I hope that the behavior illustrated below is a feature and not a bug that will be corrected in future versions, but can find no justification for it. If this turns out to be an important issue, I can take the time to trim the actual script down to a reasonable size to send to you so you can run it.
Illustrative portions of large script ...
rg = horzcat(r331, C1, Xg, Yg, Zg); % size(r331)= 3x3, the others are 3x1
R = SimRespMeas(rg, alpha); % SimRespMeas has 3 more arguments
...
kag = horzcat(k, [1;1;1], [1;0;0], [0;1;0], [0;0;1]);
Model = @(kag, alpha) SimRespMeas(kag, alpha); % SimRespMeas has 3 more arguments
[Kag, resnorm,residual,exitflag,output,lambda,jacobian] = lsqcurvefit (Model,kag,alpha,R,[],[],opts);
...
function R = SimRespMeas(rg, alpha, Xg, Yg, Zg)
if size(rg,2) == 4
Xq = Xg;
Yq = Yg;
Zq = Zg;
elseif size(rg,2) == 7
Xq = rg(:,5)/sqrt(sum(rg(:,5).^2)); % Normalized for RRF
Yq = rg(:,6)/sqrt(sum(rg(:,6).^2));
Zq = rg(:,7)/sqrt(sum(rg(:,7).^2));
else
disp('size(rg,2) must be 4 or 7');
crash
end
Both calls to SimRespMeas work without the arguments Xg, Yg, and Zg and give the same answer as when these arguments are explicitly included in the call to the function. I was going to add them to the function call after I generized the function this way, but forgot to do so and was very surprised when it ran without them. Is there somewhere in the MATLAB literature that says that this is allowed, or should I always include the redundant argument values when running the code even when they are not needed?
Thanks, Jon Geist
end % function SimRespMeas

채택된 답변

Jon
Jon 2020년 10월 16일
This is a feature. As long as you don't do a calculation within the function that needs the missing variables it will not throw an error. You can use the function nargin to detemine how many input arguments you have and branch accordingly

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by