if function works in one table but not in another

1 view (last 30 days)
Hey community,
I wan to use an extremely simple if-function on two tables (one self-made, the other imported). Everything works fine for the self-made table, but not for the imported table. Error messa: Operator '==' is not supported for operands of type cell). Here's the table, the code to construct it, and the if-function - works fine.
%Create table
numb = [1;2;3;4;5;6;7];
string = ['a';'b';'c';'d';'e';'f';'g'];
Tab = table(numb, string)
%if-function
if Tab{1,2} == 'a'
output(1,1) = 1
else
output(1,1) = 0
end
Now here's my imported table, and the if function - doesn't work.
%If-function for imported table (It should be analogous o the previous one.
for eventsN = 1:height(eventsTable)
if eventsTable{eventsN,7} == 'AZ'
markerinfo(eventsN,1) = 1
else
markerinfo(eventsN,1) = 0
end
end
I also double-checked that both are class table (using the whos function, also visible in the figures of the tables. This drives me crazy, WHAT IS MY MISTAKE HERE??? Thanks in advance for any help

Accepted Answer

Walter Roberson
Walter Roberson on 12 May 2022
Your constructed table passes in a fixed-width character array for the second variable, which results in each entry being a scalar character. Using == to compare a scalar character to a single character constant works.
Your imported table has variable width character vectors. The table important routines do not use fixed width character arrays unless you override the defaults. Instead they import as cell array of character vectors (with an option to use string objects instead).
It is a mistake to use == to compare non-scalar character vectors that could be different lengths. Character vectors are treated the same as numeric vectors. You would not use [63 61 62] == [62 61] because those are different lengths, and you should not be considering 'CAB' == 'BA' because they are different lengths.
You have four major options:
  • use strcmp or strcmpi
  • use ismember
  • convert to string objects. "CAB" == "BA" is valid for string objects. readtable has options for importing text as string objects
  • convert to categorical. readtable has options for importing text as categorical
  1 Comment
Tobias Kleinert
Tobias Kleinert on 12 May 2022
Thank you so much Walter! I converted to categorical and life is good again.

Sign in to comment.

More Answers (1)

Dyuman Joshi
Dyuman Joshi on 12 May 2022
Use isequal or strcmp if you are comparing the whole string.
Use ismember or array indexes if you want to compare partial string.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!