function [flirtmat spmvoxmat fslvoxmat] = worldmat2flirtmat(worldmat, src, trg) %worldmat2flirtmat: convert NIfTI world (mm) coordinates matrix to flirt % % Example: % [flirtmat spmvoxmat fslvoxmat] = worldmat2flirtdmat(worldmat, src, trg); % % See also: flirtmat2worldmat, flirtmat_write % Copyright 2009 Ged Ridgway if ischar(src) src = nifti(src); end if ischar(trg) trg = nifti(trg); end spmvoxmat = inv(src.mat) * worldmat * trg.mat; addone = eye(4); addone(:, 4) = 1; fslvoxmat = inv(addone) * spmvoxmat * addone; trgscl = nifti2scl(trg); srcscl = nifti2scl(src); flirtmat = inv( srcscl * fslvoxmat * inv(trgscl) ); %% function scl = nifti2scl(N) % not sure if this is always correct with rotations in mat, but seems okay! scl = diag([sqrt(sum(N.mat(1:3,1:3).^2)) 1]); if det(N.mat) > 0 % neurological, x-axis is flipped, such that [3 2 1 0] and [0 1 2 3] % have the same *scaled* coordinates: xflip = diag([-1 1 1 1]); xflip(1, 4) = N.dat.dim(1)-1; % reflect about centre scl = scl * xflip; end