exporting data to excel / csv using fprintf

72 次查看(过去 30 天)
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 个评论
Justin Ferland
Justin Ferland 2021-3-25
编辑:Justin Ferland 2021-3-25
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 2021-3-25
Technically, csv files do not have spaces before the commas, except for character vectors.

请先登录,再进行评论。

回答(1 个)

Ben v O
Ben v O 2013-3-7
编辑:Ben v O 2013-3-7
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 个评论
K E
K E 2014-5-13
Couldn't you just create a csv file by changing the extension? fid = fopen('test.csv','w+');

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by