Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SciPy Matlab Arrays

SciPy Matlab Arrays

NumPy provides methods to save data in a Python-readable format.

SciPy provides methods for interacting with Matlab.

SciPy's scipy.io module provides many functions to handle Matlab arrays.

Export Data in Matlab Format

savemat() The method can export data in Matlab format.

The method's parameters are:

Export the array as the variable "vec" to a mat file:

Example

from

scipy

import

io

import

numpy

as

np

arr

=

np.

arange

(

10

)

io.

savemat

(

'arr.mat'

,

{

"vec"

: arr

}

)

**Note:** The code above will save a file named "arr.mat" on your computer.

Import Data in Matlab Format

The loadmat() method can import Matlab format data.

The method's parameters:

Returns a structured array whose keys are variable names and whose corresponding values are variable values.

The following example imports an array from a mat file:

Example

from

scipy

import

io

import

numpy

as

np

arr

=

np.

array

(

[

0

,

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

]

)

Export

io.

savemat

(

'arr.mat'

,

{

"vec"

: arr

}

)

Import

mydata

=

io.

loadmat

(

'arr.mat'

)

print

(

mydata

)

The returned result is as follows:

{

   '__header__': b'MATLAB 5.0 MAT-file Platform: nt, Created on: Tue Sep 22 13:12:32 2020',

   '__version__': '1.0',

   '__globals__': [],

   'vec': array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

 }

Use the variable name "vec" to display only the array of the matlab data:

Example

from

scipy

import

io

import

numpy

as

np

arr

=

np.

array

(

[

0

,

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

]

)

Export

io.

savemat

(

'arr.mat'

,

{

"vec"

: arr

}

)

Import

mydata

=

io.

loadmat

(

'arr.mat'

)

print

(

mydata

[

'vec'

]

)

The returned result is as follows:



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

From the result, you can see that the array was originally one-dimensional, but it gained a dimension when extracted, becoming a two-dimensional array.

To solve this problem, you can pass an extra parameter squeeze_me=True:

Example

from

scipy

import

io

import

numpy

as

np

arr

=

np.

array

(

[

0

,

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

]

)

Export

io.

savemat

(

'arr.mat'

,

{

"vec"

: arr

}

)

Import

mydata

=

io.

loadmat

(

'arr.mat'

,

squeeze_me

=

True

)

print

(

mydata

[

'vec'

]

)

The returned result is as follows:



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