readtable and strcmp returning 0 all the time

4 ビュー (過去 30 日間)
Mini Me
Mini Me 2016 年 11 月 17 日
コメント済み: Peter Perkins 2016 年 11 月 18 日
I am comparing a string that is in my excel csv file that I read in matlab using readtable because it has numbers and strings with special characters in it.
I set my string: Str = 'var'
keep in mind in readtable in the excel sheet there's no ' ' around the string but readtable inserts it.
now I am trying to compare my string to what's in readtable an it keeps returning 0 when it should be 1.
The data in the table always display the header, may that be the reason why it never matches the string? How can I fix it?
fid = readtable('filename')
C = zeros(1,size(fid,1));
Str = 'var';
for k = 1: 10
tf=strcmp(fid(k,28), Str ) ;
if tf == 1
C(k) = Yes;
else
C(k) = No;
end
end

採用された回答

Walter Roberson
Walter Roberson 2016 年 11 月 17 日
The basic problem that you are having is that fid(k,28) is a table not the contents stored at that location. You need fid{k,28} to get the contents.
A shorter version of your code would be to remove the for loop and
vals = [No, Yes];
C(1:10) = vals( 1 + strcmp(fid{1:10,28}, Str) );
If No is 0 and Yes is 1 then
C(1:10) = strcmp(fid{1:10,28}, Str);
  3 件のコメント
Walter Roberson
Walter Roberson 2016 年 11 月 17 日
Those are two different ways. The second single-line version is appropriate only in the case where No == 0 and Yes == 1.
Peter Perkins
Peter Perkins 2016 年 11 月 18 日
Without meaning to muddy the waters, if you're only accessing one variable in the table at a time, you might find that
fid.Var28(1:10)
is more readable than
fid{1:10,28}
Some people prefer the dot to the braces. In any case, one of the benefits of tables is that you can use a meeaningful name, rather than a number like 28. So even
fid{k,'Var28'}
might be preferable. Of course, "Var28' probably isn't the name that readtable will create from the file, you would use whatever that is.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by