Append Column from Loaded Data to Matrix in a Loop
Show older comments
Hi, I am trying to load data into a matrix. Every iteration should result in a new column. My code currently appends everything in 1 column as a new row.
Open to any simplifications or suggestsions! I am new to matlab and have been using this load code as my go-to.
TYIA
spectra_dir = uigetdir; %gets directory
my_spectras = dir(fullfile(spectra_dir,'RSN*.txt')); %gets all txt files in struct
spectras_load = []; %creates matrix from data in each vector
for k = 1:length(my_spectras)
baseFileName = my_spectras(k).name;
fullFileName = fullfile(spectra_dir, baseFileName);
spectra_file = load(fullFileName);
psa_spectra = spectra_file(:, 2);
spectras_load = [spectras_load; {psa_spectra}];
end
spectras = cell2mat(spectras_load);
Answers (1)
the cyclist
on 7 Mar 2022
Changing this
spectras_load = [spectras_load; {psa_spectra}];
to this
spectras_load = [spectras_load, {psa_spectra}]; % Notice use of comma rather than semicolon
Beware aware that building arrays by adding columns is very inefficient for memory management, and can become very slow. You could use preallocation to speed this code.
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!