2012-07-16 191 views
2

如何重複如何重複元素矩陣在MATLAB

A = [ 1 2 ; 
     3 4 ] 

反覆通過

B = [ 1 2 ; 
     2 1 ] 

因此,我希望我的回答像矩陣C:

C = [ 1 2 2; 
     3 3 4 ] 

感謝您的幫助。

+1

這是什麼邏輯?請解釋 – 2012-07-16 13:33:37

+0

@Andrey:我假設在'B'中有'2'的位置,我們想沿着列重複兩次'A'的值。 – Jonas 2012-07-16 13:47:27

+0

@Jonas這實際上是有道理的! – 2012-07-16 13:48:12

回答

5

爲了簡單起見,我假設您只會添加更多列,並且您已經檢查過每行的列數是否相同。

那麼變得重複元素和重塑的簡單組合。

編輯我修改了代碼,這樣它也可以工作,如果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 
+0

+1是理解的問題:) – 2012-07-16 13:48:57

+2

@EitanT的神祕邏輯:我看到,那就是「重複」的稱號,而我們應該用B到找出如何重複從A.我居然元素髮現它很明顯。感謝upvote,無論如何:) – Jonas 2012-07-16 13:49:06

+0

@jonas:如果我想要做超過矩陣A和B的價值? – 2012-07-17 06:30:36

6

只是爲了好玩,另一種解決方案利用arrayfun的:

res = cell2mat(arrayfun(@(a,b) ones(b,1).*a, A', B', 'uniformoutput', false))' 

這導致:

res = 

    1  2  2 
    3  3  4 
+0

+1:你一直都會生產出漂亮整齊的單行玩家,先生:) – 2012-07-17 11:56:07