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
1 个评论
采纳的回答
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
1 个评论
Jon
2020-10-16
Here's a good reference on variable number of function argumentshttps://www.mathworks.com/help/matlab/input-and-output-arguments.html?s_tid=CRUX_lftnav
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!