/* -*- MaTX -*- * * NAME * diff_col() - Difference function for each column * diff_row() - Difference function for each row * diff() - Same as diff_col * * SYNOPSIS * dx = diff_col(x) * Matrix dx; * Matrix x; * * dx = diff_col(x, k) * Matrix dx; * Matrix x; * Integer k; * * dx = diff_row(x) * Matrix dx; * Matrix x; * * dx = diff_row(x, k) * Matrix dx; * Matrix x; * Integer k; * * dx = diff(x) * Matrix dx; * Matrix x; * * dx = diff(x, k) * Matrix dx; * Matrix x; * Integer k; * * DESCRIPTION * If x is a vector, then diff(x) returns a vector of differences * between adjacent elements as [x(2)-x(1) x(3)-x(2) ... x(n)-x(n-1)]. * * If x is a matrix, * * diff_col(x) calculates the differences for each column: * diff_col(x) = x(2:n,:) - x(1:n-1,:). * * diff_row(x) calculates the differences for each row: * diff_row(x) = x(:,2:n) - x(:,1:n-1). * * diff(x,n), diff_col(x,n), and diff_row(x,n) are the n'th * difference functions. * * SEE ALSO * cumsum */ Func Matrix diff(x, k, ...) Matrix x; Integer k; { error(nargchk(1, 2, nargs, "diff")); if (nargs == 1) { if (Rows(x) == 1 || Cols(x) == 1) { return diff_col(x); } else { error("diff(): Vector is expected.\n"); } } else { if (Rows(x) == 1 || Cols(x) == 1) { return diff_col(x, k); } else { error("diff(): Vector is expected.\n"); } } } Func Matrix diff_col(x, k, ...) Matrix x; Integer k; { Matrix dx; Integer i,m,n; error(nargchk(1, 2, nargs, "diff_col")); if (nargs == 1) { k = 1; } if (k <= 0) { error("diff_col(): Index must be positive.\n"); } for (i = 1; i <= k; i++) { {m,n} = size(x); if (m == 1) { dx = x(2:n) - x(1:n-1); } else { dx = x(2:m,:) - x(1:m-1,:); } } return dx; } Func Matrix diff_row(x, k, ...) Matrix x; Integer k; { error(nargchk(1, 2, nargs, "diff_row")); if (nargs == 1) { return trans(diff_col(trans(x))); } else { return trans(diff_col(trans(x), k)); } }