generate multiple text files from a matrix

2 Ansichten (letzte 30 Tage)
fadzhi
fadzhi am 15 Jan. 2021
Kommentiert: Jon am 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)

Akzeptierte Antwort

Mathieu NOE
Mathieu NOE am 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

Weitere Antworten (1)

Jon
Jon am 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 Kommentar
Jon
Jon am 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

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by