Post date: May 21, 2009 11:57:39 PM
*** Note that text in green starting with a % is a comment in Matlab and is here to explain each step of the code in this font
Reading data into the Matlab workspace
% Step 1. Define filepath and filename of the data I want to read into the Matlab workspace
datadir = '/data/fMRI';
fname = '12001.nii';
Data2Read = fullfile(datadir,fname);
% What I've done in Step 1 is to construct a filename such as /data/fMRI/12001.nii from its filepath (the variable called datadir) and filename (the variable called fname). Both these variables are string variables and I've used the function fullfile to essentially concatenate these two strings together. The end result is a string variable called Data2Read, which is essentially a string that looks like this: /data/fMRI/12001.nii
% Step 2. Now pass Data2Read into the function spm_vol in order to read in the header information for the file. Note that the spm_vol function comes with the SPM toolbox in Matlab that is a standard software package for neuroimagers. Having SPM is essential for this part.
HeaderInfo = spm_vol(Data2Read);
% In Step 2, the header information for the data you want to read in is now in your workspace. This is required for Step 3, where you will use the header information to actually read in the entire data.
% Step 3. Now use spm_read_vols to read in the data
Data = spm_read_vols(HeaderInfo);
Your data is now loaded into the Matlab workspace.
Writing data out of Matlab into a NIFTI file
% Step 1. Take the header information from a previous file with similar dimensions and voxel sizes and change the filename in the header.
HeaderInfo.fname = 'NewData.nii'; % This is where you fill in the new filename
HeaderInfo.private.dat.fname = HeaderInfo.fname; % This just replaces the old filename in another location within the header.
% Step 2. Now use spm_write_vol to write out the new data. You need to give spm_write_vol the new header information and corresponding data matrix
spm_write_vol(HeaderInfo,Data); % where HeaderInfo is your header information for the new file, and Data is the image matrix corresponding to the image you'll be writing out.