Excel - xls problem

3 次查看(过去 30 天)
Raviteja
Raviteja 2011-8-22
I am writing here some portion of my code.
for i=1:size(files_hea,1)
fid = fopen(files_hea(i).name, 'r');
scan_hea(i)= textscan(fid,...
'%s','delimiter','\n','whitespace','');
scan_file=scan_hea{i};
id=char(scan_file(1,:));
Pat(i).id=id(1:9);
age=char(scan_file(17,:));
Pat(i).age=age(8:end);
sex=char(scan_file(18,:));
Pat(i).sex=sex(7:end);
date=char(scan_file(19,:));
Pat(i).date=date(13:end);
reason=char(scan_file(21,:));
Pat(i).reason=reason(24:end);
acute_mi=char(scan_file(22,:));
Pat(i).acute_mi=acute_mi(35:end);
former_mi=char(scan_file(23,:));
Pat(i).former_mi=former_mi(36:end);
additional=char(scan_file(24,:));
Pat(i).additional=additional(24:end);
scan_file=[];
fid = fclose(fid);
end
The above code create a structure like this
>> Pat
Pat =
1x536 struct array with fields:
id
age
sex
date
reason
acute_mi
former_mi
additional
My doubt is, I want to save the data 'Pat' into an excel sheet. In that excel sheet it have to show
colourns like this
id age sex date reason acute_mi former_mi additional
1 60 m 1999 mi yes no -
2 58 f 1998 mi no yes yes
3
. . .
. . .
. .
How to do it in matlab ?

采纳的回答

Raviteja
Raviteja 2011-8-22
Pc=struct2cell(Pat);
for i=1:20
XSL_mat(i,:)=[Pc(1,1,i),Pc(2,1,i),Pc(3,1,i), ...
Pc(4,1,i),Pc(5,1,i),Pc(6,1,i),Pc(7,1,i),Pc(8,1,i)];
end
xlswrite('database_pat.xls',XSL_mat)
  1 个评论
Fangjun Jiang
Fangjun Jiang 2011-8-23
I saw you accepted your own answer. That's fine. But I really encourage you try and understand the code in my comment. It is simply better code for the task. What if you have 20 fields (20 columns of data) to write?

请先登录,再进行评论。

更多回答(1 个)

Fangjun Jiang
Fangjun Jiang 2011-8-22
Not exactly fit but I think my answer to another question contains the solution. If you have difficulties, please post back.
Or use the function struct2cell(). There is an example in the help document.
  2 个评论
Raviteja
Raviteja 2011-8-22
Some progress I got now, I have written the code like this
Pc=struct2cell(Pat);
for i=1:10
xlswrite('test_xls.xls',[Pc(1,1,i),Pc(2,1,i),Pc(3,1,i), ...
Pc(4,1,i),Pc(5,1,i),Pc(6,1,i),Pc(7,1,i),Pc(8,1,i)],'A1:H10');
end
But it is giving only the last i=10 Pat data and over writing in all cells for A1:H10 (all columns are same)
Fangjun Jiang
Fangjun Jiang 2011-8-22
Try this:
%%
Pat(1,5).id=5;
Pat(1,5).age=20;
Pat(1,5).sex='m'
prop=fieldnames(Pat);
N_prop=length(prop);
mat=cell(size(Pat,2),N_prop);
for k=1:N_prop
[mat{:,k}]=deal(Pat(1,:).(prop{k}));
end
mat=[prop';mat]
xlswrite('test.xls',mat);

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by