0

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
1
  • See edited answer. Commented Nov 3, 2019 at 22:41

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

I edited my question, do you have a chance to look again ? @UnbearableLigtness
Thank you so much!! But I use writematrix(M,'M.txt','Delimiter','tab') and its done.
1

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.

1 Comment

I edited my question, do you have a chance to look again ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.