Reading multiple files

10 次查看(过去 30 天)
Sofia
Sofia 2012-5-27
Hello,
i´m writing a program that is supposed to read several files called regiao(1 through 10).txt. This is my program:
regiao=dir('regiao*.txt');
for k=1:10;
nome=regiao(k).name;
id=fopen(nome,"r");
while !feof(id)
for f=1:length(coluna);
[semana,infectados,mortes]=fscanf(id,"%s%s%s","C");
if !isempty(semana);
l(f).semana=semana;
l(f).infectados=infectados;
l(f).mortes=mortes;
f=f+1;
endif
endfor
endwhile
endfor
fclose(id);
endfunction
And this is what the .txt files look like:
Populacao:11000
Semana Infectados Mortes
8 29 13
35 290 148
My problem is that instead of retrieving all the information in the columns from all ten files my function only gets one value from each column. Can anyone help me?

采纳的回答

Andrei Bobrov
Andrei Bobrov 2012-5-28
try
regiao=dir('regiao*.txt');
for k=1:10;
nome=regiao(k).name;
id=fopen(nome,'r');
nms = textscan(id,'%s',4);
d = textscan(id,'%f %f %f',4);
fclose(id);
fd = regexp(nms{1}{1},'\w*','match');
dd = [fd(1), str2double(fd(2)); nms{1}(2:end), d']';
l(k) = struct(dd{:})
end

更多回答(1 个)

Walter Roberson
Walter Roberson 2012-5-27
1) Your code is not MATLAB. MATLAB does not have "endif", or "endfor" or "endwhile"
2) What is "coluna" ?
3) index your "l" at (k,f) rather than at (f) alone, or else you end up overwriting "l" on every file.
4) The "f=f+1" is not useful there as you are in a "for f" loop.

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by