pproctor
pproctor

Reputation: 101

Accesing a matrix within a .mat file with python

I'm translating matlab code to python. I have a few matrices within a .mat file called 'AK_1'. I only want to access the data in one of these matrices. The matlab code accesses it this way where .response1 is the desired matrix:

numtrials1 = subject_data1.response1(1,:);

I tried loading all the data into a dict so I could then loop through it to the desired matrice with this code but that did not produce a workable result.

subject_data1_dict = {}

subject_data1 = scipy.io.loadmat('./MAT_Data_Full_AAAD_V2/AK_1.mat', subject_data1_dict)

How can I access only the matrix 'response1' within the file AK_1.mat?

Upvotes: 0

Views: 854

Answers (2)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22215

Say you have a myfile.mat with the following struct S:

S = 
    response1: [5x5 double]
    response2: [5x5 double]
    response3: [5x5 double]

And you want to access response1 from python. Then:

>>> from scipy.io import loadmat
>>> D = loadmat("myfile.mat", variable_names = ("S",) )
>>> D["S"]["response1"]   # returns matlab's S.response1

If you wanted to select more variables contained in the file than just S, you just add them in the tuple, i.e. variable_names=("S","otherVar")

Obviously, if all you're interested in is the response1 array, you can bypass collecting the dictionary altogether, i.e.:

>>> response1 = loadmat("myfile.mat", variable_names = ("S",) )["S"]["response1"]
>>> response1
array([[ array([[ 9,  1,  2,  2,  7],
       [10,  3, 10,  5,  1],
       [ 2,  6, 10, 10,  9],
       [10, 10,  5,  8, 10],
       [ 7, 10,  9, 10,  7]], dtype=uint8)]], dtype=object)

Upvotes: 1

jlarsch
jlarsch

Reputation: 2307

create and save a structure containing 3 matrices in matlab:

a=1:5
b.aa=a
b.bb=a
b.cc=a
save(struct.mat,'b')

load .mat file in python

from scipy.io import loadmat
matfile = loadmat('d:/struct.mat')

you can now access for example b.aa and b.bb via:

matfile[('b')][0][0][0]
matfile[('b')][0][0][1]

Is that what you wanted?

Upvotes: 0

Related Questions