# How to expand struct or cell?

56 ビュー (過去 30 日間)
John 2016 年 3 月 16 日
コメント済み: Dave Behera 2016 年 3 月 25 日
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 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
James Tursa 2016 年 3 月 16 日
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.

サインインしてコメントする。

### 回答 (2 件)

Dave Behera 2016 年 3 月 24 日
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
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'
##### 0 件のコメント-2 件の古いコメントを表示-2 件の古いコメントを非表示

サインインしてコメントする。

John 2016 年 3 月 24 日
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 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Dave Behera 2016 年 3 月 25 日
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.

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeStructures についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by