Convert data between MATLAB and Nifti format

Nifti format is widely used in fMRI, noted by the extension .nii, .nii.gz. In this tutorial I show how to convert the data format between MATLAB and Nifti format.

First, you have to have the Nifti toolbox for MATLAB, which can be found here.

Read the Nifti (.nii) file into MATLAB workspace using command MRIread(pathToFile).

out = MRIread('/X/NiftiData.nii'); % read the Nifti file  
outVolume = out.vol; % The 3D/4D (MRI/fMRI) volume data 

Writing .mat to Nifti file using MRIwrite is a bit trickier than the reading part. Let's say we have some values to write to the brain in Nifti format. An easy way is to

1) Read a Nifti file from the brain using the example above

2) Write the new value back to the volume attribute

% outVolume --> newValueVolume is the volume of the new value we want to write to the Nifti file

% we put it back to the vol attribute

out.vol = newValueVolume;
% write to a nifti file
err = MRIwrite(out,'newOutputValue.nii.gz','double');

That's all.