我的A
是640x1单元格,其中每个单元格A(i,1)
的值因行而异,例如:
A(1,1)=[]
A(2,1)=[1]
A(3,1)=[1,2,3]
我想要做的是将A
转换为:
A(1,1)=[]
A(2,1)=1
A(3,1)=1; A(3,2)=2; A(3,3)=3
以便每个单元格只有一个值。所以,如果有人可以帮助我,我该怎么办呢?这是A
看起来像
A=
[]
0
0
0
145
[144;192]
[145;197;307]
答案 0 :(得分:3)
示例:
% first lets create some random cellarray containing data of different length
A = cell(10,1);
for i=1:numel(A)
A{i} = rand(1,randi([0 5]));
end
% determine the maximum number of columns
colnum = max(cellfun(@numel, A));
% create new cellarray, and fill each row
B = cell(numel(A),colnum);
for i=1:numel(A)
if isempty(A{i}), continue; end
B(i,1:numel(A{i})) = num2cell(A{i});
end
所以我把第一个单元格数组作为:
>> celldisp(A)
A{1} =
0.2217 0.1174 0.2967 0.3188
A{2} =
0.5079 0.0855
A{3} =
0.8010
A{4} =
[]
A{5} =
0.7303 0.4886 0.5785 0.2373 0.4588
A{6} =
0.5468 0.5211 0.2316 0.4889 0.6241
A{7} =
0.3955 0.3674 0.9880 0.0377
A{8} =
0.9133 0.7962 0.0987 0.2619 0.3354
A{9} =
0.1366 0.7212 0.1068 0.6538
A{10} =
0.7791 0.7150
变成了:
>> B
B =
[0.2217] [0.1174] [0.2967] [0.3188] []
[0.5079] [0.0855] [] [] []
[0.8010] [] [] [] []
[] [] [] [] []
[0.7303] [0.4886] [0.5785] [0.2373] [0.4588]
[0.5468] [0.5211] [0.2316] [0.4889] [0.6241]
[0.3955] [0.3674] [0.9880] [0.0377] []
[0.9133] [0.7962] [0.0987] [0.2619] [0.3354]
[0.1366] [0.7212] [0.1068] [0.6538] []
[0.7791] [0.7150] [] [] []
我们将元素作为2D单元格数组访问:
>> B{5,3}
ans =
0.5785
这是一个稍微不同的实现:
len = cellfun(@numel, A);
padding = arrayfun(@(n)cell(1,n), max(len)-len, 'UniformOutput',false);
B = cellfun(@num2cell, A, 'UniformOutput',false);
B = cellfun(@(b,pad) [b{:} pad], B, padding, 'UniformOutput',false);
B = cat(1, B{:});
请注意,上述内容将返回2D 单元格数组。这是因为常规数字矩阵不能被锯齿(所有行必须具有相同的长度)。
如果您想获得2D 数字矩阵,则必须插入NaN
值作为填充符:
C = B;
C(cellfun(@isempty,C))= {NaN};
C = cell2mat(C)
输出:
>> C
C =
0.2217 0.1174 0.2967 0.3188 NaN
0.5079 0.0855 NaN NaN NaN
0.8010 NaN NaN NaN NaN
NaN NaN NaN NaN NaN
0.7303 0.4886 0.5785 0.2373 0.4588
0.5468 0.5211 0.2316 0.4889 0.6241
0.3955 0.3674 0.9880 0.0377 NaN
0.9133 0.7962 0.0987 0.2619 0.3354
0.1366 0.7212 0.1068 0.6538 NaN
0.7791 0.7150 NaN NaN NaN