To find a vector subset of a matrix in sequence?

조회 수: 2 (최근 30일)
Vishal Sharma
Vishal Sharma 2017년 1월 27일
댓글: Vishal Sharma 2017년 1월 27일
I have a vector A = [1 2 3] And another matrix B = [2 3 4 1; 1 2 3 4; 2 4 1 3; 2 3 1 4]
I want to know which row of vector A is subset of Matrix B (in same sequence of A, i.e. 1 2 3
The answer is 2nd row of B matrix

채택된 답변

Thibaut Jacqmin
Thibaut Jacqmin 2017년 1월 27일
Here is a solution in one line :
A = [1 2 3];
B = [2 3 4 1; 1 2 3 4; 2 4 1 3; 2 3 1 4];
% Reshape B in a 1D array (all rows in a line)
C = reshape(B', [1, numel(B)]);
% Then use strfind to find a pattern in a string pattern within a string
linear_index = strfind(C, A);
% Compute the row number of the pattern knowing the initial number of columns
row_number = ceil(linear_index/size(B, 2));
% Or do it in a single line :
row_number = ceil(strfind(reshape(B', [1, numel(B)]), A)/size(B, 2));
  댓글 수: 2
Jan
Jan 2017년 1월 27일
A good idea.
The current version fails, if the searched vector appears over the margins:
B = [2 3 4 1; 2 3 1 4]
But you can filter all occurrences, which do not start between 1 and size(B,2)-length(A).
Vishal Sharma
Vishal Sharma 2017년 1월 27일
please suggest code for this case

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by