loop storing only the last value, I want all values of the loop to be stored
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Narges Raee
am 10 Nov. 2021
Bearbeitet: Image Analyst
am 11 Nov. 2021
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
0 Kommentare
Akzeptierte Antwort
Voss
am 10 Nov. 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
0 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!