compare variable with different data types

조회 수: 6 (최근 30일)
clauper
clauper 2023년 4월 14일
댓글: Adam Danz 2023년 4월 14일
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

채택된 답변

Stephen23
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
It is true
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
It is true
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
It is false
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
It is true
  댓글 수: 1
Adam Danz
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"])
str = "yes"
x = 'what?';
str = validatestring(x,["yes","no"])
Expected input to match one of these values:

'yes', 'no'

The input, 'what?', did not match any of the valid values.

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Rik
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
  댓글 수: 2
Adam Danz
Adam Danz 2023년 4월 14일
You could also define an enumeration class to recognize the options 1|0|true|false|Yes|No.
Rik
Rik 2023년 4월 14일
That would be a nice and neat solution, but I'm a freak (which in this case means I want to maintain compatibility with Matlab 6.5 and with Octave), so unfortunately this option is out. But it defenitely deserves an honorable mention.

댓글을 달려면 로그인하십시오.


Adam Danz
Adam Danz 2023년 4월 14일
  1. Detect if x is a string or character array
  2. Validate the string and convert it to a logical where yes==true
  3. 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

Antoni Garcia-Herreros
Antoni Garcia-Herreros 2023년 4월 14일
Hello,
You can take a look at the isa function to determine the datatype of x.
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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by