0

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?

4
  • 1
    As simple as that: a = yourStruct.a. And so on for other fields. Commented Jun 5, 2017 at 12:44
  • 2
    Are you wanting to generalize this to any number of arbitrarily-named fields? It's probably better to just keep values stored in a structure, as that is better organized than a bunch of variables. Commented Jun 5, 2017 at 13:26
  • 1
    I would like to do it automatically Commented Jun 5, 2017 at 13:34
  • 1
    If you provide more info on your use case you might get a better answer - as this type of thing is generally bad practice Commented Jun 5, 2017 at 15:01

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.