Readmatrix returns NaNs until a certain number of lines is reached in the text file.

8 次查看(过去 30 天)
Hi,
I'm trying to import data from a text file, and I realised, when my text file is "too short", the readmatrix function only returns NaNs.
In the following example, the only difference between both text files is that I repeated the last line in the file to make it work.
Do you have any ideas why the original file does not work ?
Thank you in advance,
Regards,
RB
Edit : base on Stephen23 comment, by decomposing and knowing in advance the structure of my file, I can resolve my problem by being more precise on the range definition. Thank you for your support.
bad = readmatrix('readmatrix_TEST_bad.txt','Range',[1 1]);
disp(bad(2,1))
NaN
good = readmatrix('readmatrix_TEST_good.txt','Range',[1 1]);
disp(good(2,1))
299741
%Solution
bad = readmatrix('readmatrix_TEST_bad.txt','Range',[2 1 7 6]);
disp(bad(1,1))
299741
good = readmatrix('readmatrix_TEST_good.txt','Range',[2 1 7 6]);
disp(good(1,1))
299741
bad = readmatrix('readmatrix_TEST_bad.txt','Range',[27 1]);
disp(bad(1,1))
-4.3862e-04
good = readmatrix('readmatrix_TEST_good.txt','Range',[27 1]);
disp(good(1,1))
-4.3862e-04
  1 个评论
Stephen23
Stephen23 2022-7-12
"Do you have any ideas why the original file does not work ?"
Because the textfile contains multiple numeric arrays of different sizes interspersed with multiple headers, and any automagical algorithm that tries to dectect headers, columns, data types, etc. can be easily confused by such a file. You provided READMATRIX with no help or hints (data range, types, etc.) which it could use to select a "reasonable" set of data from that file.
Perhaps READCELL would suit your needs better.
But what you actually need is a file parser for that file format (not a universal tool that tries its best).

请先登录,再进行评论。

采纳的回答

Rémy Bretin
Rémy Bretin 2022-7-12
编辑:Rémy Bretin 2022-7-12
Edit : base on Stephen23 comment, by decomposing and knowing in advance the structure of my file, I can resolve my problem by being more precise on the range definition. Thank you for your support.
%Solution
bad = readmatrix('readmatrix_TEST_bad.txt','Range',[2 1 7 6]);
disp(bad(1,1))
299741
good = readmatrix('readmatrix_TEST_good.txt','Range',[2 1 7 6]);
disp(good(1,1))
299741
bad = readmatrix('readmatrix_TEST_bad.txt','Range',[27 1]);
disp(bad(1,1))
-4.3862e-04
good = readmatrix('readmatrix_TEST_good.txt','Range',[27 1]);
disp(good(1,1))
-4.3862e-04

更多回答(0 个)

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by