检查方阵中的所有诊断是否为真

时间:2015-05-27 03:26:58

标签: arrays matlab matrix

我试图检查在方阵中是否在所有可能的对角线和反对角线中都有多个真值,并返回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的第一步,是否有特定的功能或更好的方法来实现我想要的结果?

3 个答案:

答案 0 :(得分:4)

检测任何对角线或反对角线(不仅仅是主对角线和反对角线)中是否存在多个非零值:获取非零值的行和列索引{{1 }和<img>;然后检查是否重复ii(对角线)或jj(反对角线)的任何值:

ii-jj

答案 1 :(得分: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

注意:此方法仅考虑Main diag和Main Anti-Diag(考虑您提供的示例)。如果你想要所有可能的诊断,the other answer from Luis Mendo是要走的路

答案 2 :(得分:0)

使用@Santhan Salai的生成技术,我们可以使用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))])