MATLAB Answers

generate multiple text files from a matrix

18 views (last 30 days)
fadzhi
fadzhi on 15 Jan 2021
Commented: Jon on 15 Jan 2021
Hi all,
i have a 1000 x 2 matrix and i want to generate 1000 text files with two lines with first entry from first colum of matrix and second from second (for first files and so on till 1000). Will appreciate any help in this regard
a = 1...1000
b = 1001...2000
txt1= (1,10001)
....
......
txt1000 = (1000, 2000)

  0 Comments

Sign in to comment.

Accepted Answer

Mathieu NOE
Mathieu NOE on 15 Jan 2021
hello
see below
data = [(1:1000)' 1000+(1:1000)'];
for ci = 1: size(data,1)
str = ['(' num2str(data(ci,1)) ',' num2str(data(ci,2)) ')'];
filename = ['file_out' num2str(ci) '.txt'];
writematrix(str, filename,"QuoteStrings",0);
end

  0 Comments

Sign in to comment.

More Answers (1)

Jon
Jon on 15 Jan 2021
While I was working on this I see you have already received an answer. This is probably similar to what Mathieu has already submitted, but since I had already spent time preparing it I'll provide it as an alternative. I like to put leading zeros on my filenames e.g. txt00001.csv, txt0002.csv, ... txt0999.csv, txt1000.csv as you can then easily retrieve them in alphabetical (dictionary) order.
baseName = 'txt'
A = rand(1000,2)
% loop through data making individual files for each row
numRows = size(A,1);
for k = 1:numRows
% build filename % e.g. txt083.csv
filename = [baseName,num2str(k,'%04d'),'.csv'];
% write data to file
writematrix(A(k,:),filename)
end

  1 Comment

Jon
Jon on 15 Jan 2021
By the way, I wonder why you are creating so many smaill files. Often there is a more efficient alternative, but I can't offer any suggestions without knowing what your overall problem is

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by