How to convert .mat file into text file in a specific format ?
7 views (last 30 days)
Show older comments
How can i convert the .mat file into the following format of .txt file
x={
( 0.000000 0.000000 )
( 0.500000 0.333333 )
( 0.250000 0.666667 )
( 0.750000 0.111111 )
( 0.125000 0.444444 )
( 0.625000 0.777778 )
( 0.375000 0.222222 )
( 0.875000 0.555556 )
( 0.062500 0.888889 )
( 0.562500 0.037037 )
}
0 Comments
Answers (1)
per isakson
on 27 Jul 2017
Edited: per isakson
on 28 Jul 2017
I assume that the mat file contains a cell array named, x
x={
0.000000, 0.000000
0.500000, 0.333333
0.250000, 0.666667
0.750000, 0.111111
0.125000, 0.444444
0.625000, 0.777778
0.375000, 0.222222
0.875000, 0.555556
0.062500, 0.888889
0.562500, 0.037037
};
save('the_mat_file.mat','x');
S = load('the_mat_file.mat');
len = size( S.x, 1 );
fid = fopen( 'the_text_file.txt', 'w' );
fprintf( fid, '%s\n', 'x={' );
for jj = 1 : len
fprintf( fid, '( %8.6f %8.6f )\n', S.x{jj,:} );
end
fprintf( fid, '%s\n', '};' );
fclose( fid );
and inspect the result
>> type the_text_file.txt
x={
( 0.000000 0.000000 )
( 0.500000 0.333333 )
( 0.250000 0.666667 )
( 0.750000 0.111111 )
( 0.125000 0.444444 )
( 0.625000 0.777778 )
( 0.375000 0.222222 )
( 0.875000 0.555556 )
( 0.062500 0.888889 )
( 0.562500 0.037037 )
};
In response to comments below
The example above produce a text file with LF as new line separator. (See wiki on Newline). Some editors, e.g. Notepad, requires CRLF as new line separator.
To output CRLF you may modify the the fopen statement as proposed by @Walter or use \r\n explicitly in the print statements as in the code below.
x_array.mat contains a double array, not a cell array as I assumed from your question. The code below should do the job.
S = load('x_array.mat');
len = size( S.x, 1 );
fid = fopen( 'the_text_file.txt', 'w' );
fprintf( fid, '%s\r\n', 'x={' );
for jj = 1 : len
fprintf( fid, '( %8.6f %8.6f )\r\n', S.x(jj,:) );
end
fprintf( fid, '%s\r\n', '};' );
fclose( fid );
4 Comments
Walter Roberson
on 27 Jul 2017
You must be using MS Windows and you are looking at the file with an obsolete program such as NotePad.
Change the line
fid = fopen( 'the_text_file.txt', 'w' );
to
fid = fopen( 'the_text_file.txt', 'wt' );
per isakson
on 28 Jul 2017
Edited: per isakson
on 28 Jul 2017
@SUSHMA MB, see the code I added to my answer
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!