remove numbers in an array that are equal to the previous number in matlab

Here is one approach to removing numbers in an array that are equal to the previous number. We can loop through the array and compare the current element to the previous element. If they are equal, we delete the current element using the delete function.

main.m
% create example array
arr = [1 2 3 3 4 5 6 6];

% loop through array
for i = length(arr):-1:2
    if arr(i) == arr(i-1)
        arr(i) = [];
    end
end

% display modified array
disp(arr);
191 chars
13 lines

In this example, the desired array is [1 2 3 4 5 6]. The length(arr):-1:2 notation produces a vector that counts down from the length of the array to 2. This allows us to loop through the array in reverse order, which is necessary when deleting elements. The if statement checks if the current element is equal to the previous element. If it is, we delete the current element using arr(i) = []. Finally, we display the modified array using disp(arr) to confirm that the duplicates have been removed.

gistlibby LogSnag