esrakoeri
esrakoeri

Reputation: 3

How to write output of MATLAB to a txt file?

I would like to write output of Matlab code's result into a .txt file.

My code is :

for i=1:1000;
  M{i}=rand(1,4)';
end

So I try :

fid=fopen('M.txt','wt'); 
fprintf(fid,'%.8f\n',M{i}); 
fclose(fid)

The result is 1*1000 cell and every cell has 4*1 matrice. But the output file has 1*4000 matrices with this. How can I write column by column to a .txt file.

Thanks in advance.


screenshot from matlab

I want to write down all values of matrix like below side by side for 1000 matrices.

 0.9572 0.9572 0.9572 0.9572 0.9572 0.9572 0.9572 0.9572 0.9572 0.9572 
 0.4854 0.4854 0.4854 0.4854 0.4854 0.4854 0.4854 0.4854 0.4854 0.4854
 0.8003 0.8003 0.8003 0.8003 0.8003 0.8003 0.8003 0.8003 0.8003 0.8003 
 0.1419 0.1419 0.1419 0.1419 0.1419 0.1419 0.1419 0.1419 0.1419 0.1419

Upvotes: 0

Views: 2245

Answers (2)

Paolo
Paolo

Reputation: 26220

As you mentioned your MATLAB version is R2019a, you can use writematrix directly:

>> n = 4;
>> m = rand(1,n);
>> M = repmat(m.',1,1000);
>> writematrix(M,'M.txt','Delimiter','space')

Upvotes: 1

Mike Scannell
Mike Scannell

Reputation: 378

Your format specifier *.8f\n says print each value on a new line. If you want to print the four values as four columns, use a format specifier like this:

fprintf(fid,'%.8f %.8f %.8f %.8f\n',M{i});

If you want to write just one column of the data at a time, specify which column like this:

fprintf(fid,'%.8f\n',M{i}(1));

Then you'll have to repeat or loop to do the other 3 columns.

Upvotes: 1

Related Questions