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:
V=spm_vol('myfile.nii')
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=spm_read_vols(V);
Y is now a 3d matrix containing your data values. You may find the size with
size(Y)
and view a slice with
figure; 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.
V1=spm_vol('myfile1.nii'); V2=spm_vol('myfile2.nii'); Y1=spm_read_vols(V1); Y2=spm_read_vols(V2); Y3=Y1+Y2; % only ever do this if they're in the same space V3=V1; V3.fname='outputfile.nii'; spm_write_vol(V3,Y3);
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