How to add additional field in the structure from already formed cell array?

I want to add the additional field with (imported) data to include in already formed structure. I will use the example from the tutorial:
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
The data I want to include in the structure refer to cell array:
Name:
'John Doe'
'John Doe'
'John Doe'
'Ann Lane'
'Ann Lane'
'Ann Lane'
'Ann Lane'
'Ann Lane'
and related Score (8x1 double): [72 75 88 14 12 33 66 90].
I want to form a new field in patient structure (score) so that the [72, 75,88] match patient(1), i.e. John Doe and the rest to patient(2) i.e. Ann Lane.

 Accepted Answer

patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
name={'John Doe','John Doe','John Doe','Ann Lane','Ann Lane','Ann Lane','Ann Lane','Ann Lane'}
score=num2cell( [72 75 88 14 12 33 66 90])
nom={patient.name}
for k=1:numel(score)
p=patient(ismember(nom,name{k}))
pa(k).name=p.name
pa(k).billing=p.billing
pa(k).score=score(k)
end
pa

4 Comments

Aleksander commented
Dear Azzi, thank you for the answer. Just the note that pa structure is 1x8 while patient structure is 1x2. Pa structure now contains three John Does and five Ann Lanes while the patient includes only two names (items). Is there a possibility that score field in 'pa' structure contains vector structure (now it is a scalar structure)?
Edit
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
name={'John Doe','John Doe','John Doe','Ann Lane','Ann Lane','Ann Lane','Ann Lane','Ann Lane'}
score=num2cell( [72 75 88 14 12 33 66 90])
for k=1:numel(patient)
nam=patient(k).name
pa(k).name=patient(k).name
pa(k).billing=patient(k).billing
pa(k).score=score(ismember(name,nam))
end
Dear Azzi thank you again. however I get 1x8 struct with 3 fields. Field 1 is John Lane, field 2 is Ann, but field 3 is again John Lane etc. If I may ask you this - if I have let's say these cell arrays a1={'AA','AA','AA'}; a2={'35000','96000','88000'}; a3={'1a','1b','1c'}. How can I convert these two cell arrays in a structure 1x1 structure with three fields?
No, maybe you didn't clear the variable pa. Try to clear your variables
clear
Or try this
patient=struct('name',{'John Doe'; 'Ann Lane'},'billing',{127.00;28.50})
name={'John Doe','John Doe','John Doe','Ann Lane','Ann Lane','Ann Lane','Ann Lane','Ann Lane'}
score=num2cell( [72 75 88 14 12 33 66 90])
for k=1:numel(patient)
nam=patient(k).name
pa(k).name=patient(k).name
pa(k).billing=patient(k).billing
pa(k).score=score(ismember(name,nam))
end

Sign in to comment.

More Answers (0)

Categories

Products

Community Treasure Hunt

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

Start Hunting!