Arrays 在Matlab中将数组的结构/数组转换为单个数组
我有一个包含数组的Matlab结构。具体来说,它是这样分配的:Arrays 在Matlab中将数组的结构/数组转换为单个数组,arrays,matlab,struct,matlab-struct,Arrays,Matlab,Struct,Matlab Struct,我有一个包含数组的Matlab结构。具体来说,它是这样分配的: info(27).field1 = []; info(27).field2 = []; info(27).field3 = []; [1048576;0;0;0] [1;0;0;0] [1;0;0;0] [1047512;0;1064;0] [0,99;0;0,01;0] [1;0;8;0] [1047900;0;676;0] [0,94;0;0,07;0] [2;0;3;0] ... 它是通过一个循环填充的 % he
info(27).field1 = [];
info(27).field2 = [];
info(27).field3 = [];
[1048576;0;0;0] [1;0;0;0] [1;0;0;0]
[1047512;0;1064;0] [0,99;0;0,01;0] [1;0;8;0]
[1047900;0;676;0] [0,94;0;0,07;0] [2;0;3;0]
...
它是通过一个循环填充的
% here simplified for your convenience
for i = 1:27
info(i).field1 = rand(1,4);
info(i).field2 = rand(1,4);
info(i).field3 = rand(1,4);
当填充(我的值)时,如下所示:
info(27).field1 = [];
info(27).field2 = [];
info(27).field3 = [];
[1048576;0;0;0] [1;0;0;0] [1;0;0;0]
[1047512;0;1064;0] [0,99;0;0,01;0] [1;0;8;0]
[1047900;0;676;0] [0,94;0;0,07;0] [2;0;3;0]
...
我希望这是一个单独的(27x12)表,可以保存为一个表文件,数组的单个值为列(使用writetable(T,'myData.csv',…')
有点像这样(可以忽略表格标题):
甚至更好
1.A 1.B 1.C 1.D 2.A 2.B 2.C 2.D 3.A 3.B 3.C 3.D
___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
1048576 0 0 0 100% 0% 0% 0% 1 0 0 0
1047512 0 1064 0 99% 0% 1% 0% 1 0 8 0
1047900 0 676 0 94% 0% 7% 0% 2 0 3 0
到目前为止,我尝试的是:
T = table(info) %obviously doesn't work
info
_____________
[1x27 struct]
以及一个单元阵列的解决方案
% create a cell array and try to concatenate the arrays in the array
C = struct2cell(info)
Cp = permute(C,[3 1 2]);
Cpx = horzcat(Cp(:,1),Cp(:,2),Cp(:,3));
T = table(Cpx)
T =
Cpx
________________________________________
[4x1 double] [4x1 double] [4x1 double]
[4x1 double] [4x1 double] [4x1 double]
[4x1 double] [4x1 double] [4x1 double]
...
我原以为horzcat会起作用,但不知何故,我不明白为什么它不会起作用。有人能解决这个问题吗?您对
horzcat
的调用只是将Cp
的三列(作为单元格数组)连接起来。它们已经是列,因此输出与输入相同
如果要将内容连接在一起,可以首先使用cell2mat
将其转换为矩阵,然后将其直接传递到array2table
以创建表
T = array2table(cell2mat(Cp));
更新
如果原始向量为4x1
,则可以执行以下操作:
T = array2table(squeeze(cell2mat(struct2cell(info))).')
谢谢你的回答!我尝试了几种变体,但遇到了一些细节:@Honeybear你的评论似乎被打断了。细节是什么?结构中包含的向量是垂直的(4x1),因此cell2mat(Cp)
垂直堆叠值(27x3结构变成了108x3矩阵)。为了解决这个问题,我将结构中包含的向量(例如[1;0;0]
)更改为水平向量(例如[1 0 0 0]
,使用v=v'
。不知道如果没有循环,您会如何操作。然后它工作了(27x12表)。非常感谢。注意:抱歉,尝试换行时无意中用Enter发送了注释;)@在你最初的帖子中,它们是1 x 4,所以我假设它们在你的数据中。我增加了额外的方法,如果他们是4 x 1。完美的,谢谢你,像一个魅力工程。投了赞成票,但仍然是小代表,以显示投票。