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

5 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 12 Jul 2022
"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).

Sign in to comment.

Accepted Answer

Rémy Bretin
Rémy Bretin on 12 Jul 2022
Edited: Rémy Bretin on 12 Jul 2022
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

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!