Reading multiple files in multiple loops
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
Star Strider
on 14 Sep 2021
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 Comments
Star Strider
on 14 Sep 2021
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.
.
More Answers (0)
See Also
Categories
Find more on Downloads 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!