MATLAB sort() vs Numpy argsort() - how to match results?
<p>I'm porting a MATLAB code to Python's Numpy.</p>

<p>In MATLAB (Octave, actually), I have something like:</p>

<pre><code>&gt;&gt; someArr = [9, 8, 7, 7]
&gt;&gt; [~, ans] = sort(someArr, 'descend')
   ans =
   1   2   3   4
</code></pre>

<p>So in Numpy I'm doing:</p>

<pre><code>&gt;&gt;&gt; someArr = np.array([9, 8, 7, 7])
&gt;&gt;&gt; np.argsort(someArr)[::-1]
array([0, 1, 3, 2])
</code></pre>

<p>I got <code>1, 2, 3, 4</code> in MATLAB while <code>0, 1, 3, 2</code> on Numpy, and I need <code>0, 1, 2, 3</code> on Numpy.  </p>

<p>I believe it due to the sorting algorithm used in each function, But I checked and it looks like both are using "quicksort" (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow">here</a> and <a href="https://www.mathworks.com/matlabcentral/answers/96656-what-type-of-sort-does-the-sort-function-in-matlab-perform" rel="nofollow">here</a>). </p>

<p>How can I match the Numpy's solution to the MATLAB one?</p>

<p>You can choose between different sorting algorithms. Changing it to <code>heapsort</code> worked for me:</p>

<pre><code>&gt;&gt; np.argsort(someArr, kind="heapsort")[::-1]
array([0, 1, 2, 3], dtype=int32)
</code></pre>

<p>Edit: This only works for a few test cases I looked at. For <code>[9, 8, 7, 7, 4, 1, 1]</code> it stops working. My answer is probably not a good solution.</p>

python matlab sorting numpy