exporting data to excel / csv using fprintf

50 views (last 30 days)
David C
David C on 23 Feb 2013
Commented: Walter Roberson on 25 Mar 2021
So i have a data structure where I want to export into a csv or excel file. the fieldnames are the headers of the columns, and each field contains numeric data pertaining to that particular field name.
what I want to do is to print the row of headers, then under each header, concatenate the numerical data pertaining to that column.
Here's what I have, but simplified:
if true
s = struct('names',{'david' 'charles' 'mary'},'age',{18 19 17});
headers = fieldnames(s);
fid=fopen('test.csv','w');
fprintf(fid,'%s,',headers{:});
for i = 1:length(headers)
fprintf(fid,'%d\n',s.(headers{i}));
end
fclose(fid);
end
however, this just concatenates everything into the first column only, and it doesn't move to the next column.
Is there a better way to do what i'm trying to do? my structure is a rather larger matrix, and I would hate to have to convert each of the fields to a matrix and then deal with it that way.
Any advice is highly appreciated.
Thanks
  2 Comments
Justin Ferland
Justin Ferland on 25 Mar 2021
Edited: Justin Ferland on 25 Mar 2021
I know this question is old but It might help someone else down the road. The .CSV file type is a comma seperated list and so
x = [1 ,2, 3, 4, 5]
y = [6, 7, 8, 9, 10]
fid=fopen('file_name.csv')
for i = 1:5
fprintf(fid,'%i ,%i \n',x(i),y(i))
end
fclose(fid)
Notice the comma in between the place holder. This will make sure that each entry is in a different cell in your .CSV file.
Walter Roberson
Walter Roberson on 25 Mar 2021
Technically, csv files do not have spaces before the commas, except for character vectors.

Sign in to comment.

Answers (1)

Ben v O
Ben v O on 7 Mar 2013
Edited: Ben v O on 7 Mar 2013
I have the same problem here, however, I can get it in excel using a .txt instead of a .csv.
Using the code:
if true
RM = [1.234,2.1227873,3.2323423221,4,0];
rf = [23.00123,23.9384,4.2983, 0, 0];
rp = [12 44 56 64 23];
results = [RM; rf; rp];
fid = fopen('test.txt','w+');
% headers
% fprintf(fid, 'observed particles \n\n');
fprintf(fid, '%6s\t%6s\t%6s\t\n', 'RM', 'rf', 'rp');
% tab-separated columns of results
fprintf(fid, '%6.4f\t%6.41f\t%6.5f\n', results);
fclose(fid);
end
Opening it in excel gives good results. Maybe that will help. Still I'm looking for a way to get it in a .csv properly.
Any suggestions would be helpful.
  1 Comment
K E
K E on 13 May 2014
Couldn't you just create a csv file by changing the extension? fid = fopen('test.csv','w+');

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!