fileID doesn't update when importing data using for loop

18 visualizaciones (últimos 30 días)
Kris Longmore
Kris Longmore el 9 de Abr. de 2015
Comentada: Adam el 9 de Abr. de 2015
I'm using Matlab's import data code generator to pass data to a series of commands. This works fine when I run the script and reference a single file, but if I loop through several files, my variables aren't updated as I expect. I believe I have traced the problem to 'fileID' not updating after the first iteration of the loop.
In the code below, I can confirm that 'filename' is updated with each iteration of the loop, while 'fileID' is not. Consequently, the same vector is assigned to the variable 'y' in each iteration.
Can anyone suggest where I am going wrong?
FileList = dir('*.csv');
N = size(FileList,1);
for k = 1:N
% get the file name:
filename = FileList(k).name;
delimiter = ',';
startRow = 2;
%%Format string for each line of text:
% column2: double (%f)
% column3: double (%f)
% column4: double (%f)
% column5: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%*s%f%f%f%f%[^\n\r]';
%%Open the text file.
fileID = fopen(filename,'r');
%%Read columns of data according to format string.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'HeaderLines' ,startRow-1, 'ReturnOnError', false);
%%Close the text file.
fclose(fileID);
%%Allocate imported array to column variable names
O1 = dataArray{:, 1};
H1 = dataArray{:, 2};
L1 = dataArray{:, 3};
C1 = dataArray{:, 4};
%%Test filename and fileID
filename
fileID
%%Clear temporary variables
clearvars filename delimiter startRow formatSpec fileID dataArray ans;
y=C1;
figure
plot(y);
end
  1 comentario
Adam
Adam el 9 de Abr. de 2015
I can't see anything wrong at a glance with that. fileID is clearly getting re-assigned though if you get the same data each time because if it weren't it would be at the end of the file next time round and read in nothing.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Low-Level File I/O 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