How to use varargin: to specify a second input variable with separate output
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Sterre
am 29 Mär. 2019
Kommentiert: Adam
am 29 Mär. 2019
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 Kommentar
Adam
am 29 Mär. 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)
Akzeptierte Antwort
Jos (10584)
am 29 Mär. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!