Convert table to struct

9 views (last 30 days)
DavidL88 on 12 Feb 2021
Edited: DavidL88 on 18 Feb 2021
How can I convert a table to a struct with two layers (a struct within a struct)? Each subject has completed four conditions in a task, and within each of the four conditions there are 100 trials. So there are 400 trials total per subject. Each trial has a delay. I have this data in a table (with 400 rows per subject). Example table attached. I would like to place this data in a struct. First column in the struct should list Subject ID with one row per subject. Second column would have a 1x4 struct per row. This second layer struct within these cells of the second column would contain four rows (for the four Conditions - 11, 12, 21, 22). Each row listing a 1x100 double. These 1x100 double would be the 100 delays per condition per subject.
Example rows from table
T =
Subject Conditions Trial Delay
"Subject111" 11 95 83
"Subject111" 12 96 84
"Subject222" 21 97 67
"Subject333" 22 98 67
The output struct should look something like this;
Struct =
SubjectName Conditions
'Subject111' 1x4 struct
'Subject222' 1x4 struct
'Subject333' 1x4 struct
Within one of 1x4 struct above
1x100 double
1x100 double
1x100 double
1x100 double
Each 1x100 double would have a single row/100 columns listing the delays for that condition for that subject.

Accepted Answer

DavidL88 on 18 Feb 2021
Edited: DavidL88 on 18 Feb 2021
I figured out a script that does this.
[testID, SubjectNames] = findgroups(t.Subject);
[testID, Events] = findgroups(t.ConditionSample_Whole);
Events = num2cell(Events)
for i = 1:length(SubjectNames)
for i2 = 1:length(Events)
A(i).Subject = SubjectNames(i)
A(i).Events = Events
A(i).Events(i2,2) = {zeros(1,100)}
for i = 1:length(SubjectNames)
for i2 = 1:length(Events)
b = (ismember(t.Subject, A(i).Subject)) & (ismember(t.Event, A(i).Events{i2}))
idx = find(b)
A(i).Events(i2,2) = {t.Delay(idx)}

More Answers (0)

Community Treasure Hunt


Start Hunting!