Replacing values in a cell with NaN

39 ビュー (過去 30 日間)
Caroline
Caroline 2017 年 1 月 28 日
コメント済み: Image Analyst 2017 年 1 月 29 日
Hello community, I am new to Matlab, so still struggling with the apparently easy stuff. I have a 435x2 cell with text and numbers called "Data". The first column consists of text, the second column consists of numbers. My goal is to replace -1 values in the second column by NaN. What I have so far:
for i = 1:length(Data)
if Data{i,2} == -1
Data{i,2} = NaN
end
end
I do not get any error message. However, nothing gets replaced either. What am I missing or how can it be done more efficiently? Remember, I am just learning Matlab, so an easy solution would be cool :) Thank you!
  1 件のコメント
Image Analyst
Image Analyst 2017 年 1 月 29 日
You should not use a cell array for this type of variable, where all the values in a single column are of the same type. You should use a table, which uses lots less memory and overhead than a cell array.

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

採用された回答

John Chilleri
John Chilleri 2017 年 1 月 28 日
編集済み: John Chilleri 2017 年 1 月 29 日
Hello,
Your code works for me, although I would recommend using
for i = 1:size(Data,1)
rather than
for i = 1:length(Data)
since Data is a 435x2, and you don't want to accidentally use the wrong dimension in the future.
As for your issue, the only thing that makes sense to me is that you've stored your numbers as strings rather than doubles, making the comparison do nothing.
Try,
for i = 1:length(Data)
if strcmp(Data{i,2},'-1')
Data{i,2} = NaN
end
end
If this works, then your -1's were strings rather than doubles.
Hope this helps!
  3 件のコメント
Jan
Jan 2017 年 1 月 28 日
Its good idea, that the numbers have been stored as string, John! +1
You can omit the "==1" after the strcmp, because this command replies a logical already.
John Chilleri
John Chilleri 2017 年 1 月 29 日
編集済み: John Chilleri 2017 年 1 月 29 日
I'll edit the above code - thank you for your input Jan, I hadn't considered that!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by