Reputation: 88
I have a struct in the format of:
my_struct
|
+ element_1
| |
| + value_1: "some string"
| + value_2: 25
|
+ element_2
| |
| + value_1: "some other string"
| + value_2: 11
...
and can't find a simple way to create a struct array such that my_struct(1).value_1 == "some string"
. And similarly, my_struct(2).value_2 == 11
. The field names "element_1" and "element_2" are unnecessary.
Upvotes: 1
Views: 162
Reputation: 112759
Here's a way (see struct2cell
and cell2mat
):
result = cell2mat(struct2cell(my_struct).');
Example:
my_struct.element_1.value1 = "some string";
my_struct.element_1.value2 = 25;
my_struct.element_2.value1 = "some other string";
my_struct.element_2.value2 = 11;
result = cell2mat(struct2cell(my_struct).');
gives
>> result
result =
1×2 struct array with fields:
value1
value2
>> result(1)
ans =
struct with fields:
value1: "some string"
value2: 25
>> result(2)
ans =
struct with fields:
value1: "some other string"
value2: 11
Upvotes: 2