Read .mat file in Python. But the shape of the data changed
<pre><code> % save .mat file in the matlab    
train_set_x=1:50*1*51*61*23;   
train_set_x=reshape(train_set_x,[50,1,51,61,23]);   
save(['pythonTest.mat'],'train_set_x','-v7.3');
</code></pre>

<p>The data obtained in the matlab is in the size of (50,1,51,61,23).</p>

<p>I load the .mat file in Python with the instruction of this <a href="http://stackoverflow.com/questions/874461/read-mat-files-in-python">link</a>.</p>

<p>The code is as follows:</p>

<pre><code>import numpy as np, h5py
f = h5py.File('pythonTest.mat', 'r')
train_set_x = f.get('train_set_x')
train_set_x = np.array(train_set_x)
</code></pre>

<p>The output of train_set_x.shape is <code>(23L, 61L, 51L, 1L, 50L)</code>. It is expected to be <code>(50L, 1L, 51L, 61L, 23L)</code>. So I changed the shape by </p>

<pre><code>train_set_x=np.transpose(train_set_x, (4,3,2,1,0))
</code></pre>

<p>I am curious about the change in data shape between Python and matlab. Is there some errors in my code?</p>

<p>You do not have any errors in the code. There is a fundamental difference between Matlab and python in the way they treat multi-dimensional arrays.<br>
Both Matalb and python store all the elements of the multi-dim array as a single contiguous block in memory. The difference is the order of the elements:<br>
<strong>Matlab</strong>, (like fortran) stores the elements in a column-first fashion, that is storing the elements according to the dimensions of the array, for 2D:</p>

<pre><code> [1 3;
  2 4]
</code></pre>

<p>In contrast, <strong>Python</strong>, stores the elements in a row-first fashion, that is starting from the <em>last</em> dimension of the array:</p>

<pre><code>[1 2;
 3 4];
</code></pre>

<p>So a block in memory with <em>size</em> <code>[m,n,k]</code> in Matlab is seen by python as an array of <em>shape</em> <code>[k,n,m]</code>.</p>

<p>For more information see <a href="https://en.wikipedia.org/wiki/Row-major_order" rel="nofollow">this wiki page</a>.</p>

<p>BTW, instead of transposing <code>train_set_x</code>, you might try setting its order to "Fortran" order (col-major as in Matlab):</p>

<pre><code> train_set_x = np.array(train_set_x, order='F')
</code></pre>

python matlab numpy file-io mat-file