exporting data to excel / csv using fprintf

50 ビュー (過去 30 日間)
David C
David C 2013 年 2 月 23 日
コメント済み: Walter Roberson 2021 年 3 月 25 日
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+');

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by