我有一个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]
我有一个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]
例子:
% 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 numeric matrix,则必须插入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