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 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!