You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: spm_affreg.m
    path of file: ./repos/fieldtrip/external/spm12/toolbox/OldNorm
    
    the code of the file until where you have to start completion: function [M,scal] = spm_affreg(VG,VF,flags,M,scal)
% Affine registration using least squares.
% FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0)
%
% VG        - Vector of template volumes.
% VF        - Source volume.
% flags     - a structure containing various options.  The fields are:
%             WG       - Weighting volume for template image(s).
%             WF       - Weighting volume for source image
%                        Default to [].
%             sep      - Approximate spacing 
    
function and its 1st and second derivatives
    % ---------------------------------------------------------------
    n     = 0;
    ss    = 0;
    Beta  = zeros(12+length(VG),1);
    Alpha = zeros(12+length(VG));

    if length(VG)==1,
        % Make the cost function symmetric
        % ---------------------------------------------------------------

        % Build a matrix to rotate the derivatives by, converting from
        % derivatives w.r.t. changes in the overall affine transformation
        % matrix, to derivatives w.r.t. the parameters p.
        % ---------------------------------------------------------------
        dt  = 0.0001;
        R   = eye(13);
        MM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat;
        for i1=1:12,
            p1          = p0;
            p1(i1)      = p1(i1)+dt;
            MM1         = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat));
            R(1:12,i1)  = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);
        end