Specifying parameters for varargin

1 vue (au cours des 30 derniers jours)
Anne O'Neil
Anne O'Neil le 29 Fév 2016
I have a function that plots data using varargin as an input. Varargin can contain at least one of the following but nothing else - 'tomatoes', 'carrots', 'lettuce', 'blueberries', 'strawberries'. I have data relating to each one of these options that will be plotted. I can't figure out how to get it so the function will only accept inputs with some kind of combination of these. It has to be case insensitive so I know I have to use strcmpi, but I don't really know how to work with varargin

Réponses (1)

Matthew Eicholtz
Matthew Eicholtz le 29 Fév 2016
Modifié(e) : Matthew Eicholtz le 29 Fév 2016
Here's an example...
function fruitsandveggies(varargin)
validinputs = {'tomatoes', 'carrots', 'lettuce', 'blueberries', 'strawberries'};
mask = ismember(lower(varargin),lower(validinputs));
if ~all(mask)
error('Valid inputs are: %s',sprintf('%s ',validinputs{:}));
end
% insert additional code here
end
In this case, if the user enters one or more invalid inputs, the function gives an error.
fruitsandveggies('carrots') %works
fruitsandveggies('Strawberries','TOMATOES') %works
fruitsandveggies('carrots','lettuce','peas') %gives an error!
Is this what you were looking for?

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by