How to expand struct or cell?

39 views (last 30 days)
John
John on 16 Mar 2016
Commented: Dave Behera on 25 Mar 2016
The cell or struct contains sub struct and sub struct with name and value of number or string, a long list. Can it be expanded into a list of variables with its value of number or string?
  1 Comment
James Tursa
James Tursa on 16 Mar 2016
Please give a short example of what you are trying to do. That being said, it sounds like you are trying to "poof" variables into existence where the variable name is created dynamically from a string and/or a number. This is usually a bad idea and there are better alternatives.

Sign in to comment.

Answers (2)

Dave Behera
Dave Behera on 24 Mar 2016
Hi James,
I believe that you are trying to retrieve a list of values from a struct contained in another struct. This can be easily done using struct2cell function:
a = struct([]);
a(1).b = struct([]); % b is a struct within struct a
%add some fields
a(1).b(1).field1 = 'value1';
a(1).b(1).field2 = 'value2';
a(1).b(1).field3 = 'value3';
c = struct2cell(a.b)
ans =
'value1'
'value2'
'value3'
This gives you the list of values in the inner struct. To get the fieldnames, use the fieldnames function:
>> fieldnames(a.b)
ans =
'field1'
'field2'
'field3'

John
John on 24 Mar 2016
Hi, Dave:
The problem is that the structure is already there to load. We can check its variables layer by layer. You can see their names and values, either numbers or strings. The question is that if it can be expended into single variables with its individual values, number or string.
Thanks.
  1 Comment
Dave Behera
Dave Behera on 25 Mar 2016
From what I understand now, you want to extract all fields from the struct and create variables out of them, assigning them the same values as in the struct.
There is a way to do this using eval, but it is not recommended. Here is an example, anyway:
>> a = 'x'
a =
x
>> b = '2'
b =
2
>> eval([a '=' b])
x =
2
This creates a variable x with the value 2. From my previous answer, you can get the field names and values from your struct. You will need to use the eval-based logic above for each such fieldname-value pair in your structs.
Note that dynamically creating variables using eval is not the best way to go. You may want to reconsider your overall logic to make sure that such a need does not arise.

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!