矩阵中的高级搜索,以查找具有特殊特征的行

时间:2016-08-07 07:51:07

标签: matlab

我需要找到具有以下内容的行:
a)行中所有元素的总和= 6
b)行中的两个连续元素= 1,行中其他三个连续元素= 0

例如,
给出以下矩阵: -

X=[ 0  0  1  0  1  1  0  0  0  1  0  0  1  0  0  0  1  0  0  0  0;
    1  1  1  0  1  1  0  0  1  0  0  0  0  0  0  1  1  0  0  0  0; 
    0  0  0  1  1  1  0  0  0  1  1  1  0  0  0  1  1  1  0  1  1; 
    1  1  1  1  1  1  1  1  0  0  0  0  0  1  1  1  1  1  0  0  0;
    0  0  1  0  1  1  0  0  0  1  0  0  1  0  0  0  1  0  0  0  0]

上述特征仅在第1行和第5行 所以我想把这些行作为答案。

1 个答案:

答案 0 :(得分:0)

X=[ 0  0  1  0  1  1  0  0  0  1  0  0  1  0  0  0  1  0  0  0  0;
    1  1  1  0  1  1  0  0  1  0  0  0  0  0  0  1  1  0  0  0  0; 
    0  0  0  1  1  1  0  0  0  1  1  1  0  0  0  1  1  1  0  1  1; 
    1  1  1  1  1  1  1  1  0  0  0  0  0  1  1  1  1  1  0  0  0;
    0  0  1  0  1  1  0  0  0  1  0  0  1  0  0  0  1  0  0  0  0];

sum6rows=find(sum(X,2)==6);   %finding the row numbers that meet condition-1
if sum6rows
req=X(sum6rows,:); %storing the rows in a variable which meet condition-1 
%now finding the row numbers that also meet condition-2
test=mat2str(req) ; % Converting the matrix into a string
j=unique(ceil(findstr([test(2:end-1)], '1 1 0 0 0')/(2*(size(X,2))))); %finding our pattern in the string
req=req(j.',:); % removing those rows which don't meet condition-2
end
相关问题