How to convert .mat file into text file in a specific format ?
6 ビュー (過去 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 )
}
0 件のコメント
回答 (1 件)
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 );
4 件のコメント
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' );
per isakson
2017 年 7 月 28 日
編集済み: per isakson
2017 年 7 月 28 日
@SUSHMA MB, see the code I added to my answer
参考
カテゴリ
Help Center および File Exchange で Environment and Settings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!