15.12.2012 Views

scipy tutorial - Baustatik-Info-Server

scipy tutorial - Baustatik-Info-Server

scipy tutorial - Baustatik-Info-Server

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

octave:11> my_struct = struct(’field1’, 1, ’field2’, 2)<br />

my_struct =<br />

{<br />

field1 = 1<br />

field2 = 2<br />

}<br />

octave:12> save -6 octave_struct.mat my_struct<br />

We can load this in Python:<br />

SciPy Reference Guide, Release 0.8.dev<br />

>>> mat_contents = sio.loadmat(’octave_struct.mat’)<br />

>>> print mat_contents<br />

{’my_struct’: array([[]], dtype=object), ’__vers<br />

>>> oct_struct = mat_contents[’my_struct’]<br />

>>> print oct_struct.shape<br />

(1, 1)<br />

>>> val = oct_struct[0,0]<br />

>>> print val<br />

<br />

>>> print val.field1<br />

[[ 1.]]<br />

>>> print val.field2<br />

[[ 2.]]<br />

In this version of Scipy (0.7.1), Matlab structs come back as custom objects, called mat_struct, with attributes<br />

named for the fields in the structure. Note also:<br />

>>> val = oct_struct[0,0]<br />

and:<br />

octave:13> size(my_struct)<br />

ans =<br />

1 1<br />

So, in Matlab, the struct array must be at least 2D, and we replicate that when we read into Scipy. If you want all<br />

length 1 dimensions squeezed out, try this:<br />

>>> mat_contents = sio.loadmat(’octave_struct.mat’, squeeze_me=True)<br />

>>> oct_struct = mat_contents[’my_struct’]<br />

>>> oct_struct.shape # but no - it’s a scalar<br />

Traceback (most recent call last):<br />

File "", line 1, in <br />

AttributeError: ’mat_struct’ object has no attribute ’shape’<br />

>>> print oct_struct<br />

<br />

>>> print oct_struct.field1<br />

1.0<br />

Saving struct arrays can be done in various ways. One simple method is to use dicts:<br />

>>> a_dict = {’field1’: 0.5, ’field2’: ’a string’}<br />

>>> sio.savemat(’saved_struct.mat’, {’a_dict’: a_dict})<br />

1.11. File IO (<strong>scipy</strong>.io) 83

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!