Need help with this error using fscanf

6 visualizaciones (últimos 30 días)
Timothy Monroe
Timothy Monroe el 30 de Mzo. de 2020
Comentada: Walter Roberson el 30 de Mzo. de 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 comentario
Timothy Monroe
Timothy Monroe el 30 de Mzo. de 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

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 30 de Mzo. de 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 comentarios
Timothy Monroe
Timothy Monroe el 30 de Mzo. de 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 el 30 de Mzo. de 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};

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Entering Commands en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by