2015-05-27 42 views
2

我想檢查一個方陣中是否有多個真值在所有可能的對角線和反對角線上,並返回true,否則返回false。 到目前爲止,我已經嘗試如下,但並不涵蓋所有可能的對角線:檢查方陣中所有的方位角是否爲真

n=8; %matrix dimension 8 x 8 
diag= sum(A(1:n+1:end)); 
d1=diag>=2; 
antiDiag=sum(A(n:n-1:end)); 
d2=antiDiag>=2; 

if ~any(d1(:)) || ~any(d2(:)) 
    res= true; 

else 
    res=false; 
end 

這是一個錯誤:

0  0  0  0  0  1  0  0 
0  0  0  0  0  0  0  0 
1  0  0  0  0  0  0  0 
0  0  0  0  0  0  0  0 
0  0  0  1  0  0  0  0 
0  1  0  0  0  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  1 
0  0  0  0  0  0  1  0 
0  0  0  0  0  0  0  0 
0  0  0  0  0  0  0  0 
0  0  0  0  0  0  0  0 
0  0  0  0  0  0  0  0 
0  0  0  0  0  0  0  0 
0  0  0  0  0  0  0  0 

由於這些我使用Matlab的第一步,是否有一個特定的功能或更好的方法來實現我期待的結果?

+0

您可以編輯,顯示矩陣A''? –

+0

@SanthanSalai更新輸出樣本 – FeliceM

回答

4

要檢測是否有超過一個非零值的任何對角線或antidiagonal(不只是主對角線和antidiagonal):獲得非零值,iijj的行和列索引;然後檢查是否重複ii-jj(對角線)或ii+jj(反對角線)的任何值:

[ii, jj] = find(A); 
res = (numel(unique(ii-jj)) < numel(ii)) || (numel(unique(ii+jj)) < numel(ii)); 
+0

哇..這適用於每個可能的診斷! –

3

一種方法:

n=8;       %// size of square matrix 
A = logical(randi(2,n)-1); %// Create a logical matrix of 0s and 1s 

d1 = sum(A(1:n+1:end));  %// sum all the values of Main diagonal 
d2 = sum(A(n:n-1:end-1)); %// sum all the values of Main anti-diag 
result = d1>=2 | d2>=2  %// result is true when any one of them is > than or = to 2 

採樣運行:

輸入:

>> A 

A = 

0  1  1  1  1  0  1  0 
0  1  1  1  1  1  0  0 
0  1  0  1  1  0  0  1 
0  1  1  0  1  1  0  0 
0  1  0  1  1  0  0  1 
1  0  0  0  1  1  0  1 
1  1  1  1  1  1  0  0 
1  1  1  1  0  0  0  1 

輸出:

result = 

1 

注:這種方法只考慮主要診斷和主防-DIAG(考慮到你所提供的例子)。如果你想爲所有可能的DIAGS,the other answer from Luis Mendo是去

+0

這隻會檢查_main_對角線和反對角線,對嗎? –

+0

@LuisMendo是的。從這個例子來看,我認爲OP只需要這樣。可能是我錯了 –

+0

對於這種解釋,這絕對是要走的路 –

0

使用@Santhan薩萊的發電技術的方式,我們可以使用diag功能(拉出主對角線矩陣),該fliplr翻轉該中心列和any減少到一個單一的值。

n=8;       %// size of square matrix 
A = logical(randi(2,n)-1); %// Create a logical matrix of 0s and 1s 

any([diag(A) ; diag(fliplr(A))]) 
相關問題