Matlab Set i=1:文件结束
我试图让MATLAB读取一个文件列表。但是,我有几个这些文件的列表,它们的长度都不同。如何为循环设置Matlab Set i=1:文件结束,matlab,for-loop,Matlab,For Loop,我试图让MATLAB读取一个文件列表。但是,我有几个这些文件的列表,它们的长度都不同。如何为循环设置,使I从1到文件末尾?(我说的这一行是‘for I=1:文件结束’部分 为了举例说明,my.dat文件的前几行如下所示: 2006-01-003-0010.mat 2006-01-027-0001.mat 2006-01-033-1002.mat 2006-01-051-0001.mat 2006-01-055-0011.mat for y = 1:9 flist = fopen([num2st
,使I
从1到文件末尾?(我说的这一行是‘for I=1:文件结束’部分
为了举例说明,my.dat文件的前几行如下所示:
2006-01-003-0010.mat
2006-01-027-0001.mat
2006-01-033-1002.mat
2006-01-051-0001.mat
2006-01-055-0011.mat
for y = 1:9
flist = fopen([num2str(year(y))'_MDA8_mat.dat']); % Open the list of file names - CSV files of states with data under consideration
nt = 0; % Counter will go up one for each file loaded
while ~feof(flist) % While end of file has not been reached
for i = 1:END OF FILE % Number of files CHECK EACH TIME FILE IS MODIFIED
fname = fgetl(flist); % Reads next line of list, which is the name of the next data file
disp(fname); % Stores name as string in fname
nt = nt+1; % Time index
load (fname, 'site_data'); % Load current file. It is all the data for one site for one year
O3_data{i} = site_data;
% Stuff
end
end
我的代码如下所示:
2006-01-003-0010.mat
2006-01-027-0001.mat
2006-01-033-1002.mat
2006-01-051-0001.mat
2006-01-055-0011.mat
for y = 1:9
flist = fopen([num2str(year(y))'_MDA8_mat.dat']); % Open the list of file names - CSV files of states with data under consideration
nt = 0; % Counter will go up one for each file loaded
while ~feof(flist) % While end of file has not been reached
for i = 1:END OF FILE % Number of files CHECK EACH TIME FILE IS MODIFIED
fname = fgetl(flist); % Reads next line of list, which is the name of the next data file
disp(fname); % Stores name as string in fname
nt = nt+1; % Time index
load (fname, 'site_data'); % Load current file. It is all the data for one site for one year
O3_data{i} = site_data;
% Stuff
end
end
请尝试以下代码:
for y = 1:9
flist = fopen([num2str(year(y))'_MDA8_mat.dat']); % Open the list of file names - CSV files of states with data under consideration
while ~feof(flist) % While end of file has not been reached
newFileName = fgetl(flist);
fid = fopen(newFileName);
while ~feof(fid)
currentLine = fgetl(fid);
% Do stuff on each sub-file
end
fclose(fid);
end
flcose(flist);
end
您还可以执行以下操作:
flist = fopen([num2str(year(y))'_MDA8_mat.dat']);
line = fgetl(flist);
while(ischar(line))
%Do process (like open next file with the line variable)
%read the next line
line = fgetl(flist);
end
首先,尽量避免在matlab中使用i作为迭代变量。i通常是虚数。在您的While eof中,您已经在文件中循环,所以只需逐行读取,直到这段时间结束。当您读取一行时,假设它是一个新的文件名?所以只需启动另一个fopen并读取它。matlab提供了您需要的内容,您就有了一个新的文件名小示例如何在文件中循环。我需要循环文件本身中的内容。y
只循环每个.dat
文件,但每个.dat
文件都有一个长的文件列表。我可以使用I
以外的内容,但是当某个内容I=1:something
e> 是由文件的长度决定的?我是否需要为两个循环设置两个计数器(thent=nt+1;
)?不,对不起,我复制了您的代码并没有删除它。在第二个计数器中,只需执行fgetl(fid)即可读取当前文件中的内容。