Reputation: 29
I need to write a string variable in several lines for example as bellow:
a = 1, b = 2, c = 3
a = 0, b = 5, c = 1
a = 4, b = 2, c = 0
a = 8, b = 7, c = 3
a = 3, b = 0, c = 8
a = 2, b = 9, c = 3
...
a = 1, b = 5, c = 5
and save it in a text file.
I have a matrix containing 3 columns of a, b and c. What is an issue is definition of the string. What simply comes to mind but is absolutely wrong is as follows, I just wrote this to explain my problem better:
for i = 1:100
s(i) = (['a = ',num2str(A(i,1)),'b = ',num2str(A(2,1)),'c = ',num2str(A(2,1))]);
end
How can I generate such text file?
Upvotes: 1
Views: 59
Reputation: 5190
You could use the dlmwrite
function to write the strings in a .txt
file as follows:
dlmwrite('my_output_file.txt',sprintf('a = %i, b = %i, c = %i\n',A'),'delimiter','')
Notice, you should use the transpose
of the input matrix A otherwhise the values wll be get "column-wise".
Hope this helps.
Upvotes: 1
Reputation: 10792
You can save this matrix with:
A = round(abs(10*randn(100,3))); %generation of random matrix
fid = fopen('data.txt','w'); %creation of the file data.txt, w stand for writing
fprintf(fid,'a = %d, b = %d, c = %d\n',...
A(:,1),A(:,2),A(:,3)); %write the text
fclose(fid); %close the file
Upvotes: 1
Reputation: 1797
sprintf('a = %i, b = %i, c = %i\n',A(:,1),A(:,2),A(:,3))
will generate a string of what you would like to save in your text file.
Upvotes: 0