如何有效地将单元格数组中的值赋给数值数组? A和B总是任何大小的方形矩阵。为简单起见,我只分配了小矩阵。如果例如A {1} = [2 3 8];那么我想在B矩阵的第二行和第三列中分配值8。 如,
Input
A=[1x3 double] [1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double] [1x3 double]
B=zeros(4,4);
A{1}=[2 3 8];
A{2}=[3 4 7];
and so on...
Output
B(2,3)=8;
B(3,4)=7;
and so on...
答案 0 :(得分:2)
使用spconvert
:
B = full(spconvert(cat(1, A{:})));
答案 1 :(得分:1)
你可以不用循环来做到这一点:
B=zeros(4,4);
A{1}=[2 3 8];
A{2}=[3 4 7];
C = cell2mat(A);
C = reshape(C,3,size(C,2)/3)';
indices = sub2ind(size(B), C(:,1), C(:,2));
B(indices) = C(:,3);
对于您的示例,结果为:
B =
0 0 0 0
0 0 8 0
0 0 0 7
0 0 0 0
答案 2 :(得分:1)
使用sub2ind
和indexing
%// creating a sample cell array. Replace this with your actual cell array
A = {[1 2 8] [1 1 4]; [2 1 5] [2 2 1]};
%// Reshaping the cell array to kx3 matrix
Amat = cat(1,A{:}); %// from luis' answer
%// taking first column as row sub, 2nd col as col sub
%// The subs are converted into linear indices to the size of A or B
ind = sub2ind(size(A),Amat(:,1),Amat(:,2));
%// You have done this (helps in fixing the dimensions of B)
B = zeros(size(A));
%// Taking last col of 'Amat' as values and assigning to corresponding indices
B(ind) = Amat(:,3);
<强>结果:强>
>> B
B =
4 8
5 1
答案 3 :(得分:0)
我建议在A单元格上循环一次以找到最大索引值,比方说max_i,max_j
。
然后初始化B,如:
B=zeros(max_i,max_j)
然后在A单元格上再次循环,并将值分配给相应的B元素。
编辑:添加了示例代码:
max_i=0
max_j=0
for k=1:size(A,1)
for l=1:size(A,2)
max_i=max([A{k,l}(1),max_i])
max_j=max([A{k,l}(2),max_j])
end
B=zeros(max_i,max_j)
for k=1:size(A,1)
for l=1:size(A,2)
B(A{k,l}(1),A{k,l}(2))=A{k,l}(3)
end