[Python] Why does np.unique return fewer/more unique rows than MATLAB’s unique with identical...

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to replicate MATLAB behavior using NumPy in Python.

    I have a 2D matrix of shape (248, 2) in both MATLAB and Python (via NumPy). When I use the unique function to filter out duplicate rows:

    • MATLAB’s unique(A, 'rows') returns shape (240, 2)
    • NumPy’s np.unique(A, axis=0) returns shape (232, 2)

    Why is there a difference in the number of unique rows, even though the input matrices are the same?

    I suspect it has to do with floating-point precision. Does MATLAB use a tolerance internally for comparing rows in unique? And if so, how can I replicate MATLAB’s behavior accurately in NumPy?

    Code I’m using:

    # Example: MATLAB
    a = unique(a, ‘rows’)


    # Trying to mimic MATLAB behavior
    unique_rows = np.unique(a, axis=0)
    print("Shape after unique:", a.shape)`

    Continue reading...

Compartilhe esta Página