Finding sequence in matrix

I have a matrix and I want find which row contains some sequence. For example:
  • A= [8 5 2 3 -1 0 4 -2 5 0 0 0
  • | 5 3 4 -2 1 6 -1 -3 0 0 0 0|
  • | -1 3 5 2 0 4 2 0 0 0 0 0];|
  • and sequence is:
  • seq=[4 -2 1];
  • Result shoulde be:
  • Result=2
  • I tried to use xcorr function like this:
  • [m n]=size(A);
  • for i=1:m
  • fi(i)=max((xcorr(A(i,:),seq)));
  • end
  • [no index]=max(fi);
  • result=index
  • But it doesnt work in some cases. Thanks for any help.

 채택된 답변

per isakson
per isakson 2013년 3월 11일

1 개 추천

If
  • speed matters
  • the elements of the matrix are integers
This old trick does it
A= [8 5 2 3 -1 0 4 -2 5 0 0 0
5 3 4 -2 1 6 -1 -3 0 0 0 0
-1 3 5 2 0 4 2 0 0 0 0 0];
seq=[4 -2 1];
ix = strfind( reshape( transpose( A ), 1, [] ), seq );
ixr = ceil( ix / size( A, 2 ) );
Recipe
  • convert A "row-wise" to a row
  • use strfind to find the start of seq: ix
  • find out to which row ix belongs

추가 답변 (1개)

Image Analyst
Image Analyst 2013년 3월 11일

1 개 추천

Try this:
A= [8 5 2 3 -1 0 4 -2 5 0 0 0
5 3 4 -2 1 6 -1 -3 0 0 0 0
-1 3 5 2 0 4 2 0 0 0 0 0]
template = [4 -2 1]
% Here's how to do it.
out = normxcorr2(template, A)
[row, column] = find(out == 1)

댓글 수: 3

Image Analyst
Image Analyst 2013년 3월 11일
Forgot to mention that it requires the Image Processing Toolbox.
Viktor
Viktor 2013년 3월 31일
thanks, but it doesnt work correctly.
Image Analyst
Image Analyst 2013년 3월 31일
Funny -- I just copied and pasted and it ran perfectly. Why do you say it doesn't work?

댓글을 달려면 로그인하십시오.

카테고리

태그

질문:

2013년 3월 11일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by