Hello,
i need to remove duplicates form my matrix, but only if they are consecutive duplicates.
Lets suppose i have the following list of coordinates in a matrix, with for example x, y and z coordinates, that is describing a path.
A=[ 1, 0, 3
2, 1, 3
2, 1, 3
2, 2, 3
1, 0, 3]
Now, you can see that the point [2, 1, 3] is a consecutive duplicate, that I want to remove (because it's unuseful information).
But I do not want to remove the (duplicate) row at the end, [1, 0, 3], even if this row is already there in the beginning.
Also, the sorting shouldn't be changed. The desired output should be
A=[ 1, 0, 3
2, 1, 3
2, 2, 3
1, 0, 3]
I cannot use 'unique' for that, because that would filter also the last line.
What is the smartest way to do that?
Thank you very much for your help!

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 11월 26일

1 개 추천

Try this
A=[ 1, 0, 3
2, 1, 3
2, 1, 3
2, 2, 3
1, 0, 3];
idx = find(~any(diff(A), 2))+1;
A(idx, :) = [];

댓글 수: 4

Simon Meyer
Simon Meyer 2020년 11월 26일
Yes, that works for this example.
Could you explain your answer a little bit so that I wont have problems using this for a much bigger project? :)
Thank you very much!
A=[ 1, 0, 3
2, 1, 3
2, 1, 3
2, 2, 3
1, 0, 3];
First apply the diff() on each column. It calculates difference of consecutive elements
>> diff(A)
ans =
1 1 0
0 0 0
0 1 0
-1 -2 0
Now I want the rows in which all elements are zero
>> ~any(diff(A), 2)
ans =
4×1 logical array
0
1
0
0
the number of rows are one less then the number of rows in A. Since first row can never be removed so I expand the vector like this
>> idx = [false; ~any(diff(A), 2)]
idx =
5×1 logical array
0
0
1
0
0
It shows the rows I want to remove. So I just remove them
>> A(idx, :) = []
A =
1 0 3
2 1 3
2 2 3
1 0 3
Simon Meyer
Simon Meyer 2020년 11월 30일
Thank you very much! :)
Ameer Hamza
Ameer Hamza 2020년 11월 30일
I am glad to be of help!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2020년 11월 26일

댓글:

2020년 11월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by