compare variable with different data types

9 次查看(过去 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

采纳的回答

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
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