How to overwrite 'NaN' strings in a table using the for-loop
Show older comments
I want to replace the strings 'NaN' with NaN in my table using a loop / or any other strategy that returns NaN, leaving all else unchanged. Here my code:
for k = 1:height(Z_24TimeSteps)
if isnan(Z_24TimeSteps{k})
Z_24TimeSteps{k} = nan;
end
end
Table:

Another strategy I tried:
Z_24TimeSteps(cellfun(@isnan,Z_24TimeSteps))=nan;
How can I use this rationale for the "table" format?
Screenshot of .xlsx file to be imported:

Accepted Answer
More Answers (1)
Peter Perkins
on 12 Jan 2017
You almost certainly don't want to the specific thing you've stated, i.e. "replace the strings 'NaN' with NaN". You'd end up still having a cell array, which isn't usually a good way to store numbers. I think you want to address the root cause.
Excel does not have any notion of NaN. So I'm guessing those those NaNs in your screenshot are text fields in the spreadsheet. That may be contributing to this. It's hard to say exactly how you got to where you are because there are different ways you could call readtable, and readtable itself has seen improvements for interpreting spreadsheets over the last few releases. It is probably possible to read things into MATLAB in the right form, but I think you're going to have to provide a small example that's exactly like what you have and what you've done.
One work-around might be to save the .xlsx as a .csv and read it as a text file. Another would be to loop over the vars in the table and convert them to numeric. Something like
for i = indicesOfTheVarsToConvert name = t.Properties.VariableNames{i}; t.(name) = convertToNumeric(t.(name)); end
where convertToNumeric is a function you'll write to convert those cell arrays to numeric. It may be something along these lines:
>> c = {'NaN' 'NaN' 1 2 3}
c =
1×5 cell array
'NaN' 'NaN' [1] [2] [3]
>> j = strcmp(c,'NaN')
j =
1×5 logical array
1 1 0 0 0
>> c(j) = {NaN}
c =
1×5 cell array
[NaN] [NaN] [1] [2] [3]
>> cell2mat(c)
ans =
NaN NaN 1 2 3
Hope this helps.
Categories
Find more on Data Type Identification in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!