I have a large vector that contains monotonically increasing data or a duplicate, looking something like this:
data = [0 1.1 2.2 3.3 4.4 4.4 4.4 4.4 5.5 6.6 6.6 6.6 7.7];
In this data set, I'm interested in the duplicate entries (in this case, 4.4
and 6.6
). I have a sorta clunky solution to extract these values, but I feel like MATLAB should have a one-liner solution to extract a result like
result = [4.4 6.6];
Slicing an Array To extract only a subset of the array, use the array_slice( ) function: $subset = array_slice (array , offset , length ); The array_slice( ) function returns a new array consisting of a consecutive series of values from the original array.
Retrieving the number of array elements in a simple array can most easily be done by using the CARDINALITY function and retrieving the maximum allowed size of an array can be done using the MAX_CARDINALITY function.
Can an array hold multiple values? Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
The combination of unique
and diff
is enough, find
is actually not necessary.
out = unique(data(~diff(data)))
Here's another option using just hist
and indexing:
result = data(hist(data, data) > 1);
My one liner:
unique(data(find(diff(data)==0)))
Test it here!
Explanation:
with diff
you get the differences from one element to the next.
As the array is previously ordered, the result of the above line will output zero on the repeated ones.
With find(result_from_above == 0)
I get where they live (indexes
for zeroes)
With data(result_from_above)
I get the repeated elements, and then
apply unique to get them.
Update:
You can use logical indexing, as @rayryeng said, you dont need the find
, then it becomes:
unique(data(diff(data)==0));
Then test it here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With