1

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.

1
  • 1
    Did you try a simple loop? out(ii)=my_struct.(['element_',num2str(ii)]); Commented Jan 13, 2021 at 22:27

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

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.