Reading multiple files in multiple loops
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello,
I have a set of text fiels to read into matlab. For instance, to read following files;
cbeta1_1.txt
cbeta1_5.txt
cbeta1_10.txt
cbeta1_20.txt
cbeta2_1.txt
cbeta2_5.txt
cbeta2_10.txt
cbeta2_20.txt
cbeta3_1.txt
cbeta3_5.txt
cbeta3_10.txt
cbeta3_20.txt
I've created the code below, but it only saves the last file to all elements of "mydata", where as I'd like it to write each file sequentially. i.e, cbeta1_1.txt to be mydata{1,1}, and cbeta1_5.txt to be mydata{1,2} and so on.
Any help is much appreciated!
mydata = [];
path = 'H:\..';
for k = 1:3
for i = [1 5 10 20]
for g = 1:12
myfilename{g} = fullfile(path, sprintf('cbeta%d_%d.txt', k, i ));
mydata{g} = importdata(myfilename{g});
end
end
end
댓글 수: 0
채택된 답변
Star Strider
2021년 9월 14일
The separate ‘g’ loop is not necessary, since it can be created either using a counter or by calculating it.
See if this does what you want —
mydata = cell(12,1);
path = 'H:\..';
iv = [1 5 10 20];
for k = 1:3
for i = 1:numel(iv)
g = k+3*(k-1) + i-1;
myfilename{g,:} = fullfile(path, sprintf('cbeta%d_%d.txt', k, iv(i) ));
% mydata{g,:} = importdata(myfilename{g});
end
end
myfilename
I commented-out the ‘mydata’ assignment since there are no files to read here. Restore it in your code.
.
댓글 수: 6
Star Strider
2021년 9월 14일
There is logic. The logic is simply calculating the value based on the indices. (A simple counter would also work, however I prefer the approach I use here.)
Here, the expression increments the ‘g’ value by adding ‘km’, the number of elements of ‘iv’, to ‘k’ so that it adds the value of ‘km’ to ‘k’ in each second and subsequent iteration of the ‘k’ loop value, to the index value in the ‘i’ loop to calculate.‘g’. So in the first ‘k’ iteration, ‘g’ is just ‘k+i-1’, in the second iteration, ‘k+km+i-1’ , in the third iteration, ‘k+2*km+i-1’ and so on. It must be consistent with the loop counter values, since they are used to create the file names.
.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Downloads에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!