How to use varargin: to specify a second input variable with separate output
6 views (last 30 days)
Show older comments
I am trying to make a function that converts an amount of liters (first input variable) into mililiters by default. Additionally, the function coverts liters into microliters and nanoliters if a second input 'micro' or 'nano' is specified.
I am stuck with the varargin part.
The convertion from liters into microliters seem to work, but when I try the input 'nano' i get the following error:
Matrix dimensions must agree.
In the line:
if varargin{1} == 'micro'
How to solve this problem???
function [converted_value] = convertLiters_sterre(liters, varargin)
%%CONVERTLITERS converts value in liters to milliliters, microliters or
%%nanoliters.
if nargin == 0
error('No input');
elseif nargin == 1 && isnumeric(liters)
converted_value = liters*1000;
elseif nargin > 1
if varargin{1} == 'micro'
converted_value = liters*1000000;
elseif varargin{1} == 'nano'
converted_value = liters*1000000000;
else
error('Second input variable must be micro or nano');
end
else
error('First input must be an integer or an array of numbers');
end
1 Comment
Adam
on 29 Mar 2019
There may be other issues, but you should use
doc strcmp
to compare char arrays:
if strcmp( varargin{1}, 'micro' )
as a straight == will fail with the error you see if varargin{1} is not the same length as 'micro' and will still not give what you want even if they are the same length (you'll get a 5-element logical array)
Accepted Answer
Jos (10584)
on 29 Mar 2019
You cannot compare strings with different lengths using ==. Use isequal or strcmpi instead, for instance:
if isequal(lower(varargin{1}), 'nano')
% code here
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!