Code covered by the BSD License  

Highlights from
Difference Matrix

from Difference Matrix by Zachary Danziger
Builds the matrix that takes the column-wise difference of another matrix when post-multiplied.

diffMat(obs,type)
function D = diffMat(obs,type)
% Builds a difference matrix for subtracting columns via multiplication
%
% D = diffMat(obs)
% D = diffMat(obs,type)
%
% Creates a difference matrix, D, that when multiplied by by another matrix
% takes its difference over obs columns. The type is either 'circular'
% or 'none'. The defalt is 'none'.
%
% EXAMPLE
% B = [2:1:8;sin(linspace(0,pi,7))]
% B =
%     2.0000    3.0000    4.0000    5.0000    6.0000    7.0000    8.0000
%          0    0.5000    0.8660    1.0000    0.8660    0.5000    0.0000
%
% D = diffMat(size(B,2));
% B*D
% ans =
%    -1.0000   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000
%    -0.5000   -0.3660   -0.1340    0.1340    0.3660    0.5000
%
% B*diffMat(size(B,2),'circular')
% ans =
%    -1.0000   -1.0000   -1.0000   -1.0000   -1.0000   -1.0000    6.0000
%    -0.5000   -0.3660   -0.1340    0.1340    0.3660    0.5000    0.0000
%
%
% %%% ZCD April 2010 %%%
%


D = eye(obs);
IX = sub2ind([obs obs],2:obs,1:obs-1);
D(IX) = -1;

if nargin==2 && strcmp('circular',type)
    D(1,end) = -1;
elseif nargin==2 && strcmp('none',type) || nargin==1
    D = D(:,1:end-1);
else
    error('Unrecognized Input');
end

Contact us