SPMのユーザーはMATLABを使いますが、Pythonを利用した脳画像解析用プログラムもたくさんあります。scipy.io.loadmat, scipy.io.savematを利用して、PythonからMatlabへ、あるいはその逆というように、脳データをプログラミング言語に応じてフォーマットを変える方法を知っていると便利です。このPythonのスクリプトでは、npyでデータをsaveしています。Pythonのdictionary形式はMatlabのmatファイルに変換できることを覚えておきましょう。
import numpy as N
from scipy import io
from scipy.io import loadmat
mu, sigma = 0, 0.1 # mean and standard deviation
data=N.random.normal(mu, sigma, 1000) #Generating 1000 real numbers following the standard normal distribution
dataplus=[x for x in data if x>0] #extracting values > 0 from data
lendataplus=len(dataplus)
numbereddataplus=[0]*lendataplus #Initialization
for i in range(lendataplus):
numbereddataplus[i]=[i,dataplus[i]]
"""
numbereddataplus returns something like
[[0, 0.078272729925686457],
[1, 0.13697490399651532],
[2, 0.04744210038526795],
[3, 0.038804128600632967],
[4, 0.041290024546932265],
...
[503, 0.34114032106343845],
[504, 0.039543806717148904],
[505, 0.21131624678657551]]
"""
N.save('numbereddataplus.npy', numbereddataplus) #saving data as a npy file.
pydata=N.load('numbereddataplus.npy')
#This time we save this data so that it will be reused on Matlab.
io.savemat('pydata.mat', mdict={'numbereddataplus':pydata}) #saving a data available for Matlab uses the dictionary format in Python
"""
%Now launching your Matlab and loading 'pydata.mat'...
>> pydata=load('pydata.mat');
%Clicking the variable in workspace, you see a field named 'numbereddataplus', with values of <around 500 * 2 double>
>>pydata.numbereddataplus
%returns 'ans'
>>matdata=pydata.numbereddataplus
%We are going to save only matdata under the name of 'matdata.mat'
>>clearvars -except matdata
>>save('matdata.mat','matdata')
"""
#Now we go back to Python. We need to 'loadmat' in 'scipy.io' to load a Matlab file on Python.
pydataagain=loadmat('matdata.mat')
"""
In [48]: pydataagain
#pydataagain returns something like that.
Out[48]:
{'__globals__': [],
'__header__': 'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Tue Apr 29 15:18:37 2014',
'__version__': '1.0',
'matdata': array([[ 0.00000000e+00, 5.15108198e-02],
[ 1.00000000e+00, 7.16411029e-02],
[ 2.00000000e+00, 1.06825954e-01],
[ 3.00000000e+00, 1.31675693e-01],
[ 4.00000000e+00, 1.03511925e-01],
[ 5.00000000e+00, 4.21006635e-02],
...
[ 4.93000000e+02, 1.25338019e-01],
[ 4.94000000e+02, 2.44409350e-02],
[ 4.95000000e+02, 1.12179070e-01]])}
#This is a mapping object.
"""
pymatdata=pydataagain['matdata']#use the key.
"""
In [52]: pymatdata[0]
Out[52]: array([ 0. , 0.05151082])
"""