Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to write a matrix to a text file in Octave?

I have a large matrix (2e6 x 3) which I have to write to a text file.

dlmwrite takes about 230s to achieve this task.

From your experience what is the fastest way to write a large matrix to a text file?

like image 544
Steven Avatar asked Oct 17 '12 10:10

Steven


People also ask

How do you write a matrix to a text file in Matlab?

Create a matrix, write it to a comma-separated text file, and then write the matrix to another text file with a different delimiter character. Create a matrix in the workspace. Write the matrix to a comma delimited text file and display the file contents. The writematrix function outputs a text file named M.

How do I read a TXT file in Octave?

data = load('-ascii','autocleaned. txt'); Loaded the data as wanted in to a matrix in Octave. Since all the data is in fixed width columns (except the last strings), you should be able to read it line by line, using fscanf to decode the line.


3 Answers

The following applies to MATLAB, but I suggest you try it in Octave. First of all, if you can - transpose the matrix. Here are examples using fprintf and csvwrite (essentially dlmwrite)

A = rand(3, 1e6);
tic;
fid = fopen('data.txt', 'w+');
for i=1:size(A, 1)
    fprintf(fid, '%f ', A(i,:));
    fprintf(fid, '\n');
end
fclose(fid);
toc

tic;
csvwrite('data.txt', A);
toc;

Elapsed time is 1.311512 seconds.
Elapsed time is 2.487737 seconds.

If not transposed, it will take ages indeed. By default, fprintf flushes the buffer after every call. You can try to use W instead of w to open the file, but it does not improve the situation here too much.

like image 106
angainor Avatar answered Oct 05 '22 19:10

angainor


Did you try this? I'm not sure about it's speed as compared to dlmwrite.

a = [1 2;3 4];
save temp.txt a;
like image 42
Anant Gupta Avatar answered Oct 05 '22 20:10

Anant Gupta


Having a variable data you can save it in a text format with space separated values (including a header):

save out.txt data

The header can be simply removed using basic Unix command tail e.g. (on any Linux/Mac OS):

tail -n +6 out.txt > file.csv
like image 21
Tombart Avatar answered Oct 05 '22 20:10

Tombart