Whitespace Delimited Textfile, NaN results?

조회 수: 5 (최근 30일)
Sage Hayes
Sage Hayes 2021년 10월 28일
답변: Walter Roberson 2021년 10월 28일
Hi, so I'm having trouble reading this delimited textfile. It's whitespace delimited columns with rows being indicated by carriage returns.
So far I've been trying to read it through this method:
clear all;
close all;
fid = fopen('test.txt', 'rt');
%make headers
tline = fgetl(fid);
headers = strsplit(tline, ','); %a cell array of strings
%make data
datacell = textscan(fid,'%f%f%f%f', 'Delimiter',' ', 'CollectOutput', 1);
fclose(fid);
datavalues = datacell{1}; %as a numeric array
However this has resulted in a bunch of NaN's inserted into the matrix (Capture.PNG).
Any help would be greatly appreciated.

채택된 답변

per isakson
per isakson 2021년 10월 28일
편집: per isakson 2021년 10월 28일
The problem is caused by 'Delimiter',' ' in
datacell = textscan(fid,'%f%f%f%f', 'Delimiter',' ', 'CollectOutput', 1);
in combination with two spaces between the third and the fourth column in the text file.
Try
datacell = textscan( fid,'%f%f%f%f', 'CollectOutput', 1);
and let Matlab take care of the problem or
datacell = textscan(fid,'%f%f%f%f', 'Delimiter',' ', 'CollectOutput',1, 'MultipleDelimsAsOne',true);

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 10월 28일
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/781593/test.txt';
datavalues = readmatrix(filename)
datavalues = 16×4
1.0e+05 * -0.0000 0 -0.0000 4.2263 -0.0000 0 -0.0000 4.0334 -0.0000 0 -0.0000 3.9879 -0.0000 0 -0.0000 4.0397 -0.0000 0 -0.0000 4.1445 -0.0000 0 -0.0000 4.2644 -0.0000 0 -0.0000 4.3675 -0.0000 0 -0.0000 4.4280 -0.0000 0 -0.0000 4.4264 -0.0000 0 -0.0000 4.3490

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by