[SciPy-User] Simple ndarray dim question?
Travis Oliphant
travis at continuum.io
Fri May 11 16:02:10 EDT 2012
On May 10, 2012, at 4:15 PM, Erik Kastman wrote:
> Hi all,
>
> Using SciPy and Matlab, I'm having trouble reconstructing an array to match what is given from a matlab cell array loaded using scipy.io.loadmat().
>
> For example, say I create a cell containing a pair of double arrays in matlab and then load it using scipy.io (I'm using SPM to do imaging analyses in conjunction with pynifti and the like)
>
> Matlab
>
>>> onsets{1} = [0 30 60 90]
>>> onsets{2} = [15 45 75 105]
>
> Python
>
>>>> import scipy.io as scio
>>>> mat = scio.loadmat('onsets.mat')
>>>> mat['onsets'][0]
> array([[[ 0 30 60 90]], [[ 15 45 75 105]]], dtype=object)
>
>>>> mat['onsets'][0].shape
>
> (2,)
>
> My question is this: **Why does this numpy array have the shape (2,) instead of (2,1,4)**? In real life I'm trying to use Python to parse a logfile and build these onsets cell arrays, so I'd like to be able to build them from scratch.
loadmat returns an array of *Python objects* because you have cell arrays. Each object in the outer NumPy array is probably a (1,4) NumPy array of a different type. To be sure look at
type(mat['onsets'][0][0])
and
mat['onsets'][0].shape
if the result of the first expression is an ndarray.
>
> When I try to build the same array from the printed output, I get a different shape back:
>
>>>> new_onsets = array([[[ 0, 30, 60, 90]], [[ 15, 45, 75, 105]]], dtype=object)
> array([[[0, 30, 60, 90]],
>
> [[15, 45, 75, 105]]], dtype=object)
>
>>>> new_onsets.shape
> (2,1,4)
Now you have an "object" array of shape (2,1,4) where each object happens to be a Python int. Normally you would make an array of "integers" or "floating point values".
You could build what you saw before with:
new_onsets = empty((2,), dtype=object)
new_onsets[0] = array([[0, 30, 60, 90]])
new_onsets[1] = array([[15, 45, 75, 105]])
-Travis
More information about the SciPy-User
mailing list