简体   繁体   English

MATLAB:结构的二维数组(包含向量)到3-D数组?

[英]MATLAB: 2-D array of structs (containing vectors) to 3-D Array?

I have a 2-dimensional array of structs 'cell' which each contain a number of vectors: 我有一个二维结构'cell'数组,每个数组包含许多向量:

cell(1,1).U = [1 2 3];
cell(1,2).U = [4 5 6];
cell(2,1).U = [7 8 9];
cell(2,2).U = [0 1 2];

I would like to extract the data into a 3-D array A(i,j,k). 我想将数据提取到3-D数组A(i,j,k)中。

Using cell-style extraction returns a 1x3 cell, the contents of which are 使用单元格样式提取将返回一个1x3的单元格,其内容为

>> {cell.U}
ans = {[cell(1,1).U]   [cell(1,2).U]   [cell(2,1).U]   [cell(2,2).U]}

And thus, converting this to a matrix using cell2mat(), as in: 因此,使用cell2mat()将其转换为矩阵,如下所示:

cell2mat(ans)

Returns a 3x4 array. 返回一个3x4数组。

Ideally, I would like a 2x2x3 array so that the indices i and j are preserved. 理想情况下,我想要一个2x2x3数组,以便保留索引i和j。 Is there any way (short of looping) to accomplish this? 有什么办法(短循环)来做到这一点?

Use CAT and RESHAPE . 使用CATRESHAPE Also, don't call your variable cell , since that's a built-in function. 另外,不要调用您的可变cell ,因为这是一个内置函数。

>> c(1,1).U = [1 2 3];
c(1,2).U = [4 5 6];
c(2,1).U = [7 8 9];
c(2,2).U = [0 1 2];


>> out = cat(1,c.U)
>> out = reshape(out,2,2,3)
out(:,:,1) =
     1     4
     7     0
out(:,:,2) =
     2     5
     8     1
out(:,:,3) =
     3     6
     9     2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM