How to use varargin names to specify values
4 views (last 30 days)
Show older comments
I want to be able to use varargins like plot does, where you have to write the variable name for the variable being specified before defining a value for it, e.g.
plot(x, y, '--rs', 'LineWidth', 4, 'MarkerSize', 10, 'MarkerEdgeColor', 'b')
where 'LineWidth', 'MarkerSize' and 'MarkerEdgeColor' are the variables being changed and 4, 10 and 'b' are the values being assigned to these variables.
I want to know how they do this, so I can implement it into my own code. Is it just a case of doing
if(~isempty(varargin))
for i = 1:size(varargin, 2) - 1
if(strcmp(varagin{i}, 'LineWidth')
LineWidth = varargin{i+1};
elseif(strcmp(varargin{i}, 'MarkerSize')
MarkerSize = varargin{i+1};
elseif(strcmp(varargin{i}, 'MarkerEdgeColor')
MarkerEdgeColor = varargin{i+1};
end
end
end
or is there a simpler way of doing this? The above method feels really clunky and long winded, so having a quicker method would be ideal.
1 Comment
Stephen23
on 29 Jun 2017
Edited: Stephen23
on 29 Jun 2017
"The above method feels really clunky and long winded"
It is clunky, and it will not expand easily, for the reasons explained here: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
"or is there a simpler way of doing this?"
See my FEX submission num2words for one example of how to do this. I convert the varargin into a structure (this is trivial using struct), and then parse that structure, providing default values where required.
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!