Star
Star

Reputation: 2299

Saving in txt format in Matlab with commas and semicolons

I have a huge matrix in Matlab that I want to save in .txt format (or in any other text format).

Suppose the matrix is

A =

     1     2     3
     4     5     6
     7     8     9

If I type save prova.txt A -ASCII I get the matrix in .txt format as

1 2 3

4 5 6

7 8 9

(in an horrible exponential form, actually)

I would like to get instead

1, 2, 3;

4, 5, 6;

7, 8, 9;

Can you help me? In addition, do you know a way to make the exponential form disappear?

Upvotes: 0

Views: 327

Answers (1)

rayryeng
rayryeng

Reputation: 104515

First, use the approach by Luis Mendo to convert your numeric array to a character matrix that is comma delimited with a semi-colon at the end of each row:

str = num2str(A, '%i, '); 
str(:,end) = ';';

Next, convert each of the rows of the character array into a cell array:

s = mat2cell(str, ones(1,size(str,1)), size(str,2));

Now, use fopen, fprintf and fclose to write the data to file:

fid = fopen('prova.txt', 'w');
fprintf(fid, '%s\n', s{:});
fclose(fid);

This is what I get when I examine prova.txt:

1, 2, 3;
4, 5, 6;
7, 8, 9;

Upvotes: 2

Related Questions