- 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
if function works in one table but not in another
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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:
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!