BasicProgrammingWithSpm - MRC CBU Imaging Wiki

Please enter your password of your account at the remote wiki below.
/!\ You should trust both wikis because the password could be read by the particular administrators.

Clear message
location: BasicProgrammingWithSpm

Loading files into Matlab using SPM commands

Neuroimaging files are stored by SPM in one of two different formats - FormatAnalyze or FormatNifti.

There are two main components to these files:

* The data itself

* Descriptive header information, which stores data type, scaling, and importantly, the space: the voxel size, slice orientation (often relative to the main axes of the scanner - x left-right, y down-up and z along the bore of the magnet from foot to head end) and the origin, often relative to the isocentre of the magnet

When you are reading in a file into SPM, you must first load the header information, and then the main data. To load the header, use the Matlab line:


where myfile.nii is the name of the file you wish to load. It should end with .nii for Nifti, or .img for Analyze.

Various useful parameters are containing in V, such as the V.mat, which describes the space. You might want to extract some details from this using the command spm_imatrix. the help for any spm command is accessed with 'help [commandname]' Then, to load the data


Y is now a 3d matrix containing your data values. You may find the size with


and view a slice with

imagesc(Y(:,:,10)); % display the axial slice where z=10 

Simple calculations

If you have two files that are in EXACTLY the same space (i.e., exactly the same number of slices, voxel sizes, orientation) then you may perform simple mathematical calculations. For example, the following code loads two files, adds them and saves the result to a new file.

Y3=Y1+Y2; % only ever do this if they're in the same space

If they're in a different space, you will either need to reslice one to the same space as the other (see command spm_reslice) or to resample one as you load it up, with spm_sample_vol