if function works in one table but not in another

조회 수: 1(최근 30일)
Tobias Kleinert
Tobias Kleinert 2022년 5월 12일
댓글: Tobias Kleinert 2022년 5월 12일
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 Tab{1,2} == 'a'
output(1,1) = 1
output(1,1) = 0
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
markerinfo(eventsN,1) = 0
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

채택된 답변

Walter Roberson
Walter Roberson 2022년 5월 12일
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
Tobias Kleinert
Tobias Kleinert 2022년 5월 12일
Thank you so much Walter! I converted to categorical and life is good again.

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

추가 답변(1개)

Dyuman Joshi
Dyuman Joshi 2022년 5월 12일
Use isequal or strcmp if you are comparing the whole string.
Use ismember or array indexes if you want to compare partial string.

Community Treasure Hunt

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

Start Hunting!

Translated by