Question

I had two arrays, (data1 is a header array of strings and data2 is the data array of numbers)

data1 = {'#','Area','C Xp','C Yp','Length','B #','R','L','Ch','E1 Xp','E1 Yp','E2 Xp','E2 Yp'};
data2 = [1   939  -397   586   99  2  2  0  -1  -450   588  -352   572
         2  1185  -287   294  145  2  1  1   0  -317   359  -235   244
         3   592  -242   486   77  3  2  1   0  -278   488  -202   477
         4   818  -144   480   60  2  0  2   1  -181   488  -135   451
         5   377   -23  -443   37  1  0  1   0   -42  -459   -12  -460
         6   923    32  -234   67  1  0  0   0    -3  -260    60  -212
         7   812   150  -148   54  1  0  1   0   136  -130   169  -161
         8  5968   428   432  402  3  3  0  -1   224   468   622   356
         9   617   714    13   63  1  0  1   0   687    35   702   -22

csvwrite('file.xlsx', data1, 0, 0);
csvwrite('file.xlsx', data2, 0, 1);

My first problem is data1 prints to the spreadsheet as an array of chars (example: '#','A','r','e','... each in their own cells). How do I get it to print as the strings I am passing?

My second problem is when I csvwrite data2, data1's info is erased or overwritten. How can I write both to the same file?

Was it helpful?

Solution

Hidden away in the Tips section of the csvwrite documentation:

csvwrite does not accept cell arrays for the input matrix M. To export a cell array that contains only numeric data, use cell2mat to convert the cell array to a numeric matrix before calling csvwrite. To export cell arrays with mixed alphabetic and numeric data, where each cell contains a single element, you can create an Excel® spreadsheet (if your system has Excel installed) using xlswrite. For all other cases, you must use low-level export functions to write your data. For more information, see Export Cell Array to Text File in the MATLAB® Data Import and Export documentation.

I'd say, use xlswrite.


If you can't use xlswrite, it looks like you are stuck doing it manually as described on the page, Export Cell Array to Text File. Something along the lines of:

% write headers
fid = fopen('test.csv','w');
fprintf(fid,'%s,',data1{:});
fprintf(fid,'\n');

% write data...
fprintf(fid,[repmat('%d,',1,numel(data1)) '\n'],data2);
fclose(fid)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top