Reading multiple files

10 visualizzazioni (ultimi 30 giorni)
Sofia
Sofia il 27 Mag 2012
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?

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 28 Mag 2012
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

Più risposte (1)

Walter Roberson
Walter Roberson il 27 Mag 2012
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.

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by