How to group dynamically different fields from a structure ?

Hello,
I'm analyzing different type of data (EMG, torque), which is regroup in different fields (257) divided into 8 channels. I want to group different channels by record with a loop to create 1 variable with the different type of data.
By example, I tested with this type of loop but it doesn't work. There are 36 records, so i would like to have a loop for all these records.
Thank you for your help
data=load('labchart.mat');
data.data__chan_1_rec_1 %strucutre syntax
for i=1
triggerPNS=(data.data__chan_1_rec_(i));
triggerTMS=(data.data__chan_2_rec_(i));
torque=(data.data__chan_3_rec_(i));
emgVL=(data.data__chan_5_rec_(i));
emgRF=(data.data__chan_6_rec_(i));
emgVM=(data.data__chan_7_rec_(i));
end
fichier1= cat(2,triggerPNS,triggerTMS,torque,emgVL,emgVM,emgRF);

 Accepted Answer

Stephen23
Stephen23 on 19 Nov 2018
Edited: Stephen23 on 19 Nov 2018
This is a very good example of why putting meta-data into variable names or fieldnames makes code pointlessly complex. If that data has been simply stored in one structure array, then accessing the data would be trivially easy using indexing.
But as it is you will have to dynamically access fieldnames:
Here is an example using dynamic fieldnames, with two channels in three groups:
S.A_1_1 = [1;2;3];
S.A_2_1 = [0;0;1];
S.A_1_2 = [4;5;6];
S.A_2_2 = [0;1;0];
S.A_1_3 = [7;8;9];
S.A_2_3 = [1;0;0];
save('temp1.mat','-struct','S')
clear
S = load('temp1.mat');
N = 3; % how many groups
C = cell(1,N);
for k = 1:N
C{k} = [...
S.(sprintf('A_1_%d',k)),...
S.(sprintf('A_2_%d',k)),...
];
end
And checking the output (i.e. each group):
>> C{:}
ans =
1 0
2 0
3 1
ans =
4 0
5 1
6 0
ans =
7 1
8 0
9 0
But this task would be much easier if the original data had been saved in one structure array, e.g:
S(1,1).A = [1;2;3];
S(2,1).A = [0;0;1];
S(1,2).A = [4;5;6];
S(2,2).A = [0;1;0];
S(1,3).A = [7;8;9];
S(2,3).A = [1;0;0];
N = size(S,2);
D = cell(1,N);
for k = 1:N
D{k} = [S(:,k).A];
end
Putting meta-data into names just makes code pointlessly complex:

1 Comment

+1, exactly. You can access the dynamically created fields by sprintf (and this is much better than dynamically created variables using eval in addition!), but it is much smarter, more efficient and lee confusing, to store the information about the data in an additional field instead of a cryptic coding scheme in the fieldnames.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 19 Nov 2018

Commented:

Jan
on 19 Nov 2018

Community Treasure Hunt

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

Start Hunting!