Find if two numbers occurs in the same sequence

12 次查看(过去 30 天)
Hello
I would like to know how to determine if numbers occur in the same sequence.
[3 1 5 0 0
1 2 5 0 0
1 3 4 1 5
2 1 5 0 0]
For example in row 1 , we can see that 1 is followed by a 5. Now I need to determine if the same happens in row 2. But in this case 1 is followed by a 2 and then 5.
In that case I need to delete the second row and check with the third row.
When I compare row 1 and row 3 , though 1 is followed by a 5 , 3 should be followed by a 1 in row 1. But in row 3, 3 is followed by a 4, so need to delete this as well.
When you compare row 1 and row 4, since 1 is followed by a 5 in both cases I retain row 4 ( even though the first numbers are different).
So my final answer should be.
[3 1 5 0 0
2 1 5 0 0]
If a row is retained , then the checking needs to start from that row on wards. That is row 4 will now be checked with row 5 and not row 1.
I hope I have explained it correctly, if not I will clear it out better if anyone has any questions.I am not sure how to proceed and any help would be appreciated. Thanks in advance
  2 个评论
Ced
Ced 2014-10-22
编辑:Ced 2014-10-22
How big are the matrices in question? Do you know which numbers can be present?
The easiest (note: inefficient) way I can think of right now is to do it in two steps:
Step 1: Set up a matrix, where e.g. column 1 contains all occurring numbers, and column 2 the numbers that should come after them.
Step 2: iterating over column one, look for each occurrence of the value in your matrix, check if the next value matches your value from column 2, and act accordingly.
Guillaume
Guillaume 2014-10-23
For your information I've turned a variation of this question into a cody problem.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2014-10-22
Does this do what you want?
m = [3 1 5 0 0
1 2 5 0 0
1 3 4 1 5
2 1 5 0 0];
out = m(1, :); %output matrix
comprow = 1; %row that must be matched
for row = 2:size(m, 1) %iterates from row 2 onwards
[~, match] = ismember(m(row, :), nonzeros(m(comprow, :))); %find positions of numbers in common, ignoring 0s
%we now need to make sure that the elements that match are in sequence, that is that the
%min of match (ignoring 0, unmmatched element) to the max of match are in sequence.
%strfind also find sequences in numbers
minpos = min(nonzeros(match));
maxpos = max(match);
if strfind(match, minpos:maxpos) %works with numbers as well
out(end+1, :) = m(row, :); %match, then copy
comprow = row; %use current row for further comparison
end
end
  5 个评论
Guillaume
Guillaume 2014-10-22
Alright, then you just change the if to:
if strfind(match, minpos:maxpos) && ~isequal(m(row, :), m(comprow, :))

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by