How to use varargin: to specify a second input variable with separate output
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam
2019-3-29
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)
采纳的回答
Jos (10584)
2019-3-29
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!