compare variable with different data types
조회 수: 6 (최근 30일)
이전 댓글 표시
I would like to run different lines of code, depending on the value of x. However, x can be string, logical, or numerical.
The example bellow does not work because ismember only accepts string input. Is there another way that can compare x with multiple data types?
x="yes"; % x can be string, logical, or numerical
if ismember(x, {"yes", 1, true})
disp("It is true")
elseif ismember(x, {"no", 0, false})
disp("It is false")
end
댓글 수: 0
채택된 답변
Stephen23
2023년 4월 14일
편집: Stephen23
2023년 4월 14일
Here is a neat approach that also allows case-insensitivity:
x = 'Yes'; % x can be char, string, logical, or numerical
if strcmpi(string(x),"YES")||isequal(x,1)
disp("It is true")
else
disp("It is false")
end
x = true; % x can be char, string, logical, or numerical
if strcmpi(string(x),"YES")||isequal(x,1)
disp("It is true")
else
disp("It is false")
end
x = 0; % x can be char, string, logical, or numerical
if strcmpi(string(x),"YES")||isequal(x,1)
disp("It is true")
else
disp("It is false")
end
With STRNCMPI you can make it also accept partial "Y", "y", "N"; etc.:
x = "y"; % x can be char, string, logical, or numerical
s = string(x);
if strncmpi(s,"YES",strlength(s))||isequal(x,1)
disp("It is true")
else
disp("It is false")
end
댓글 수: 1
Adam Danz
2023년 4월 14일
You could even use
if strcmpi(string(x),"YES")||x
One thing I like about validatestring is that in addition to supporting partial matches and case insensitivity, it also casts the input string to the clas specified by the valid string list (char/string) and throws a helpful error message when the input string does not match one of the options.
x = "yES";
str = validatestring(x,["yes","no"])
x = 'what?';
str = validatestring(x,["yes","no"])
추가 답변 (3개)
Rik
2023년 4월 14일
편집: Rik
2023년 4월 14일
I use the function below. Since loops are fast, I just loop through all the options.
I use this for input validation, so this order of outputs makes most sense for my use. For your use you may consider swapping the output arguments.
function [isLogical,val]=test_if_scalar_logical(val)
%Test if the input is a scalar logical or convertible to it.
% The char and string test are not case sensitive.
% (use the first output to trigger an input error, use the second as the parsed input)
%
% Allowed values:
% - true or false
% - 1 or 0
% - 'on' or 'off'
% - "on" or "off"
% - matlab.lang.OnOffSwitchState.on or matlab.lang.OnOffSwitchState.off
% - 'enable' or 'disable'
% - 'enabled' or 'disabled'
persistent states
if isempty(states)
states = {...
true,false;...
'true','false';...
1,0;...
'1','0';...
'on','off';...
'enable','disable';...
'enabled','disabled'};
% We don't need string here, as that will be converted to char.
end
% Treat this special case.
if isa(val,'matlab.lang.OnOffSwitchState')
isLogical = true;val = logical(val);return
end
% Convert a scalar string to char and return an error state for non-scalar strings.
if isa(val,'string')
if numel(val)~=1,isLogical = false;return
else ,val = char(val);
end
end
% Convert char/string to lower case.
if isa(val,'char'),val = lower(val);end
% Loop through all possible options.
for n=1:size(states,1)
for m=1:2
if isequal(val,states{n,m})
isLogical = true;
val = states{1,m};
return
end
end
end
% Apparently there wasn't any match, so return the error state.
isLogical = false;
end
Adam Danz
2023년 4월 14일
- Detect if x is a string or character array
- Validate the string and convert it to a logical where yes==true
- Use a conditional statement to detect if x is true (works for logicals and numerics)
if isstring(x) || ischar(x)
yesno = validatestring(x,{'yes','no'});
x = strcmp(yesno,'yes');
end
if x
disp('It is true')
else
disp('It is false')
end
댓글 수: 0
Antoni Garcia-Herreros
2023년 4월 14일
Hello,
Something like this should do the trick:
if isa(x,'char')
if strcmp(x,'yes')
disp("It is true")
else
disp("It is false")
end
elseif isa(x,'logical')
if x
disp("It is true")
else
disp("It is false")
end
elseif isa(x,'numeric')
if x==1;
disp("It is true")
else
disp("It is false")
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!