MATLAB: Save data to .txt file

notepadsave to text filetxt

How do I save data to a txt file? I want to create a simple two column text file, where the first column is the data from an nx1 matrix and the second column is a different n x 1 matrix. I also want column headings in the first row of each column.
thanks

Best Answer

To write a text file with columns of data that have variable names, use the “writetable” function. First, create the data to write, put it in a table with variable names, and then write the data to text file.
% Create two columns of data
A = rand(10,1);
B = rand(10,1);
% Create a table with the data and variable names
T = table(A, B, 'VariableNames', { 'A', 'B'} )
% Write data to text file
writetable(T, 'MyFile.txt')
For more information see:
Starting in R2019a, you can use "writematrix" to write a matrix to a file.
For example:
M=magic(5);
writematrix(M, "M.txt");
For more information on "writematrix", please refer to the following documentation: