2013-02-16 120 views
1

我有一個105x105的矩陣B(實際上是一個連接的矩陣的35x35組),我必須根據一個規則改變其元素< 3x3>矩陣。根據子矩陣規則更改大矩陣的元素

鑑於任何子矩陣每行只能有「1」,「1」只能出現在(1,1)和/或(2,2)和/或(3,3)。

因此唯一可能的子矩陣是

[0 0 0 0 0 0 0 0 0],它變爲[0 0 0 0 0 0 0 0 0]

[1 0 0 0; 0 0 0; 0 0 0],其變成[1 1 1; 0 0 0; 0 0 0]

[0 0 0; 0 1 0; 0 0 0] 0 0 0 1 1 1 0 0 0]

[0 0 0 0 0 0 0 0 1],它變爲[0 0 0 0 0 0 1 1 1]

[1 0 0; 0 1 0; 0 0 0],其變成[1 1 1; 1 1 1; 0 0 0]

[1 0 0; 0 0 0; 0 0 1]變爲[1 1 1; 0 0 0; 1 1 1]

[0 0 0; 0 1 0; 0 0 1],變成[0 0 0; 111]; 111 0

和[1 0 0; 0 1 0; 0 0 1],它變爲[1 1 1 1 1 1; 1 1 1]

我使用[1 1 1]*any(submatrix,2)改變值累計。到規則,它工作正常。但我使用下面的循環遍歷所有的子矩陣:

for i=1:3:103 
    for j=1:3:103 
     temp=A(i:i+2,j:j+2); 
     temp=[1 1 1]*any(temp,2); 
     A(i:i+2,j:j+2)=temp 
    end 
    end 

是不是有一個替代loopless方法做到這一點?

回答

0

一種解決方案是重塑陣列,這樣的重新分配變得簡單:

%# remember size of A 
[nRows,nCols] = size(A); 

%# reshape A to 3xn 
%# transpose so that we get each "row" as a separate column 
temp = reshape(A',3,[]); 

%# overwrite temp with the rows filled in 
temp = repmat(any(temp,1),3,1); 

%# reshape to recreate the original array 
%# and transpose 
B = reshape(temp,nRows,nCols)'; 
+0

它完美。你是怎麼想出這樣的解決方案的? – 2013-02-16 23:09:24

+0

@KunalRmth:我只是在考慮操作是什麼(如果它包含一個操作,就填充一行),然後想知道如何安排原始數組以便於操作。此外,我真的很好用Matlab;) – Jonas 2013-02-17 01:17:28

+0

,因爲你是如此優秀的Matlab,請參閱真的需要一些環removings。 – 2013-02-17 22:50:08