how to input data into an array from csv files in a for loop

6 views (last 30 days)
I have some csv files broken up and I want to concatenate them all into one big array but I dont want to input them one by one like the commented out code, is there a way to do this? Thank you
Birth1 = 5.6;
Death1 = 1;
for i = 1:17
na = sprintf('Birth2_%g',i);
str = sprintf('Birth2_Cons_muj_%g_bj_%g_Part_%g.csv',Death1,Birth1,i);
na = readmatrix(str);
end
% Birth2_1= readmatrix('Birth2_Cons_muj_1_bj_5.6_Part_1.csv');
% Birth2_2= readmatrix('Birth2_Cons_muj_1_bj_5.6_Part_2.csv');
Birth2 = [Birth2_1 Birth2_2 Birth2_3 Birth2_4 Birth2_5 Birth2_6 Birth2_7 Birth2_8 Birth2_9 Birth2_10 Birth2_11 Birth2_12 Birth2_13 Birth2_14 Birth2_15 Birth2_16 Birth2_17];
When I run the above code I get an error:
Unrecognized function or variable 'Birth2_1'.
Error in concatenating_matrices (line 14)
Birth2 = [Birth2_1 Birth2_2 Birth2_3 Birth2_4 Birth2_5 Birth2_6 Birth2_7 Birth2_8 Birth2_9 Birth2_10 Birth2_11 Birth2_12 Birth2_13 Birth2_14 Birth2_15 Birth2_16 Birth2_17];%

Accepted Answer

dpb
dpb on 22 Sep 2022
You loop above would work except you use the variable na as both a dynamic file name to read and then overwirite it with the returned data in every pass -- hence, you lose everything you just did on the next loop and end up with only the last-read file in the end.
While you can build the filenames dynamically, this is the ideal place for the dir solution using filename wildcards to select the range of files wanted instead...
Birth1 = 5.6;
Death1 = 1;
rootname=sprintf('Birth2_Cons_muj_%g_bj_%g_Part_*.csv' ,Death1,Birth1);
d=dir(rootname);
for i=1:numel(d)
data(i)=readmatrix(fullfile(d(i).folder,d(i).name)); % read each into a cell array
end
data=cell2mat(data); % smoosh altogether into one array...
The cell array intermediary will be more efficient than trying to catenate the arrays themselves dynamically through the loop.
  2 Comments
Ursula Trigos-Raczkowski
Ursula Trigos-Raczkowski on 23 Sep 2022
Thank you, I was hoping na was changing each time to be the Birth2_i file :( but clearly i was wrong
dpb
dpb on 23 Sep 2022
"...I was hoping na was changing each time to be the Birth2_i file"
Well, it was the first use, but then it was overwritten each time -- but then it also overwrote the last set of data read into the same variable.
MATLAB, unlike other languages with static memory allocation (C, Fortran, etc., ...) does silent memory allocation on assignment so such logic errors are not discernible coding errors by even a warning that you've stored a numeric array into what had been a string -- and then, vice versa.

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!