How to convert .mat file into text file in a specific format ?

5 次查看(过去 30 天)
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 )
}

回答(1 个)

per isakson
per isakson 2017-7-27
编辑:per isakson 2017-7-28
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 );
inspect the text file with Notepad++
  4 个评论
Walter Roberson
Walter Roberson 2017-7-27
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' );

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by