checking for dependency in the previous row?

조회 수: 1 (최근 30일)
abhisrisai
abhisrisai 2019년 7월 10일
댓글: abhisrisai 2019년 7월 11일
Hi,
My doubt is regarding accessing the previous 'n' rows, but the catch is, that 'n' is not constant or predefined.
For example :
A = [1 2 3 4; 5 6 7 8; 1 2 3 4; 1 2 3 4; 9 10 11 12]
I want to check for how many previous 'n' rows am I obtaining the same value continiously. In the above example, I know that for the 4th row, I'm getting the same number pattern in the third row. But later from my simulations which contains more than 5000 rows, I might obtain a same value for more than 10 rows continously and a few rows later, might see the same pattern but this time for 6 rows. I have to manually count them everytime.
How can I do this through matlab?
Thank you for the help.
  댓글 수: 3
abhisrisai
abhisrisai 2019년 7월 10일
편집: abhisrisai 2019년 7월 10일
Hi @AdamDanz,
Thanks for the immediate response.
Let's say im interested in the sequence 1 2 3 4 which has occurred atleast twice (sorry I didnt mention that in question).
From your matrix, i can see that rows 3 and 4 have repeated. similarly, rows 6-9 have also repeated.
So the output im expecting is an extra column in the end, which indicates the number of times the sequence has appeared continously before. so for your matrix, row 4 will have a value 2 in the output column and similarly row 9 will have a value of 4 in the output column.
Thank you.
Adam Danz
Adam Danz 2019년 7월 10일
Got it. See answer.

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

채택된 답변

Adam Danz
Adam Danz 2019년 7월 10일
편집: Adam Danz 2019년 7월 10일
Here's a demo that counts the consecutive rows of "data" (a matrix) that match "key" (a row vector). The variable "consecutiveCounter" is the output and is concatenated to the end of the data matrix.
% Produce demo data
data = [
1 2 3 4
5 6 7 8
1 2 3 4
1 2 3 4
9 10 11 12
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
9 10 11 12
9 10 11 12
0 0 0 0];
key = [1,2,3,4];
keyMatch = all(data == key,2);
dMatch = diff([false; keyMatch==1; false]);
S1 = find(dMatch == 1); % start indices of these sequences
S2 = find(dMatch == -1); % end indices
idxCell = arrayfun(@(x1,x2)((x1:x2-1)-x1+1)',S1,S2,'UniformOutput',false);
consecutiveCounter = zeros(size(keyMatch));
consecutiveCounter(keyMatch==1) = cell2mat(idxCell);
% If you want to add that as a 5th column,
dataNew = [data, consecutiveCounter];
Result
dataNew =
1 2 3 4 1
5 6 7 8 0
1 2 3 4 1
1 2 3 4 2
9 10 11 12 0
1 2 3 4 1
1 2 3 4 2
1 2 3 4 3
1 2 3 4 4
9 10 11 12 0
9 10 11 12 0
0 0 0 0 0
  댓글 수: 1
abhisrisai
abhisrisai 2019년 7월 11일
Thank you very much for the help! It's as expected. :)

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

추가 답변 (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