Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

matlab - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
',columnsHeader{end});     %# Write the last label and a newline
fclose(fid);                                %# Close the file
dlmwrite('myfile.csv',numbersTable,'-append');  %# Append your numeric data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...