How to use varargin: to specify a second input variable with separate output

6 visualizzazioni (ultimi 30 giorni)
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 Commento
Adam
Adam il 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)

Accedi per commentare.

Risposta accettata

Jos (10584)
Jos (10584) il 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

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by