Effacer les filtres
Effacer les filtres

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

9 vues (au cours des 30 derniers jours)
SUSHMA MB
SUSHMA MB le 27 Juil 2017
Modifié(e) : per isakson le 28 Juil 2017
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 )
}

Réponses (1)

per isakson
per isakson le 27 Juil 2017
Modifié(e) : per isakson le 28 Juil 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 );
inspect the text file with Notepad++
  4 commentaires
Walter Roberson
Walter Roberson le 27 Juil 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
per isakson le 28 Juil 2017
Modifié(e) : per isakson le 28 Juil 2017
@SUSHMA MB, see the code I added to my answer

Connectez-vous pour commenter.

Catégories

En savoir plus sur Low-Level File I/O dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by