Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract elements in an array that have multiple entries?

Tags:

arrays

matlab

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];
like image 741
Pete Avatar asked Jul 22 '15 17:07

Pete


People also ask

How do I extract multiple values from an array?

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.

How do you retrieve the number of elements in an array A?

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 store multiple pieces of data?

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.


3 Answers

The combination of unique and diff is enough, find is actually not necessary.

out = unique(data(~diff(data)))
like image 184
Robert Seifert Avatar answered Oct 24 '22 19:10

Robert Seifert


Here's another option using just hist and indexing:

result = data(hist(data, data) > 1);
like image 27
gnovice Avatar answered Oct 24 '22 20:10

gnovice


My one liner:

unique(data(find(diff(data)==0)))

Test it here!


Explanation:

  1. with diff you get the differences from one element to the next.

  2. As the array is previously ordered, the result of the above line will output zero on the repeated ones.

  3. With find(result_from_above == 0) I get where they live (indexes for zeroes)

  4. 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

like image 35
Mauricio Moraes Avatar answered Oct 24 '22 18:10

Mauricio Moraes