How to slice a struct array?

泄露秘密 提交于 2020-06-27 07:26:28

问题


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'd like an array containing 6 and 7. Neither x(:).a nor x.a do what I want.

>> x(:).a

ans =    

     6


ans =

     7

回答1:


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}; 



回答2:


For a multi-dimensional array, you need

reshape([x.a], size(x))



回答3:


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.



来源:https://stackoverflow.com/questions/8631136/how-to-slice-a-struct-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!