How to remove repeating elements but maintain occurrences in an array?

15 ビュー (過去 30 日間)
Vignesh
Vignesh 2015 年 2 月 12 日
コメント済み: Vignesh 2015 年 2 月 15 日
Is there a way that I can get the first occurrence of consecutively repeating values, even if the same value occurs at few different places in the matrix?
Say I have a matrix
X=[2 2 2 2 -1 -1 -1 6 6 6 6 6 5 5 5 2 2 2 2 7 7 6 6]
I want the result to be
ans=[2 -1 6 5 2 7 6].
I've checked a similar question How to remove repeating elements from an array but using unique and keeping the same order as original matrix gives
ans=[2 -1 6 5 7].
I know I can use a loop like below. But I was wondering if there's a function for this.
for i=1:(length(X)-1)
if (X(i+1,6)-X(i,6))~=0
ans(i,1)=X(i+1,6);
else
ans(i,1)=NaN;
end
end
A function to do this will be great.
  3 件のコメント
Image Analyst
Image Analyst 2015 年 2 月 12 日
I would not use ans as the name of a variable - that has a special meeting in MATLAB.
Vignesh
Vignesh 2015 年 2 月 15 日
Thanks Stephen! That helped. Image Analyst, it was just an example for the question. Thanks for pointing out anyway.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2015 年 2 月 12 日
編集済み: Stephen23 2015 年 2 月 12 日
You could do this with diff:
>> X=[2 2 2 2 -1 -1 -1 6 6 6 6 6 5 5 5 2 2 2 2 7 7 6 6];
>> Y = [true,diff(X)~=0];
>> X(Y)
ans = [2,-1,6,5,2,7,6]
This works well with integers. If you are working with floating point numbers, then you might need to include some kind of tolerance in the diff:
>> Y = [true,abs(diff(X))>tol];
  1 件のコメント
Stephen23
Stephen23 2015 年 2 月 12 日
編集済み: Stephen23 2015 年 2 月 12 日
If you want this as a function, then you can easily define your own:
>> start = @(v)v([true,diff(v)~=0]);
>> start(X)
ans = 2 -1 6 5 2 7 6

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by