필터 지우기
필터 지우기

exporting data to excel / csv using fprintf

조회 수: 72 (최근 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 CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by