Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem concatenating a matrix of numbers with a vector of strings (column labels) using cell2mat

I'm a Mac user (10.6.8) using MATLAB to process calculation results. I output large tables of numbers to .csv files. I then use the .csv files in EXCEL. This all works fine.

The problem is that each column of numbers needs a label (a string header). I can't figure out how to concatenate labels to the table of numbers. I would very much appreciate any advice. Here is some further information that might be useful:

My labels are contained within a cell array:

    columnsHeader = cell(1,15)

that I fill in with calculation results; for example:

    columnsHeader{1}  = propertyStringOne (where propertyStringOne = 'Liq')

The sequence of labels is different for each calculation. My first attempt was to try and concatenate the labels directly:

    labelledNumbersTable=cat(1,columnsHeader,numbersTable)

I received an error that concatenated types need to be the same. So I tried converting the labels/strings using cell2mat:

    columnsHeader = cell2mat(columnsHeader);
    labelledNumbersTable = cat(1,columnsHeader,numbersTable)

But that took ALL the separate labels and made them into one long word... Which leads to:

??? Error using ==> cat

CAT arguments dimensions are not consistent.

Does anyone know of an alternative method that would allow me to keep my original cell array of labels?

like image 552
Ant Avatar asked Jun 30 '11 17:06

Ant


People also ask

Does cell2mat work for strings?

A "matrix" is a two-dimensional array, and can only hold numeric values -- not characters, text, strings, etc.

What does cell2mat do in Matlab?

Description. A = cell2mat( C ) converts a cell array into an ordinary array. The elements of the cell array must all contain the same data type, and the resulting array is of that data type.


1 Answers

You will have to handle writing the column headers and the numeric data to the file in two different ways. Outputting your cell array of strings will have to be done using the FPRINTF function, as described in this documentation for exporting cell arrays to text files. You can then output your numeric data by appending it to the file (which already contains the column headers) using the function DLMWRITE. Here's an example:

fid = fopen('myfile.csv','w');              %# Open the file
fprintf(fid,'%s,',columnsHeader{1:end-1});  %# Write all but the last label
fprintf(fid,'%s\n',columnsHeader{end});     %# Write the last label and a newline
fclose(fid);                                %# Close the file
dlmwrite('myfile.csv',numbersTable,'-append');  %# Append your numeric data
like image 69
gnovice Avatar answered Oct 17 '22 23:10

gnovice