1

In Matlab it is possible to access elements of a matrix linearly:

>> A=[1 2 3; 4 5 6]
A =
     1     2     3
     4     5     6
>> A(1)
ans =
     1
>> A(2)
ans =
     4
>> A(3)
ans =
     2

Looks like Matlab does reshape matrix on the fly.

Is it possible to do similar in Python?

If I do directly, it does not works:

A=[[1,2,3],[4,5,6]]

A[1]
Out[2]: [4, 5, 6]
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
  • 3
    MATLAB does not reshape on the fly. Data is stored in a single (column-major) column and *displayed* in the appropriate shape. Indexing with a single subscript is called [linear indexing](http://www.mathworks.com/help/matlab/math/matrix-indexing.html#f1-85511). Note that Python is row-major. – sco1 Feb 17 '16 at 18:50

2 Answers2

0

Try using np.ravel (for a 1D view) or np.flatten (for a 1D copy) or np.flat (for an 1D iterator) from module NumPy.

More information here: From ND to 1D arrays

Community
  • 1
  • 1
Tony Babarino
  • 3,355
  • 4
  • 32
  • 44
0

Python indexing starts at 0. For Matlab like functionality use Numpy:

import numpy as np
A = np.array([[1, 2], [3, 4]])

A.flatten()[0]

Yields: 1

wgwz
  • 2,642
  • 2
  • 23
  • 35