You can use the diff
function to find the difference between consecutive elements in the array. If the difference between two consecutive elements is zero, then they are the same number. You can use this information to create a logical index that marks the positions of the repeated numbers. Finally, you can use this index to remove the repeated numbers from the original array using the logical indexing.
Here's an example:
main.m179 chars10 lines
In this example, the diff
function is used to find which elements in arr
are equal to their previous elements. This creates a logical array diffs
, which is then combined with an initial false
to create a logical index indexes
. Finally, unique_arr
is created by using the logical index to remove the repeated numbers from arr
.
gistlibby LogSnag