How to keep rows whose values follow a certain sequence?

조회 수: 3 (최근 30일)
Lu Da Silva
Lu Da Silva 2022년 2월 3일
댓글: Stephen23 2022년 2월 3일
I have a matrix composed of two columns A and B, I need to only keep the rows which contain the sequence 90-180-270:
A B A B
-------- ----------
90 1 90 1
180 9 180 9
270 2 270 2
90 0 -> 90 0
270 3 180 4
90 0 270 6
180 4
270 6
How can I implement this into a Matlab code?
  댓글 수: 5
Stephen23
Stephen23 2022년 2월 3일
편집: Stephen23 2022년 2월 3일
"It only includes three possible numbers: 180, 270 and 90. (I wrote 1 2 3 for simplicity reasons)."
It is more complex and slower. Because solutions that work with 1-2-3 might not work with other values. But because you gave us incorrect information we all spend our time developing solutions that might not suit your needs at all.
You should tell us the exact values and the exact order.
Lu Da Silva
Lu Da Silva 2022년 2월 3일
편집: Lu Da Silva 2022년 2월 3일
Yes, the actual sequence is 90, 180, 270. But that shouldn't matter, the code should work for any given sequence.

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

채택된 답변

Stephen23
Stephen23 2022년 2월 3일
편집: Stephen23 2022년 2월 3일
Here is an old MATLAB trick that you can use, which still works today:
Where M is your matrix and S is the desired sequence:
S = [90,180,270]; % the required sequence
M = [90,1;180,9;270,2;90,0;270,3;90,0;180,4;270,6]
M = 8×2
90 1 180 9 270 2 90 0 270 3 90 0 180 4 270 6
X = strfind(M(:,1).',S);
Y = X-1+(1:numel(S)).';
Z = M(Y,:)
Z = 6×2
90 1 180 9 270 2 90 0 180 4 270 6
  댓글 수: 3
Stephen23
Stephen23 2022년 2월 3일
@David Hill: just two steps: STRFIND and some simple indexing :)

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

추가 답변 (1개)

David Hill
David Hill 2022년 2월 3일
s=strfind(num2str(yourMatrix(:,1))','123');
newMatrix=[];
for k=1:length(s)
newMatrix=[newMatrix;yourMatrix(s(k):s(k)+2,:)];
end
  댓글 수: 2
Lu Da Silva
Lu Da Silva 2022년 2월 3일
I tried your suggestion but I get an error:
Error using strfind
First argument must be text
David Hill
David Hill 2022년 2월 3일
This should work.
r=yourMatrix(:,1);
r(r==90)=1;r(r==180)=2;r(r==270)=3;%change based on sequence desired
f=strfind(num2str(r)','123');
newMatrix=[];
for k=1:length(f)
newMatrix=[newMatrix;yourMatrix(f(k):f(k)+2,:)];
end

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

카테고리

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