1
votes

I have a 39x4 cell:

'ID'    'x' 'y' 'z'
459     34  -49 -20
464     36  -38 -22
639     40  -47 -27
719     35  -52 -20
725     42  -45 -18
727     46  -47 -26
...

I would like to write all this to a text file. I've tried the following:

fileID = fopen('test2.txt','w');
formatSpec='%s %d %d %d';
fprintf(fileID,formatSpec,P{:});
fclose(fileID);

However, if I do this, I get the error that fprintf is not defined for 'cell' input. I've seen a couple of examples like this one about how to print a cell array as .txt in Matlab this one about how to write cell array of combined string and numerical input into text file but they don't seem to fit very well without some clunky modifications.

Could someone help?

2

2 Answers

0
votes

The error is most probably being caused due to the following line in your code:

fprintf(fileID,formatSpec,P{:}); % P{:} returns all the cells in P matrix

Also the formatSpec you have specified will not work for all your rows since the first row is in a different format. You will need two calls to fprintf as:

fprintf(fileID,'%s %s %s %s\n',P{1,:});
fprintf(fileID,'%d %d %d %d\n',P{2:end,:});
0
votes

Your error is due to the fact that the first row of your cell array contains only strings while the other rows contain only numbers. Your format specifier currently assumes the first element to write per row is a string while the others are integers. You'll have to accommodate for a special case where writing to the first line consists of just strings.

Something like this should work:

%// Open the file for writing
fileID = fopen('test2.txt','w');

%// First write the headers to file
fprintf(fileID, '%s %s %s %s\n', P{1,:});

%// Transpose because writing is done in column-major order
Pt = P.'; %'

%// Now write each row to file
fprintf(fileID, '%d %d %d %d\n', Pt{:,2:end});

%// Close the file
fclose(fileID);

Take note at the format specifier for the first row consists of entirely strings, then the format specifier for the rows after consists only of integers. Also take note that I needed to transpose the cell array because using fprintf naturally writes matrices in column-major order so in order to write your matrices in a row-major fashion, the transposition is required before printing and we'll also need to access the columns of your data instead of the rows to accommodate.