TAGS :Viewed: 10 - Published at: a few seconds ago

[ Matlab Searching and counting through values ]

I have the following two matrices

A=[1 2 3 4 5]
B=[4 5 7 8 9 4 1 2 3 4 5 8 7 9 4 2 1 6 1 2 3 4 5 4 8 9 6 4]

I need to find how many times A repeats in B and which are the following 5 values after that and put in a matrix.

Eg:

A search through B
Ans: C = [ 1 2 3 4 5 
           8 7 9 4 2 
           4 8 9 6 4]
N = 2 % numbers of times 

Answer 1


Use findstr to identify the sequences, it returns the indices of the ones. The remaining stuff is just a little indexing:

X=findstr(A,B);
Y=arrayfun(@(X)(B(X+numel(A):X+2*numel(A)-1)),X,'uni',false);
C=cat(1,A,Y{:});
N=numel(X);

Answer 2


Here's one approach, using bsxfun thrice:

%// Data
A = [1 2 3 4 5];
B = [4 5 7 8 9 4 1 2 3 4 5 8 7 9 4 2 1 6 1 2 3 4 5 4 8 9 6 4];
H = 5;

%// Computations:
s = bsxfun(@plus, 0:numel(B)-numel(A), (1:numel(A)).'); %'
ind = find(all(bsxfun(@eq, B(s), A(:)))); %// or im2col(B(:),[numel(A) 1]) instead of B(s)
N = numel(ind);
C = B(bsxfun(@plus, ind(:)+numel(A), 0:H-1));
C = [A; C];

In your example:

>> C
C =
     1     2     3     4     5
     8     7     9     4     2
     4     8     9     6     4
>> N
N =
     2