- 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
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Tobias Kleinert
il 12 Mag 2022
Commentato: Tobias Kleinert
il 12 Mag 2022
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/995550/image.png)
%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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/995555/image.png)
%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 Commenti
Risposta accettata
Walter Roberson
il 12 Mag 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:
Più risposte (1)
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!