Feb*_*ono 2 matlab matrix repeat
怎么重复
A = [ 1 2 ;
3 4 ]
Run Code Online (Sandbox Code Playgroud)
重复
B = [ 1 2 ;
2 1 ]
Run Code Online (Sandbox Code Playgroud)
所以我希望我的答案像矩阵C:
C = [ 1 2 2;
3 3 4 ]
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
只是为了它的乐趣,另一个使用arrayfun的解决方案:
res = cell2mat(arrayfun(@(a,b) ones(b,1).*a, A', B', 'uniformoutput', false))'
Run Code Online (Sandbox Code Playgroud)
这导致:
res =
1 2 2
3 3 4
Run Code Online (Sandbox Code Playgroud)
为简单起见,我假设您只需要添加更多列,并且已经检查过每行的列数相同.
然后它成为重复元素和重塑的简单组合.
编辑我修改了代码,这样如果A和B是3D数组,它也可以工作.
%# get the number of rows from A, transpose both
%# A and B so that linear indexing works
[nRowsA,~,nValsA] = size(A);
A = permute(A,[2 1 3]);
B = permute(B,[2 1 3]);
%# create an index vector from B
%# so that we know what to repeat
nRep = sum(B(:));
repIdx = zeros(1,nRep);
repIdxIdx = cumsum([1 B(1:end-1)]);
repIdx(repIdxIdx) = 1;
repIdx = cumsum(repIdx);
%# assemble the array C
C = A(repIdx);
C = permute(reshape(C,[],nRowsA,nValsA),[2 1 3]);
C =
1 2 2
3 3 4
Run Code Online (Sandbox Code Playgroud)