如何切片结构数组?

时间:2022-07-01 15:39:51

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

如何从Matlab结构数组的每个元素中提取特定字段?

>> 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.

我想要一个包含6和7的数组。无论是x(:)。还是x.a都不能做我想要的。

>> x(:).a

ans =    

     6


ans =

     7

3 个解决方案

#1


9  

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


0  

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.

可悲的是,我几乎可以肯定MATLAB没有办法做你想做的事。您将不得不使用for循环来构造新数组,或者返回并重新设计您的数据结构。例如,您可以使用结构数组而不是结构数组。

#3


0  

For a multi-dimensional array, you need

对于多维数组,您需要

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

#1


9  

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


0  

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.

可悲的是,我几乎可以肯定MATLAB没有办法做你想做的事。您将不得不使用for循环来构造新数组,或者返回并重新设计您的数据结构。例如,您可以使用结构数组而不是结构数组。

#3


0  

For a multi-dimensional array, you need

对于多维数组,您需要

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