1

I need to find the equivalent from matlab of A(:) in python. Where A is a matrix(m,n):

For example:

A =

 5     6     7
 8     9    10

A(:)

ans =

 5
 8
 6
 9
 7
10

thanks in advance!

dan1st
  • 12,568
  • 8
  • 34
  • 67
Nikko
  • 517
  • 3
  • 7
  • 19

2 Answers2

3

If you want the column-major result (to match the Matlab convention), you probably want to use the transpose of your numpy matrix, and then the ndarray.ravel() method:

m = numpy.array([[ 5, 6, 7 ], [ 8, 9, 10 ]])
m.T.ravel()

which gives:

array([ 5,  8,  6,  9,  7, 10])
rwp
  • 1,786
  • 2
  • 17
  • 28
  • I am sorry and which one would be the reverse operation? i.e. converting the result of m.T.ravel() into the m matrix? – Nikko Apr 19 '18 at 19:40
  • To reverse the operation, you could try `m.reshape((2,3), order='F')`, which uses the Fortran (column-major) ordering to repack the sequence of elements into a 2x3 matrix. – rwp Apr 20 '18 at 15:33
2

You can do this by reshaping your array with numpy.reshape

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.reshape.html

import numpy
m = numpy.array([[ 5, 6, 7 ], [ 8, 9, 10 ]])
print(numpy.reshape(m, -1, 'F'))
Patrik
  • 2,695
  • 1
  • 21
  • 36
S.MC.
  • 1,491
  • 2
  • 9
  • 17
  • You can use reshape to do that aswell! aMatrix = numpy.reshape(aVector,2,3) – S.MC. Apr 20 '18 at 00:11
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/19496178) – Draken Apr 20 '18 at 09:33
  • Okay, understood. – S.MC. Apr 20 '18 at 09:38