How to use varargin: to specify a second input variable with separate output
조회 수: 4 (최근 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!