检查单元格数组的某些元素是否相同?

时间:2015-05-05 05:45:51

标签: matlab

是否有一种简单的方法可以检查行或列中的所有元素或任何对角线是否相同?

a={'o','','o';
   'x','o','o';
   'x','o','o'}

如何检查行或列中的所有元素或任何对角线是否相同?

2 个答案:

答案 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