I am aware that this question has been asked but i am not able to find the answer yet. Any help is very much appreciated
In Matlab it is written as: [C,ia,ic] = unique(A)
I am interested in all output elements i.e., C, ia and ic
A = [9 2 9 5];
Find the unique values of A and the index vectors ia and ic,
such that C = A(ia) and A = C(ic).
[C, ia, ic] = unique(A)
C = 1×3
2 5 9
ia = 3×1
2
4
1
ic = 4×1
3
1
3
2
How can I reproduce this in python please? As mentioned, i am interested in all output elements i.e., C, ia and ic
A solution using numpy.unique (thanks to @SBad himself for improving the quality of the solution):
import numpy as np
A = np.array([9,2,9,5])
C, ia, ic = np.unique(A, return_index=True, return_inverse=True)
print(C)
print(ia)
print(ic)
output
[2 5 9]
[1 3 0]
[2 0 2 1]
with list comprehension you can also get ic as:
ic = [i for j in A for i,x in enumerate(C) if x == j]
Note:
Remember that MATLAB uses 1 (one) based indexing, while Python uses 0 (zero) based indexing.
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