MATLAB: How to save a matrix as text file? PROBLEM REFORMULATION!!!

1MATLAB

I want to save a matrix as text file.
Each column should be separated by tab.
The output file should be read with any text editor
When the output is opened, it should display the numbers
in the same way it looks like in Matlab.
For example, let the matrix be
M=
1 4 7
2 5 8
3 6 9
I tried to save using the following command:
save MATRIX.txt M -ASCII -tabs
but when I opened either with Notepad,
I got the following as a result:
MATRIX.txt=
1.0000000e+000 4.0000000e+000 7.0000000e+000
2.0000000e+000 5.0000000e+000 8.0000000e+000
3.0000000e+000 6.0000000e+000 9.0000000e+000
How to correct this command or to write a new command
such that input and output are identical?
Thank you for your help
Emerson

Best Answer

fid = fopen('Matrix.txt', 'wt');
fprintf(fid, [repmat('%g\t', 1, size(M,2)-1) '%g\n'], M.');
fclose(fid)
There is a different approach:
fid = fopen('Matrix.txt', 'wt');
fwrite(fid, '%s', evalc('disp(M)'));
fclose(fid)
This will literally output whatever Matlab would, including things like writing a vector in a cell array out as (e.g.) [2 x 3 double]