Furla94
Furla94

Reputation: 59

Remove repeating consecutive elements from array

I need some help with arrays in MATLAB:
Imagine have an array like this

a = [1,1,1,1,2,2,4,4,4,7,7,7,1,1,1,1]  

to and like to get this array:

b = [1,2,4,7,1]

How can I do this?

Upvotes: 1

Views: 125

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25232

Just index your array with its differences:

b = a( [true  logical( diff(a(:)).') ] )

b =

     1     2     4     7     1

Upvotes: 3

Tanvir Hossain
Tanvir Hossain

Reputation: 34

a = [1,1,1,1,2,2,4,4,4,7,7,7,1,1,1,1];
b = [];
length = size(a);
i = 1;
while i<=length 
    if(a(1,i) ~= a(1,i-1))
        b(1,i) = a(1,i);
    end
    i = i+1;
end
disp(b);

hope it will help.

Upvotes: 0

Related Questions