pyigal
pyigal

Reputation: 389

extract structs values into variable named as the field

I have a 1x1 Matlab struct with 5 fields ('a', 'b', 'c', 'd', 'e'). Each field contains some sort of data (which doesn't really matter for my question) and I would like to extract each value out of the struct and assign it to a variable named as the field. Any idea for a code that will do it?

Upvotes: 0

Views: 1436

Answers (3)

gnovice
gnovice

Reputation: 125854

While it is generally not best practice to spread data out to a bunch of variables when you already have it neatly stored in a structure, an easy way to move structure fields to variables that doesn't require hard-coding your field/variables names would be to use the save and load commands like so:

s = struct('a', 1, 'b', 2, 'c', 3);  % A sample structure
save('temp.mat', '-struct', 's');    % Save fields to a .mat file
clear all                            % Clear local variables (just for display purposes)
load('temp.mat');                    % Load the variables from the file
whos                                 % Display local variables

  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double              
  b         1x1                 8  double              
  c         1x1                 8  double

Pro: this is very easy and works for any structure. Con: it involves moving data into and out of a file.

Upvotes: 3

EBH
EBH

Reputation: 10440

If you know what are the variables to be created, then you can write (assuming s is your struct):

C = struct2cell(s);
[a,b,c,d,e] = C{:};

Otherwise, you need to create undeclared new variables while the program is running (using the assignin command from @Vahe-Tshitoyan answer) and that's a bad idea.

Upvotes: 1

Vahe Tshitoyan
Vahe Tshitoyan

Reputation: 1439

assuming s is your structure

cellfun(@(x) assignin('base', x, s.(x)), fieldnames(s));

However, I do not see a good use-case for this as already mentioned by gnovice.

Upvotes: 4

Related Questions