Keeping Some MATLAB Function Input Arguments Inactive
显示 更早的评论
I have a function which takes 11 pairs of input arguments (each pair representing a type of process and an input commodity) and calculates a result based on all of those 22 values. However, I would like to make the function flexible such that if I wanted to use, for example, 3 pairs of input arguments rather than 11, it would still come up with a result and meanwhile ignore the other 8 pairs of unused arguments. Can you please tell me the simplest way to do that?
I've tried using varargin but when I pass fewer than 22 values as the input arguments, MATLAB tells me that the 'the (varargin) index (in the function file) exceeds the marix dimensions.'
Is there any way to pass 'inactive' input arguments so that MATLAB simply doesn't perform any operation on them?
Thanks.
2 个评论
dpb
2013-8-4
How about using a structure instead of so many individual elements--keeping track of that many individual arguments has got to be a real pita both in writing code and particularly in trying to use any such function in the end.
As for "ignoring" any inputs, you have to write the logic to only use what is there and if an argument is expected by being in the argument list then that's what you've told Matlab to expect so there isn't any other option. You can, of course, assign default values and use those but again it has to be coded.
You didn't show any code to see why the error--the vargin argument is just a cell array containing the optional arguments so if you tried to use some fixed index as a positional indication of which one is/isn't there then you could easily have been outside the range of those that were passed. That's what the value nargin tells you--how many actually were passed; you can't access more than that. But, while that tells you how many were passed you don't know what they're supposed to be unless you have some identification of them.
That's why the named structure would work or why/how the lists of properties/values in such functions as plot work--see the
doc varargin
for example of that syntax/description of how they're used.
Usman
2013-8-4
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!