loop storing only the last value, I want all values of the loop to be stored

1 visualización (últimos 30 días)
hi all,
I have a folder with 9 DAT files in it each DAT file has 3500 rows and 19 columns in it. I want to store all the dat files. MATLAB only stores the last value of the loop for me.
Any suggestion appreciated!
(I have read the previous relative q and answers, for some reason those did not work for me! )
d = uigetdir(pwd, 'Select a folder');
datfiles = dir(fullfile(d, '*.dat'));
for a = 1 : numel (datfiles)
fullfilename = datfiles(a).name;
Ts = load(fullfilename);
Ts [ , ] = Ts;
end

Respuesta aceptada

Voss
Voss el 10 de Nov. de 2021
Note that your assignment to Ts is independent of the loop iterator a, so each time through the loop Ts is assigned the contents of the current file, replacing what was in Ts before; this is why at the end of the loop Ts has only the values from the last file.
There's a couple different ways to keep the contents of all the files: you can make Ts a 3-dimensional array with the 3rd dimension being file index (a), or you can make Ts a cell array, with each element being a matrix containing the corresponding file's contents. (The three dimensional array is only an option when all the dat-file matrices are the same size, which is the case here.)
clear Ts
d = uigetdir(pwd, 'Select a folder');
datfiles = dir(fullfile(d, '*.dat'));
for a = 1 : numel (datfiles)
fullfilename = datfiles(a).name;
Ts(:,:,a) = load(fullfilename); % 3-D array option
% Ts{a} = load(fullfilename); % cell array option
end

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by