textscan in MATLAB: read NULL value as NaN

﹥>﹥吖頭↗ 提交于 2019-12-10 23:02:13

问题


I have a .txt file with the following data:

sampleF.txt --> (tab delimited)

MSFT    200    100
APPL    10    NULL
AMZN    20    40

I need to read this data using textscan. I am facing a problem while reading the NULL data. Using treatasempty param, I can read it as 0. But I want to read it as NaN. Please help! Thanks!

fName = '.....\sampleF.txt'
[fid, message] = fopen(fName) ;
if fid < 0, disp(message), else
    datatxt = textscan(fid, '%q %d %d', 'Delimiter', '\t','treatAsEmpty','NULL');
    datatxt = [ datatxt {1} num2cell(datatxt {2}) num2cell(datatxt {3})] ;
    fclose(fid) ; 
end

%datatxt = { 'MSFT' [200] [100] ; 'AAPL' [10] [NaN] ; 'AMZN' [20] [40] } 

回答1:


The problem is the fact that the type int32 does not support NaN values. Instead read the numbers as doubles. ie:

data = textscan(fid, '%s %f %f', 'Delimiter','\t', ...
           'treatAsEmpty','NULL', 'EmptyValue',NaN);


来源:https://stackoverflow.com/questions/6657963/textscan-in-matlab-read-null-value-as-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!