Need help with this error using fscanf

9 Ansichten (letzte 30 Tage)
Timothy Monroe
Timothy Monroe am 30 Mär. 2020
Kommentiert: Walter Roberson am 30 Mär. 2020
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 Kommentar
Timothy Monroe
Timothy Monroe am 30 Mär. 2020
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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 30 Mär. 2020
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 Kommentare
Timothy Monroe
Timothy Monroe am 30 Mär. 2020
I ahve 4 columns of data how would I use that methods on more than 2 and keep them separate?
Walter Roberson
Walter Roberson am 30 Mär. 2020
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};

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Entering Commands finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by