Need help with this error using fscanf

조회 수: 15 (최근 30일)
Timothy Monroe
Timothy Monroe 2020년 3월 30일
댓글: Walter Roberson 2020년 3월 30일
I am creating a loop to read a rather large multi column txt file and change the 2 digit date to 4 digit and my scan function is returning an error in line 6 the first line fscanf is used I am sure its in my syntax used there. Any help is much appreciated!!!
fid=fopen('test.txt', 'r')
while ~feof(fid)
tline=fgetl(fid);
Year=fscanf(fid,'%g',[1 1:2:inf]);
Month=fscanf(fid,'%g',[1 2:2:inf]);
Lowtemp=fscanf(fid,'%g',[1 2:2:inf]);
Hightemp=fscanf(fid,'%g',[1 2:2:inf]);
Precip=fscanf(fid,'%g',[1 2:2:inf]);
Year=Year + 1900
end
fileID = fopen('newtxt.txt','w');
fprintf(fileID, 'Year Month LowTemp HighTemp Precip\n');
fprintf(fileID,'%g %g %g %g %g\n',Year,Month,Lowtemp,Hightemp,Precip);
fclose(fileID);
_____________
>> temphw
fid =
9
Maximum variable size allowed by the program is exceeded.
Error in temphw (line 6)
Year=scanf(fid,'%g',[1 1:2:inf]);
  댓글 수: 1
Timothy Monroe
Timothy Monroe 2020년 3월 30일
And my .txt file looks like this.
Yr Mnth LowTemp(deg F) HighTemp(deg F) Precip(in)
89 Jan 52.4 70.1 2.27
89 Feb 53.8 71.6 2.67
89 Mar 58.5 76.3 2.84
89 Apr 62.4 80.6 1.80
89 May 68.9 86.3 2.85

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 3월 30일
The size parameter for fscanf can be a scalar, or it can be a vector of values representing an array dimensions. It cannot be used to tell MATLAB to only write to every second output column, and it cannot be used to tell MATLAB to skip scanning input columns. It also cannot be used to tell MATLAB to go back and re-read a different part of the same line.
If you had reason to only read in every second value, then you can use
fscanf(fid, '%g %*s', [1 inf]) %reads odd-numbered columns, discards even-numbered
fscanf(fid, '%*s %g', [1 inf]) %reads even-numbered columns, discards odd-numbered
If you need odd and even in separate variables, then
xy = fscanf(fid, '%g %g', [2 inf]);
x = xy(1,:);
y = xy(2,:);
  댓글 수: 2
Timothy Monroe
Timothy Monroe 2020년 3월 30일
I ahve 4 columns of data how would I use that methods on more than 2 and keep them separate?
Walter Roberson
Walter Roberson 2020년 3월 30일
89 Jan 52.4 70.1 2.27
fid=fopen('test.txt', 'r')
oc = textscan(fid, '%f%s%g%g%g');
fclose(fid);
Year = oc{1};
Month = oc{2};
Lowtemp = oc{3};
Hightemp = oc{4};
Precip = oc{5};

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by