How to save matrix using fprintf in .txt file?

4 views (last 30 days)
I have a loop that opens several files. Then, 5 variables are extracted from each file and I want to save them as a matrix using fprintf. That is, for each open file I need to save a matrix with numerous rows and 5 columns in a single output file.
Matrix of file 1:
21699 -5.4177 -37.12 21 2000
21700 -5.4267 -37.12 25.5 2000
22195 -5.3818 -37.111 23 2000
22196 -5.3908 -37.111 24 2000
22197 -5.3997 -37.111 22.5 2000
22198 -5.4087 -37.111 25 2000
22199 -5.4177 -37.111 23.75 2000
22200 -5.4267 -37.111 23 2000
22694 -5.3728 -37.102 24.13 2000
22695 -5.3818 -37.102 24.5 2000
Matrix of file 2:
12178 -5.2291 -37.292 20.5 3000
12672 -5.1752 -37.283 21.5 3000
12673 -5.1842 -37.283 21.88 3000
12674 -5.1932 -37.283 22.38 3000
12675 -5.2022 -37.283 21.13 3000
12679 -5.2381 -37.283 20.5 3000
13172 -5.1752 -37.274 22.5 3000
13173 -5.1842 -37.274 20.75 3000
13174 -5.1932 -37.274 20.38 3000
13175 -5.2022 -37.274 20.5 3000
13176 -5.2111 -37.274 20.5 3000
13177 -5.2201 -37.274 20.63 3000
13178 -5.2291 -37.274 23.5 3000
13179 -5.2381 -37.274 24.38 3000
13182 -5.265 -37.274 20 3000
I need to merge the two into a single file inside the loop.
How can I do this?

Answers (1)

Mohammad Sami
Mohammad Sami on 3 Sep 2020
Edited: Mohammad Sami on 3 Sep 2020
You can try using readmatrix and vertcat functions.
I am assuming the default options would work in your case.
files = {'f1.txt' 'f2.txt' 'f3.txt'}; % file list
% you can also get the file list using dir function if you need to dynamically identify files
data = cell(1,0);
for i = 1:length(files)
data{i} = readmatrix(files{i});
end
data = vertcat(data{:});
writematrix(data,'out.txt');

Categories

Find more on Environment and Settings 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!