arraysidioms
Sort with Indices
[sorted_vals, idx] = sort(X) — one of those MATLAB idioms that breaks when ported naively.
MATLAB's `sort` returns both the sorted values and the original indices that produce that order. `np.sort` returns only values; `np.argsort` returns only indices. Neither is a drop-in. The converter recognizes the `[A, I] = sort(X)` idiom and rewrites to `A, I = sort_with_index(X)` — a helper in the matlabtopython-compat package that returns the pair MATLAB-style. `pip install matlabtopython-compat` and the import is added automatically.
MATLAB source9 lines
% Rank elements by value
scores = [87, 62, 95, 78, 85];
names = {'Alice', 'Bob', 'Carol', 'Dan', 'Eve'};
[sorted_scores, rank] = sort(scores, 'descend');
for i = 1:length(sorted_scores)
fprintf('%d. %s: %d\n', i, names{rank(i)}, sorted_scores(i));
endPython output (converter-generated)12 lines · 0 flags
import numpy as np
from matlabtopython_compat import sort_with_index
# Rank elements by value
scores = np.array([87, 62, 95, 78, 85])
names = 'Alice' + 'Bob' + 'Carol' + 'Dan' + 'Eve'
sorted_scores, rank = sort_with_index(scores, 'descend')
for i in range(1, np.max(sorted_scores.shape) + 1):
print(f'{i:d}. {names[rank[i - 1] - 1]}: {sorted_scores[i - 1]:d}')
Implementation notes
Uses the matlabtopython-compat runtime shim for sort_with_index. `pip install matlabtopython-compat` before running the output.Try it on your own MATLAB
Free for 50 lines. Same converter that produced the Python above.
More examples like this, once a week
New canonical conversions and release notes from the converter. One email, no spam.