Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Creating or changing a .csv file that has headings.

Subject: Creating or changing a .csv file that has headings.

From: Ulrik Nash

Date: 29 Oct, 2013 23:46:05

Message: 1 of 2

I have a matrix , M, containing values. These values I wish to save in csv-format, for use by another program (Processing). However, not only do I need to export the values in M, I also must add a header line in the csv-file.

As I see it, I am thinking I have two options:

A) Create the csv-file with the headings, but nothing else, and then append the csv-file.
B) Create the csv-file along with the headings all in Matlab.

I have tried something like this:

M = randn(4,4);
dlmwrite('test.csv',M,'delimiter',',');
N = randn(4,4);
dlmwrite('test.csv',N,'delimiter',',','-append');

But the headings disappear in option A.

Does anyone have a solution to this problem they would like to share? I don't have the toolbox.

Subject: Creating or changing a .csv file that has headings.

From: dpb

Date: 30 Oct, 2013 00:18:14

Message: 2 of 2

On 10/29/2013 6:46 PM, Ulrik Nash wrote:
> I have a matrix , M, containing values. These values I wish to save in
> csv-format, for use by another program (Processing). However, not only
> do I need to export the values in M, I also must add a header line in
> the csv-file.
>
...

> I have tried something like this:
>
> M = randn(4,4);
> dlmwrite('test.csv',M,'delimiter',',');

...

[dlm|csv]write() only write the data, nothing else (as you've
discovered, but the doc's would've told you that to begin with).

fprintf() lets you write whatever you wish, however you wish...

n=size(M,2); % number columns in M
fmt=[repmat('%.2f,'1,n-1) '%.2f\n']; % define appropriate format
fid=fopen(filename,'w');
fprintf(fid,'%s',hdr(:)) % hdr is char string header
fprintf(fid,fmt,M'); % NB: the transpose
fid=fclose(fid);

done. Salt format to suit, 'g' is good if values are widely disparate
in magnitude to keep given precision.

--

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us