下面是使用STRUCT2CELL稍微不同的解决方案:
%# build a sample array of structures
id = num2cell((1:10)',2); %'
coords = num2cell(rand(10,3),2);
misc = num2cell(rand(10,1),2);
conn = arrayfun(@(n)randi(5,[1 n]), randi([0 6],[10 1]), 'UniformOutput',false);
p = struct('ID',id, 'Coordinate',coords, 'Misc',misc, 'Conn',conn);
%# convert to cell array
h = fieldnames(p)'; %'
X = struct2cell(p)'; %'
%# split 'coords' field into 3 separate columns
h2 = {'xPos' 'yPos' 'zPos'};
X2 = num2cell(cell2mat(X(:,2)));
%# convert 'conn' field to string
X4 = cellfun(@num2str, X(:,4), 'UniformOutput',false);
X4 = regexprep(X4, '[ ]+', ' '); %# clean multiple spaces as one
%# build final cell array with headers
C = [h(1) h2 h(3:4) ; X(:,1) X2 X(:,3) X4]
其结果是:
>> C
C =
'ID' 'xPos' 'yPos' 'zPos' 'Misc' 'Conn'
[ 1] [0.78556] [ 0.46707] [0.66281] [ 0.46484] '3'
[ 2] [0.51338] [ 0.6482] [0.33083] [ 0.76396] '2 1 2 5 1 2'
[ 3] [ 0.1776] [0.025228] [0.89849] [ 0.8182] '1 3 1 5'
[ 4] [0.39859] [ 0.84221] [0.11816] [ 0.10022] '1 1 2'
[ 5] [0.13393] [ 0.55903] [0.98842] [ 0.17812] '3 1 5 2 2 1'
[ 6] [0.03089] [ 0.8541] [0.53998] [ 0.35963] ''
[ 7] [0.93914] [ 0.34788] [0.70692] [0.056705] '2 1 3 4 4'
[ 8] [0.30131] [ 0.44603] [0.99949] [ 0.52189] '1 1 4 5 3'
[ 9] [0.29553] [0.054239] [0.28785] [ 0.33585] '1 5 2'
[10] [0.33294] [ 0.17711] [0.41452] [ 0.17567] '2'
其中例如第二结构是:
>> p(2)
ans =
ID: 2
Coordinate: [0.51338 0.6482 0.33083]
Misc: 0.76396
Conn: [2 1 2 5 1 2]
优雅的解决方案,但是,对于某些元素为空值的人来说,这种方式可以解释它们(它是(@)(x)[{x.ID} {x.Coordinate(1)} {x.Coordinate(2)} {x.Coordinate(3)} { x.Misc} {num2str(x.Connections)}],Node,'UniformOutput',0);' – user1007692
太好了,我很高兴它有帮助! –