-3

Hi I am trying to convert some Matlab code to Python.

Here is the Matlab code:

[n,i] = sort(n);

n is already defined as an array with data, but i is not defined as anything in the entire code as far as I can see. This is what I tried to do:

[n,i] = n.sort(axis = 0)

But it said "'NoneType' object is not iterable"

I know that there is data in n, so how do I deal with i?

lower down in the matlab code I have:

y = y(i) 

What does this mean, and how do I convert this to Python?

  • What is `i` supposed to be? Are you just trying to sort an array? – Matt Messersmith May 07 '16 at 00:56
  • How is `n` defined as an array? – sco1 May 07 '16 at 01:02
  • I think i is supposed to be a number that corresponds to each value of the array in n. so if n = [2, 4, 5, 18] , i would just be [1,2,3,4] – Shivam Tewari May 07 '16 at 01:02
  • `i` holds the indices in the original array of the sorted elements. So if you used `[s,i]=sort(n)`, then `s(1)` would be the lowest value element in the sorted array, and `n(i(1))` would be the corresponding element in the original array. – beaker May 07 '16 at 01:05

2 Answers2

0

Is this straight python, or numpy?

In straight python, the sort method returns None. You can either call the sorted built-in:

n = sorted(n)

or use the sort method to sort the data in-place

n.sort()

The latter is more efficient.

If this data is a numpy object, you'll want to use the numpy methods, see http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.sort.html

Sorry, I don't know what the last MatLab expression means.

Roger Durham
  • 103
  • 6
0

So after looking at Matlab's documentation for sort, it looks like i represents the indices of the original elements. You can do this with numpy by using argsort, like this:

import numpy as np
n = np.array([3, 7, 1, 10, 9, 5, 7])
[n, i] = [np.sort(n), np.argsort(n)]

This will output:

[ 1  3  5  7  7  9 10]
[2 0 5 1 6 4 3]

for n and i respectively.

This is pretty inefficient if n is large (we're really sorting twice, here), but it's fairly readable. If speed really matters, I suggest using the method outlined here: How to get indices of a sorted array in Python

Community
  • 1
  • 1
Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52