How to slice a struct array?

后端 未结 4 495
醉梦人生
醉梦人生 2021-01-18 01:18

How can I extract a specific field from each element of a Matlab struct array?

>> clear x
>> x(1).a = 6;
>> x(2).a = 7;

I

相关标签:
4条回答
  • 2021-01-18 01:55

    For a multi-dimensional array, you need

    reshape([x.a], size(x))
    
    0 讨论(0)
  • 2021-01-18 01:55

    If elements of the struct are strings, the accepted solution concatenates all cells. The more general

    vertcat(x.a)
    

    works in all cases. Ref

    0 讨论(0)
  • 2021-01-18 02:08

    No problem - just use :

    arr = [x.a];
    

    It will concat all of the values that you need. If you have a more complex data, you can use the curly bracers:

    b(1).x = 'John';
    b(2).x = 'Doe';
    arr = {b.x}; 
    
    0 讨论(0)
  • 2021-01-18 02:09

    Sadly, I am almost sure that MATLAB has no nice way of doing what you want. You will have to either use a for loop to construct a new array, or else go back and redesign your data structures. For example you might be able to use a struct-of-arrays rather than an array-of-structs.

    0 讨论(0)
提交回复
热议问题