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

조회 수: 5 (최근 30일)
SUSHMA MB
SUSHMA MB 2017년 7월 27일
편집: per isakson 2017년 7월 28일
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' );
per isakson
per isakson 2017년 7월 28일
편집: per isakson 2017년 7월 28일
@SUSHMA MB, see the code I added to my answer

댓글을 달려면 로그인하십시오.

카테고리

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