UNIQUE Function
Returns a vector (one-dimensional array) containing the unique elements from another vector.
Usage
result = UNIQUE(vec)
Input Parameters
vec—A vector containing duplicate values.
Returned Value
result—A new vector containing the unique elements of the original vector in ascending order.
Keywords
None.
Discussion
This function works on any vector (one-dimensional array) variable. The returned value of string arrays are sorted using the ASCII collating sequence.
Example 1
For a very simple example, suppose you have a vector defined as:
vec = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
; The following command produces a new vector
; containing only the unique elements of vec:
result = UNIQUE(vec)
PRINT, result
; PV-WAVE prints: 1 2 3 4 5
Example 2
With UNIQUE, you can determine the unique values in any column of a table.
For example, a table called phone_data contains information on phone calls made during a three-day period. This table contains eight columns of phone information: the date, time, caller’s initials, phone extension, area code of call, number of call, duration, and cost. (For more information on the structure of this table, see the PV‑WAVE User’s Guide.)
To obtain a list of the dates on which calls were made.
RESTORE, !Data_Dir + 'phone_example.sav'
dates = UNIQUE(phone_data.DATE)
PRINT, dates
; PV-WAVE prints: 901002 901003 901004
note | Tables are represented as an array of structures. In this command, phone_data.DATE represents the DATE field of the structure called phone_data. |
The result is a one-dimensional variable called dates that contains a list of the dates on which calls were made.
Example 3
In some applications, it may be possible to generate the text for menu buttons from the unique elements in a table column. For example, the following commands display a menu of dates. The menu selection is then passed into the QUERY_TABLE function where the total cost of calls is calculated for that date.
RESTORE, !Data_Dir + 'phone_example.sav'
; Find the unique dates in the phone_data table.
PM, phone_data.DATE
unique_date = UNIQUE(phone_data.DATE)
; Display a menu of unique dates. The menu selection returns
; the selected date to the variable date_pick. Note that the
; parameter passed to TVMENU must be type string.
date_pick = unique_date (TVMENU(STRING(unique_date)))
; Find the total cost of calls made on the selected date.
total_cost = QUERY_TABLE(phone_data, $
'DATE, SUM(COST) Where DATE = ' + 'date_pick Group By DATE')
PRINT, 'Total cost for selected date: ', total_cost
See Also