how to input data into an array from csv files in a for loop
조회 수: 2 (최근 30일)
이전 댓글 표시
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];%
댓글 수: 0
채택된 답변
dpb
2022년 9월 22일
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
dpb
2022년 9월 23일
"...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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 MATLAB Support Package for Arduino Hardware에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!