是否有一种简单的方法可以检查行或列中的所有元素或任何对角线是否相同?
a={'o','','o';
'x','o','o';
'x','o','o'}
如何检查行或列中的所有元素或任何对角线是否相同?
答案 0 :(得分:2)
你可以使用isequal
并使用它可以接受多个参数的事实,索引单元格数组可以创建以逗号分隔的列表:
:
>> isequal(a{2,:})
ans =
0
第三栏:
>> isequal(a{:,3})
ans =
1
对角线:
>> isequal(a{logical(eye(size(a)))})
ans =
1
反对角:
>> isequal(a{flipud(logical(eye(size(a))))})
ans =
0
答案 1 :(得分:1)
使用unique
,少量diff
以及any, all
%// Tag each cell element based on their uniqueness among other cells
[~,~,idx] = unique(a)
ar = reshape(idx,size(a))
%// Perform checks along columns, rows, diagonals and anti-diagonals
col_check = any(all(diff(ar,[],1)==0,1))
row_check = any(all(diff(ar,[],2)==0,2))
diag_check = all(diff(ar(eye(3)==1))==0)
antidiag_check = all(diff(ar(fliplr(eye(3))==1))==0)
%// Finally check if any of the checks are true for the final output
out = col_check | row_check | diag_check | antidiag_check
示例运行 -
a =
'x' '' 'o' 'o'
'' 'o' 'o' 'o'
'o' 'o' 'o' 'x'
'o' 'o' 'o' 'o'
col_check =
1
row_check =
1
diag_check =
0
antidiag_check =
0
out =
1