compare variable with different data types

9 Ansichten (letzte 30 Tage)
clauper
clauper am 14 Apr. 2023
Kommentiert: Adam Danz am 14 Apr. 2023
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

Akzeptierte Antwort

Stephen23
Stephen23 am 14 Apr. 2023
Bearbeitet: Stephen23 am 14 Apr. 2023
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 Kommentar
Adam Danz
Adam Danz am 14 Apr. 2023
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (3)

Rik
Rik am 14 Apr. 2023
Bearbeitet: Rik am 14 Apr. 2023
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 Kommentare
Adam Danz
Adam Danz am 14 Apr. 2023
You could also define an enumeration class to recognize the options 1|0|true|false|Yes|No.
Rik
Rik am 14 Apr. 2023
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.

Melden Sie sich an, um zu kommentieren.


Adam Danz
Adam Danz am 14 Apr. 2023
  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 am 14 Apr. 2023
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

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by