Eric
Eric

Reputation: 429

Create a structure with a cell of variable names and a cell of double arrays

enter image description here

As shown above, I have two cells: one with variable names and another their values. I need to create a structure in the following form:

s = struct;

s.var1.Time = 1st column of 1st val_vars;
s.var1.Data = 2nd column of 1st val_vars;

s.var2.Time = 1st column of 2nd val_vars;
s.var2.Data = 2nd column of 2nd val_vars;

...

Upvotes: 1

Views: 207

Answers (2)

FangQ
FangQ

Reputation: 1544

if you want good speed, try the below vectorized code:

%define sample data
name_vars={'var1','var2','var3','var4'};
val_vars={rand(100,2),rand(100,2),rand(100,2),rand(100,2)};

a=arrayfun(@(x) struct('Time',val_vars{x}(:,1),'Data',val_vars{x}(:,2)),1:length(name_vars),'uni',false);
b=cell2struct(a,name_vars,2)

Upvotes: 2

If_You_Say_So
If_You_Say_So

Reputation: 1283

Here is a simple solution. However, if you are dealing with a large dataset where you have many many vars, this approach is not efficient.

for i = 1:4
  eval(['s.' name_vars{i} '.Time = val_vars{' num2str(i) '}(:,1);']);
  eval(['s.' name_vars{i} '.Data = val_vars{' num2str(i) '}(:,2);']);
end

Upvotes: 1

Related Questions