SPM batching

The trick to making SPM batches is using the job manager. In the graphics window, click Batch in the TASKS menu. This opens a GUI in which an analysis tree can be specified and saved to a mat file. Loading the mat file shows that it contains a cell array called job. Browsing through job shows how SPM saves the analysis options given using the GUI. The cell array can be used as an argument in spm_job('run', job), which performs the specified analysis on the specified scans. What we want is to apply the analysis to different files. This requires adjusting the relevant fields in the cells of job (including the location of the template for normalization if you change computers!). The code below shows how to adjust a standard analysis saved in the zipped batch.mat. The analysis uses onsets etc saved in multivar files.

function custom_spm_analysis_batch

load batch;

n = 1;
dirlist{n} = 'D:\fMRI\Images\subject1\taskscans\subjectID1*.img';
reslist{n} = 'D:\fMRI\Images\subject1\results';
mv_file{n} = 'D:\fMRI\Performance\multivar_subject1.mat';
anatomy{n} = 'D:\fMRI\Images\subject1\anatomy\subject1_anatomy.img,1';
n = n + 1;

dirlist{n} = 'D:\fMRI\Images\subject2\taskscans\subjectID2*.img';
reslist{n} = 'D:\fMRI\Images\subject2\results';
mv_file{n} = 'D:\fMRI\Performance\multivar_subject2.mat';
anatomy{n} = 'D:\fMRI\Images\subject2\anatomy\subject2_anatomy.img,1';
n = n + 1;

for iDir = 1:length(dirlist),
    [p, n, e] = fileparts(dirlist{iDir});
    x = dir([n e]);
    scans = {};
    ascans = {};
    wascans = {};
    swascans = {};
    for iFile = 1:length(x),
        scans{iFile} = [p '\' x(iFile).name ',1'];
        ascans{iFile} = [p '\' 'a' x(iFile).name];
        wascans{iFile} = [p '\' 'wa' x(iFile).name];
        swascans{iFile} =[p '\' 'swa' x(iFile).name];
    % slice time correction
    jobs{1}.temporal{1}.st.scans{1} = scans;
    % realign
    jobs{2}.spatial{1}.realign{1}.estimate.data{1} = ascans;
    % coreg
    jobs{2}.spatial{2}.coreg{1}.estimate.ref{1} = anatomy{iDir};
    jobs{2}.spatial{2}.coreg{1}.estimate.source{1} = ascans{1};
    jobs{2}.spatial{2}.coreg{1}.estimate.other = ascans;
    % normalize
    jobs{2}.spatial{3}.normalise{1}.estwrite.subj.source{1} = anatomy{iDir};
    jobs{2}.spatial{3}.normalise{1}.estwrite.subj.resample = ascans;
    n0 = length(jobs{2}.spatial{3}.normalise{1}.estwrite.subj.resample);
    jobs{2}.spatial{3}.normalise{1}.estwrite.subj.resample{n0 + 1} = anatomy{iDir};
    % smooth
    jobs{2}.spatial{4}.smooth.data = wascans;
    % stats: spec
    jobs{3}.stats{1}.fmri_spec.dir{1} = reslist{iDir};
    for nn = 1:length(swascans),
        jobs{3}.stats{1}.fmri_spec.sess.scans{nn, 1} = swascans{nn};
    jobs{3}.stats{1}.fmri_spec.sess.multi{1} = mv_file{iDir};
    % stats: estimate
    jobs{3}.stats{2}.fmri_est.spmmat{1} = [reslist{iDir} '\SPM.mat'];
    % stats: contrasts
    jobs{3}.stats{3}.con.spmmat{1} = [reslist{iDir} '\SPM.mat'];
    % run the job
    spm_jobman('run', jobs);