Scalar assignment and nargout bump
조회 수: 2 (최근 30일)
이전 댓글 표시
I am trying to do the following:
s = [objs.s] % s may be a struct array (really object array) or empty []
[s.prop] = assignToStructureArray(scalar_value);
where
function varargout = assignToStructureArray(value)
varargout(1:nargout) = {value};
end
This works fine unless s is empty, in which case nargout is 1, not 0 and suddenly s is no longer empty.
This brought me to Loren's Blog post which greatly confuses me. http://blogs.mathworks.com/loren/2009/04/14/convenient-nargout-behavior/
I'm really having trouble understanding why the nargout bump is a good idea. It seems to me like this is just another Matlab corner case that while sometimes convenient is not a good idea.
Any help on understanding the post and more importantly, on how to change the code to work without having to resort to an if statement before making the function call that checks whether s is empty or not would be great.
Thanks, Jim
댓글 수: 3
Matt J
2013년 8월 14일
편집: Matt J
2013년 8월 14일
My goal is to write a function which removes the initial setup of performing deal. Those steps are replication and then transfering data to a cell format so that they can be passed in as multiple inputs to deal.
I'm not sure when this comment occurred in the flow of our conversation, but hopefully you're now aware that it is not necessary to replicate scalars with deal(). The single line of code
[s(1:n).prop]=deal(scalar)
will distribute the scalar n times exactly as you would hope.
채택된 답변
Matt J
2013년 8월 14일
편집: Matt J
2013년 8월 14일
To me, a better justification (if there is one) for the nargout bump is to make it easier to write wrappers for the many builtin functions tht always return at least 1 argument, even when called with nargout=0. For example, at the command line, SORT always returns at least one output arg, even when one is not explicitly requested,
>> sort([5 1 3]) % call with no arguments
ans =
1 3 5
Suppose I now want to write a wrapper for sort() such that its 2nd argument returns 0-based indices instead of 1-based indices. Then I can do so, while preserving the above behavior, as easily as
function varargout=mysort(varargin)
[varargout{1:nargout}]=sort(varargin{:});
if nargout>1, varargout{2}=varargout{2}-1;
end
whereas without the bump, I would have to do something more complicated,
function varargout=mysort(varargin)
[varargout{1:max(1,nargout)}]=sort(varargin{:});
if nargout>1, varargout{2}=varargout{2}-1;
end
to ensure that at least one output arg was always returned. To my tastes, I would rather endure the second syntax for consistency's sake, but maybe that's just me...
댓글 수: 4
Matt J
2013년 8월 16일
It isn't clear how anonymous functions come into play with this. Any thoughts on that?
Nope. It was unclear to me, too.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Argument Definitions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!