summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--macros/arch_fit.sci120
-rw-r--r--macros/arch_test.sci104
-rw-r--r--macros/cplxpair.sci107
-rw-r--r--macros/cplxreal.sci97
-rw-r--r--macros/czt.sci102
-rw-r--r--macros/fft1.sci112
-rw-r--r--macros/fft21.sci102
-rw-r--r--macros/fftconv.sci74
-rw-r--r--macros/fftn.sci79
-rw-r--r--macros/fht.sci90
-rw-r--r--macros/grpdelay.sci204
-rw-r--r--macros/hilbert1.sci143
-rw-r--r--macros/idct1.sci62
-rw-r--r--macros/idct2.sci58
-rw-r--r--macros/idst1.sci51
-rw-r--r--macros/ifft1.sci114
-rw-r--r--macros/ifft2.sci100
-rw-r--r--macros/ifftn.sci69
-rw-r--r--macros/ipermute.sci25
-rw-r--r--macros/ols.sci70
-rw-r--r--macros/rceps.sci88
-rw-r--r--macros/shanwavf.sci65
-rw-r--r--macros/spectral_adf.sci100
-rw-r--r--macros/spectral_xdf.sci95
-rw-r--r--macros/unwrap2.sci244
-rw-r--r--macros/xcorr2.sci102
26 files changed, 1746 insertions, 831 deletions
diff --git a/macros/arch_fit.sci b/macros/arch_fit.sci
index 3e431a6..2fa462c 100644
--- a/macros/arch_fit.sci
+++ b/macros/arch_fit.sci
@@ -1,35 +1,85 @@
-function [A, B] = arch_fit(Y, varargin)
-//This functions fits an ARCH regression model to the time series Y using the scoring algorithm in Engle's original ARCH paper.
-//Calling Sequence
-//[A, B] = arch_fit (Y, X, P, ITER, GAMMA, A0, B0)
-//Parameters
-//Description
-//Fit an ARCH regression model to the time series Y using the scoring algorithm in Engle's original ARCH paper.
-//
-//The model is
-//
-// y(t) = b(1) * x(t,1) + ... + b(k) * x(t,k) + e(t),
-// h(t) = a(1) + a(2) * e(t-1)^2 + ... + a(p+1) * e(t-p)^2
-//
-//in which e(t) is N(0, h(t)), given a time-series vector Y up to time t-1 and a matrix of (ordinary) regressors X up to t. The order of the regression of the residual variance is specified by P.
-//
-//If invoked as 'arch_fit (Y, K, P)' with a positive integer K, fit an ARCH(K, P) process, i.e., do the above with the t-th row of X given by
-//
-// [1, y(t-1), ..., y(t-k)]
-//
-//Optionally, one can specify the number of iterations ITER, the updating factor GAMMA, and initial values a0 and b0 for the scoring algorithm.
-funcprot(0);
-rhs = argn(2);
-lhs=argn(1);
-if(rhs<7 | rhs>7)
-error("Wrong number of input arguments.");
-end
-if (lhs<2 | lhs>2)
- error("Wrong number of output arguments.");
-end
-
- select(rhs)
- case 7 then
- [A, B] = callOctave("arch_fit",Y, varargin(1), varargin(2), varargin(3), varargin(4), varargin(5), varargin(6));
- end
-endfunction
+/*
+Dependencies : ols, autoreg_matrix
+Calling Sequence
+ [a, b] = arch_fit (y, x, p)
+ [a, b] = arch_fit (y, x, p, iter, gamma, a0, b0)
+Parameters
+ y(vector) : A time-series data vector up to time t-1 .
+ x (Matrix): A matrix of (ordinary) regressors x up to t.
+ p (scalar): The order of the regression of the residual variance.
+ iter (scaler) : Number of iterations
+ gamma (real number) : updating factor
+ a0 b0 (real numbers) : Initial values for the scoring algorithm
+Description:
+ Fit an ARCH regression model to the time series y using the scoring algorithm in Engle’s original ARCH paper.
+ The model is
+ y(t) = b(1) * x(t,1) + … + b(k) * x(t,k) + e(t),
+ h(t) = a(1) + a(2) * e(t-1)^2 + … + a(p+1) * e(t-p)^2
+ in which e(t) is N(0, h(t)), given a time-series vector y up to time t-1 and a matrix of (ordinary) regressors x upto t. The order of the regression of the residual variance is specified by p.
+ If invoked as arch_fit (y, k, p) with a positive integer k, fit an ARCH(k, p) process, i.e., do the above with the t-th row of x given by
+ [1, y(t-1), …, y(t-k)]
+ Optionally, one can specify the number of iterations iter, the updating factor gamma, and initial values a0 and b0 for the scoring algorithm.
+*/
+function [a, b] = arch_fit (y, x, p, iter, gamma, a0, b0)
+ nargin = argn(2)
+ if (nargin < 3 || nargin == 6)
+ error("invalid inputs");
+ end
+ if (~ (isvector (y)))
+ error ("arch_fit: Y must be a vector");
+ end
+ T = max(size(y));
+ y = matrix (y, T, 1);
+ [rx, cx] = size (x);
+ if ((rx == 1) && (cx == 1))
+ x = autoreg_matrix (y, x);
+ elseif (~ (rx == T))
+ error ("arch_fit: either rows (X) == length (Y), or X is a scalar");
+ end
+ [T, k] = size (x);
+ if (nargin == 7)
+ a = a0;
+ b = b0;
+ e = y - x * b;
+ else
+ [b, v_b, e] = ols (y, x);
+ zer = zeros(1,p);
+ a = [v_b zer]';
+ if (nargin < 5)
+ gamma = 0.1;
+ if (nargin < 4)
+ iter = 50;
+ end
+ end
+ end
+ esq = e.^2;
+ Z = autoreg_matrix (esq, p);
+ for i = 1 : iter
+ h = Z * a;
+ tmp = esq ./ h.^2 - 1 ./ h;
+ s = 1 ./ h(1:T-p);
+ for j = 1 : p
+ s = s - a(j+1) * tmp(j+1:T-p+j);
+ end
+ r = 1 ./ h(1:T-p);
+ for j = 1:p
+ r = r + 2 * h(j+1:T-p+j).^2 .* esq(1:T-p);
+ end
+ r = sqrt (r);
+ X_tilde = x(1:T-p, :) .* (r * ones (1,k));
+ e_tilde = e(1:T-p) .*s ./ r;
+ delta_b = inv (X_tilde' * X_tilde) * X_tilde' * e_tilde;
+ b = b + gamma * delta_b;
+ e = y - x * b;
+ esq = e .^ 2;
+ if isempty(esq) then
+ esq = zeros(size(y))
+ end
+ Z = autoreg_matrix (esq, p);
+ h = Z * a;
+ f = esq ./ h - ones (T,1);
+ Z_tilde = Z ./ (h * ones (1, p+1));
+ delta_a = inv (Z_tilde' * Z_tilde) * Z_tilde' * f;
+ a = a + gamma * delta_a;
+ end
+ endfunction
diff --git a/macros/arch_test.sci b/macros/arch_test.sci
index 3c53fc5..5cb8ed8 100644
--- a/macros/arch_test.sci
+++ b/macros/arch_test.sci
@@ -1,46 +1,58 @@
-function [PVAL, LM]= arch_test(Y,X,P)
-// perform a Lagrange Multiplier (LM) test of thenull hypothesis of no conditional heteroscedascity against the alternative of CH(P)
-//Calling Sequence
-//arch_test(Y,X,P)
-//PVAL = arch_test(Y,X,P)
-//[PVAL, LM]= arch_test(Y,X,P)
-//Parameters
-//P: Degrees of freedom
-//PVAL:PVAL is the p-value (1 minus the CDF of this distribution at LM) of the test
-//Description
-//perform a Lagrange Multiplier (LM) test of thenull hypothesis of no conditional heteroscedascity against the alternative of CH(P).
-//
-//I.e., the model is
-//
-// y(t) = b(1) * x(t,1) + ... + b(k) * x(t,k) + e(t),
-//
-//given Y up to t-1 and X up to t, e(t) is N(0, h(t)) with
-//
-// h(t) = v + a(1) * e(t-1)^2 + ... + a(p) *e(t-p)^2, and the null is a(1) == ... == a(p) == 0.
-//
-//If the second argument is a scalar integer, k,perform the sametest in a linear autoregression model of orderk, i.e., with
-//
-// [1, y(t-1), ..., y(t-K)] as the t-th row of X.
-//
-// Under the null, LM approximatel has a chisquare distribution with P degrees of freedom and PVAL is the p-value (1 minus the CDF of this distribution at LM) of the test.
-//
-// If no output argument is given, the p-value is displayed.
- funcprot(0)
- rhs= argn(2);
- lhs= argn(1);
- if(rhs<3 | rhs>3)
- error("Wrong number of input arguments");
- end
- if(lhs<1 | lhs>2)
- error("Wrong number of output arguments");
- end
- select(rhs)
- case 3 then
- select(lhs)
- case 1 then
- PVAL= callOctave("arch_test", Y, X, P);
- case 2 then
- [PVAL,LM]= callOctave("arch_test", Y, X, P);
- end
- end
-endfunction \ No newline at end of file
+/*
+Description:
+ Perform a Lagrange Multiplier (LM) test for conditional heteroscedasticity.
+ For a linear regression model
+ y = x * b + e
+ perform a Lagrange Multiplier (LM) test of the null hypothesis of no conditional heteroscedascity against the alternative of CH(p).
+ I.e., the model is
+ y(t) = b(1) * x(t,1) + … + b(k) * x(t,k) + e(t),
+ given y up to t-1 and x up to t, e(t) is N(0, h(t)) with
+ h(t) = v + a(1) * e(t-1)^2 + … + a(p) * e(t-p)^2,
+ and the null is a(1) == … == a(p) == 0.
+ If the second argument is a scalar integer, k, perform the same test in a linear autoregression model of order k, i.e., with
+ [1, y(t-1), …, y(t-k)]
+ as the t-th row of x.
+ Under the null, LM approximately has a chisquare distribution with p degrees of freedom and pval is the p-value (1 minus the CDF of this distribution at LM) of the test.
+ If no output argument is given, the p-value is displayed.
+ Calling Sequence
+ [pval, lm] = arch_test (y, x, p)
+ Parameters
+ y: Array-like. Dependent variable of the regression model.
+ x: Array-like. Independent variables of the regression model. If x is a scalar integer k, it represents the order of autoregression.
+ p : Integer. Number of lagged squared residuals to include in the heteroscedasticity model.
+ Returns:
+ pval: Float. p-value of the LM test.
+ lm: Float. Lagrange Multiplier test statistic.*/
+ Dependencies : ols, autoreg_matrix
+//helper function
+function cdf = chi2cdf ( X, n)
+ df = resize_matrix ( n , size (X) , "" , n);
+ [cdf,Q] = cdfchi ( "PQ" , X ,df);
+endfunction
+//main function
+function [pval, lm] = arch_test (y, x, p)
+ nargin = argn(2)
+ if (nargin ~= 3)
+ error ("arch_test: 3 input arguments required");
+ end
+ if (~ (isvector (y)))
+ error ("arch_test: Y must be a vector");
+ end
+ T = max(size(y));
+ y = matrix (y, T, 1);
+ [rx, cx] = size (x);
+ if ((rx == 1) && (cx == 1))
+ x = autoreg_matrix (y, x);
+ elseif (~ (rx == T))
+ error ("arch_test: either rows (X) == length (Y), or X is a scalar");
+ end
+ if (~ (isscalar (p) && (modulo (p, 1) == 0) && (p > 0)))
+ error ("arch_test: P must be a positive integer");
+ end
+ [b, v_b, e] = ols (y, x);
+ Z = autoreg_matrix (e.^2, p);
+ f = e.^2 / v_b - ones (T, 1);
+ f = Z' * f;
+ lm = f' * inv (Z'*Z) * f / 2;
+ pval = 1 - chi2cdf (lm, p);
+endfunction
diff --git a/macros/cplxpair.sci b/macros/cplxpair.sci
new file mode 100644
index 0000000..16fceac
--- /dev/null
+++ b/macros/cplxpair.sci
@@ -0,0 +1,107 @@
+/*Description
+ Sort the numbers z into complex conjugate pairs ordered by increasing real part.
+ The negative imaginary complex numbers are placed first within each pair. All real numbers (those with abs (imag (z) / z) < tol) are placed after the complex pairs.
+ and the resulting tolerance for a given complex pair is 100 * eps (abs (z(i))).
+ Signal an error if some complex numbers could not be paired. Signal an error if all complex numbers are not exact conjugates (to within tol).
+ Note that there is no defined order for pairs with identical real parts but differing imaginary parts
+Calling Sequence
+ cplxpair (z)
+ cplxpair (z, tol)
+ cplxpair (z, tol, dim)
+Parameters:
+ z is a matrix or vector.
+ tol is a weighting factor which determines the tolerance of matching. The default value is 100.
+ By default the complex pairs are sorted along the first non-singleton dimension of z. If dim is specified, then the complex pairs are sorted along this dimension.
+Dependencies: ipermute
+Example:
+ The following code
+ [ cplxpair(exp(2*%i*%pi*[0:4]'/5)), exp(2*%i*%pi*[3; 2; 4; 1; 0]/5) ]
+ Produces the following output
+ ans =
+ -0.80902 - 0.58779i -0.80902 - 0.58779i
+ -0.80902 + 0.58779i -0.80902 + 0.58779i
+ 0.30902 - 0.95106i 0.30902 - 0.95106i
+ 0.30902 + 0.95106i 0.30902 + 0.95106i
+ 1.00000 + 0.00000i 1.00000 + 0.00000i
+*/
+function zsort = cplxpair (z, tol, dim)
+ if (nargin < 1)
+ error("Invalid inputs");
+ end
+ // default double
+ realmin = 2.2251e-308
+ if (isempty (z))
+ zsort = zeros (size (z,1) , size (z,2));
+ return;
+ end
+ if (nargin < 2 || isempty (tol))
+ tol = 100* %eps;
+ elseif (~ isscalar (tol) || tol < 0 || tol >= 1)
+ error ("cplxpair: TOL must be a scalar number in the range 0 <= TOL < 1");
+ end
+ nd = ndims (z);
+ if (nargin < 3)
+ // Find the first singleton dimension.
+ sz = size (z);
+ dim = find (sz > 1, 1);
+ if isempty(dim)
+ dim = 1;
+ end
+ else
+ dim = floor (dim);
+ if (dim < 1 || dim > nd)
+ error ("cplxpair: invalid dimension DIM");
+ end
+ end
+ // Move dimension to analyze to first position, and convert to a 2-D matrix.
+ perm = [dim:nd, 1:dim-1];
+ z = permute (z, perm);
+ sz = size (z);
+ n = sz(1);
+ m = prod (sz) / n;
+ z = matrix (z, n, m);
+ // Sort the sequence in terms of increasing real values.
+ [temp, idx] = gsort (real (z), 1 , "i");
+ z = z(idx + n * ones (n, 1) * [0:m-1]);
+ // Put the purely real values at the end of the returned list.
+ [idxi, idxj] = find (abs (imag (z)) ./ (abs (z) + realmin) <= tol);
+ // Force values detected to be real within tolerance to actually be real.
+ z(idxi + n*(idxj-1)) = real (z(idxi + n*(idxj-1)));
+ //if idxi and idxj are not scalers
+ if ~isscalar(idxi) then
+ v = ones(size(idxi,1),size(idxi,2));
+ else
+ v = 1 ;
+ end
+ q = sparse ([idxi' idxj'], v, [n m]);
+ nr = sum (q, 1);
+ [temp, idx] = gsort (q, 'r','i');
+ midx = idx + size (idx,1) * ones (size (idx,1), 1) * [0:size(idx,2)-1];
+ z = z(midx);
+ zsort = z;
+ // For each remaining z, place the value and its conjugate at the start of
+ // the returned list, and remove them from further consideration.
+ for j = 1:m
+ p = n - nr(j);
+ for i = 1:2:p
+ if (i+1 > p)
+ error ("cplxpair: could not pair all complex numbers");
+ end
+ [v, idx] = min (abs (z(i+1:p,j) - conj (z(i,j))));
+ if (v >= tol * abs (z(i,j)))
+ error ("cplxpair: could not pair all complex numbers");
+ end
+ // For pairs, select the one with positive imaginary part and use it and
+ // it's conjugate, but list the negative imaginary pair first.
+ if (imag (z(i,j)) > 0)
+ zsort([i, i+1],j) = [conj(z(i,j)), z(i,j)];
+ else
+ zsort([i, i+1],j) = [conj(z(idx+i,j)), z(idx+i,j)];
+ end
+ z(idx+i,j) = z(i+1,j);
+ end
+ end
+ // Reshape the output matrix.
+ zsort = ipermute (matrix (zsort, sz), perm);
+endfunction
+
diff --git a/macros/cplxreal.sci b/macros/cplxreal.sci
index a552998..b06fac3 100644
--- a/macros/cplxreal.sci
+++ b/macros/cplxreal.sci
@@ -1,48 +1,51 @@
-function [zc, zr] = cplxreal (z, thresh)
-//Function to divide vector z into complex and real elements, removing the one of each complex conjugate pair.
-//Calling Sequence
-//[zc, zr] = cplxreal (z, thresh)
-//[zc, zr] = cplxreal (z)
-//zc = cplxreal (z, thresh)
-//zc = cplxreal (z)
-//Parameters
-//z: vector of complex numbers.
-//thresh: tolerance for comparisons.
-//zc: vector containing the elements of z that have positive imaginary parts.
-//zr: vector containing the elements of z that are real.
-//Description
-//This is an Octave function.
-//Every complex element of z is expected to have a complex-conjugate elsewhere in z. From the pair of complex-conjugates, the one with the negative imaginary part is removed.
-//If the magnitude of the imaginary part of an element is less than the thresh, it is declared as real.
-//Examples
-//[zc, zr] = cplxreal([1 2 3+i 4 3-i 5])
-//zc = 3 + 1i
-//zr =
-// 1 2 4 5
-funcprot(0);
-lhs = argn(1)
-rhs = argn(2)
-if (rhs < 1 | rhs > 2)
-error("Wrong number of input arguments.")
-end
-
-select(rhs)
- case 1 then
- if(lhs==1)
- zc = callOctave("cplxreal",z)
- elseif (lhs==2)
- [zc, zr] = callOctave("cplxreal",z)
- else
- error("Wrong number of output argments.")
- end
-
- case 2 then
- if(lhs==1)
- zc = callOctave("cplxreal",z, thresh)
- elseif (lhs==2)
- [zc, zr] = callOctave("cplxreal",z, thresh)
- else
- error("Wrong number of output argments.")
- end
- end
+/*Description
+ Sort the numbers z into complex-conjugate-valued and real-valued elements.
+ The positive imaginary complex numbers of each complex conjugate pair are returned in zc and the real numbers are returned in zr.
+ Signal an error if some complex numbers could not be paired.
+ Signal an error if all complex numbers are not exact conjugates (to within tol).
+ Note that there is no defined order for pairs with identical real parts but differing imaginary parts.
+Calling Sequence:
+ [zc, zr] = cplxreal (z)
+ [zc, zr] = cplxreal (z, tol)
+ [zc, zr] = cplxreal (z, tol, dim)
+Parameters
+ Inputs
+ z - A vector of numbers or Matrix
+ tol - tol is a weighting factor in the range [0, 1) which determines the tolerance of the matching.
+ The default value is 100 * eps and the resulting tolerance for a given complex pair is tol * abs (z(i))).
+ dim - By default the complex pairs are sorted along the first non-singleton dimension of z. If dim is specified, then the complex pairs are sorted along this dimension.
+ Outputs
+ zc - complex conjugate pair
+ zr - real numbers
+Example:
+ with 2 real zeros, one of them equal to 0
+ [zc, zr] = cplxreal (roots ([1, 0, 0, 1, 0])) */
+function [zc, zr] = cplxreal (z, tol, dim)
+ if (nargin < 1 || nargin > 3)
+ error("invalid inputs");
+ end
+ if (isempty (z))
+ zc = zeros (size (z,1),size(z,2));
+ zr = zeros (size (z,1),size(z,2));
+ return;
+ end
+ if (nargin < 2 || isempty (tol))
+ tol = 100 * %eps ;
+ end
+ if (nargin >= 3)
+ zcp = cplxpair(z,tol,dim);
+ else
+ zcp = cplxpair (z , tol);
+ end
+ nz = max(size (z) );
+ idx = nz;
+ while ((idx > 0) && (zcp(idx) == 0 || (abs (imag (zcp(idx))) ./ abs (zcp(idx))) <= tol))
+ zcp(idx) = real (zcp(idx));
+ idx = idx - 1;
+ end
+ if (pmodulo (idx, 2) ~= 0)
+ error ("cplxreal: odd number of complex values was returned from cplxpair");
+ end
+ zc = zcp(2:2:idx);
+ zr = zcp(idx+1:nz);
endfunction
diff --git a/macros/czt.sci b/macros/czt.sci
index 84a0253..f7c4138 100644
--- a/macros/czt.sci
+++ b/macros/czt.sci
@@ -1,41 +1,65 @@
-function y = czt(x, varargin)
-//Chirp Z Transform
-//Calling Sequence
-//czt (x)
-//czt (x, m)
-//czt (x, m, w)
-//czt (x, m, w, a)
-//Parameters
-//x: Input scalar or vector
-//m: Total Number of steps
-//w: ratio between points in each step
-//a: point in the complex plane
-//Description
-//This is an Octave function.
-//Chirp z-transform. Compute the frequency response starting at a and stepping by w for m steps. a is a point in the complex plane, and w is the ratio between points in each step (i.e., radius increases exponentially, and angle increases linearly).
-//Examples
-// m = 32; ## number of points desired
-// w = exp(-j*2*pi*(f2-f1)/((m-1)*Fs)); ## freq. step of f2-f1/m
-// a = exp(j*2*pi*f1/Fs); ## starting at frequency f1
-// y = czt(x, m, w, a);
-
-funcprot(0);
-lhs= argn(1);
-rhs= argn(2);
-
-if(rhs<1 | rhs > 4)
-error("Wrong number of input arguments")
-end
-
-select (rhs)
- case 1 then
- y= callOctave("czt", x);
- case 2 then
- y= callOctave("czt", x, varargin(1));
- case 3 then
- y= callOctave("czt", x, varargin(1), varargin(2));
- case 4 then
- y= callOctave("czt", x, varargin(1), varargin(2), varargin(3));
-end
+/*Description
+ Chirp z-transform. Compute the frequency response starting at a and stepping by w for m steps. a is a point in the complex plane,
+ and w is the ratio between points in each step (i.e., radius increases exponentially, and angle increases linearly).
+ Calling Sequence
+ czt (x)
+ czt (x, m)
+ czt (x, m, w)
+ czt (x, m, w, a)
+ Parameters
+ x: Input scalar or vector
+ m: Total Number of steps
+ w: ratio between points in each step
+ a: point in the complex plane
+ Examples: This example uses the czt function to determine the frequency components of a signal, as shown in the following
+ t=linspace(0,50,1000);
+ f=linspace(0,3,1000);
+ x_t=sin(t) + cos(t*2*%pi);
+ x_f=czt(x_t);
+ plot(f,abs(x_f)); */
+function y = czt(x, m, w, a)
+ funcprot(0);
+ nargin=argn(2);
+ if nargin < 1 || nargin > 4 then
+ error("Please input valid number of arguments");
+ end
+ [row, col] = size(x);
+ if row == 1 then
+ x = x(:); col = 1;
+ end
+ if nargin < 2 || isempty(m) then
+ m = max(size(x(:,1)));
+ end
+ if max(size(m) ) > 1 then
+ error("czt: m must be a single element\n");
+ end
+ if nargin < 3 || isempty(w) then
+ w = exp(-2*%i*%pi/m);
+ end
+ if nargin < 4 || isempty(a) then
+ a = 1;
+ end
+ if max(size(w)) > 1 then
+ error("czt: w must be a single element\n");
+ end
+ if max(size(a)) > 1 then
+ error("czt: a must be a single element\n");
+ end
+ // indexing to make the statements a little more compact
+ n = max(size(x(:,1)));
+ N = [0:n-1]'+n;
+ NM = [-(n-1):(m-1)]'+n;
+ M = [0:m-1]'+n;
+ nfft = 2^nextpow2(n+m-1); // fft pad
+ W2 = w.^(([-(n-1):max(m-1,n-1)]'.^2)/2); // chirp
+ for idx = 1:col
+ fg = fft1(x(:,idx).*(a.^-(N-n)).*W2(N), nfft);
+ fw = fft1(1./W2(NM), nfft);
+ gg = ifft1(fg.*fw, nfft);
+ y(:,idx) = gg(M).*W2(M);
+ end
+ if row == 1, y = y.';
+ end
+ y = clean ( y ) ;
endfunction
diff --git a/macros/fft1.sci b/macros/fft1.sci
index a0a6438..f8a27fc 100644
--- a/macros/fft1.sci
+++ b/macros/fft1.sci
@@ -1,49 +1,63 @@
-function res = fft1 (x, n, dim)
-//Calculates the discrete Fourier transform of a matrix using Fast Fourier Transform algorithm.
-//Calling Sequence
-//fft (x, n, dim)
-//fft (x, n)
-//fft (x)
-//Parameters
-//x: input matrix
-//n: Specifies the number of elements of x to be used
-//dim: Specifies the dimention of the matrix along which the FFT is performed
-//Description
-//This is an Octave function.
-//The FFT is calculated along the first non-singleton dimension of the array. Thus, FFT is computed for each column of x.
-//
-//n is an integer specifying the number of elements of x to use. If n is larger than dimention along. which the FFT is calculated, then x is resized and padded with zeros.
-//Similarly, if n is smaller, then x is truncated.
-//
-//dim is an integer specifying the dimension of the matrix along which the FFT is performed.
-//Examples
-//x = [1 2 3; 4 5 6; 7 8 9]
-//n = 3
-//dim = 2
-//fft1 (x, n, dim)
-//ans =
-//
-// 6.0000 + 0.0000i -1.5000 + 0.8660i -1.5000 - 0.8660i
-// 15.0000 + 0.0000i -1.5000 + 0.8660i -1.5000 - 0.8660i
-// 24.0000 + 0.0000i -1.5000 + 0.8660i -1.5000 - 0.8660i
-
-funcprot(0);
-lhs = argn(1)
-rhs = argn(2)
-if (rhs < 1 | rhs > 3)
-error("Wrong number of input arguments.")
-end
-
-select(rhs)
-
- case 1 then
- res = callOctave("fft", x)
-
- case 2 then
- res = callOctave("fft", x, n)
-
- case 3 then
- res = callOctave("fft", x, n, dim)
-
- end
-endfunction
+/*Description
+ Calculates the discrete Fourier transform of a matrix using Fast Fourier Transform algorithm.
+ The FFT is calculated along the first non-singleton dimension of the array. Thus, FFT is computed for each column of D.
+ The variable 'N' is an integer that determines the number of elements of 'D' to use.
+ If 'N' is larger than the dimension along which the FFT is calculated,
+ then 'D' is resized and padded with zeros to match the required size.On the other hand,
+ if 'N' is smaller than the size of 'D', then 'D' is truncated to match the required size.
+ DIM is an integer specifying the dimension of the matrix along which the FFT is performed.
+Calling Sequence
+ fft1 (D)
+ fft1 (D, N)
+ fft1 (D, N, DIM)
+Parameters
+ D: input matrix
+ N: Specifies the number of elements of x to be used
+ DIM: Specifies the dimention of the matrix along which the FFT is performed
+Examples
+ D = [1 2 3; 4 5 6; 7 8 9]
+ N = 3
+ DIM = 2
+ fft1 (D,N,DIM)
+ ans =
+ 6.0000 + 0.0000i -1.5000 + 0.8660i -1.5000 - 0.8660i
+ 15.0000 + 0.0000i -1.5000 + 0.8660i -1.5000 - 0.8660i
+ 24.0000 + 0.0000i -1.5000 + 0.8660i -1.5000 - 0.8660i */
+function res = fft1 (D, N, DIM)
+ funcprot(0);
+ lhs = argn(1)
+ rhs = argn(2)
+ if (rhs < 1 | rhs > 3)
+ error("Wrong number of input arguments.")
+ end
+ dimension = size(D);
+ // first non-singleton dimension
+ nsdim = find(dimension >1,1)
+ if isempty(nsdim) then
+ nsdim = 1 // default to 1 to avoid error while calling fft
+ end
+ select(rhs)
+ case 1 then
+ res = fft(D, -1, nsdim);
+ case 2 then
+ if isempty(N) then
+ n = size(D, nsdim);
+ else
+ n = N;
+ end
+ new_size = size(D);
+ new_size(nsdim) = n;
+ D = resize_matrix(D, new_size);
+ res = fft(D, -1, nsdim);
+ case 3 then
+ if isempty(N) then
+ n = size(D, DIM);
+ else
+ n = N;
+ end
+ new_size = size(D);
+ new_size(DIM) = n;
+ D = resize_matrix(D, new_size);
+ res= fft(D, -1, DIM);
+ end
+endfunction
diff --git a/macros/fft21.sci b/macros/fft21.sci
index 2f04200..ee73a6b 100644
--- a/macros/fft21.sci
+++ b/macros/fft21.sci
@@ -1,45 +1,57 @@
-function res = fft21 (A, m, n)
-//Calculates the two-dimensional discrete Fourier transform of A using a Fast Fourier Transform algorithm.
-//Calling Sequence
-//fft2 (A, m, n)
-//fft2 (A)
-//Parameters
-//A: input matrix
-//m: number of rows of A to be used
-//n: number of columns of A to be used
-//Description
-//This is an Octave function.
-//It performs two-dimentional FFT on the matrix A. m and n may be used specify the number of rows and columns of A to use. If either of these is larger than the size of A, A is resized and padded with zeros.
-//If A is a multi-dimensional matrix, each two-dimensional sub-matrix of A is treated separately.
-//Examples
-//x = [1 2 3; 4 5 6; 7 8 9]
-//m = 4
-//n = 4
-//fft21 (A, m, n)
-//ans =
-//
-// 45 + 0i -6 - 15i 15 + 0i -6 + 15i
-// -18 - 15i -5 + 8i -6 - 5i 5 - 4i
-// 15 + 0i -2 - 5i 5 + 0i -2 + 5i
-// -18 + 15i 5 + 4i -6 + 5i -5 - 8i
-
-funcprot(0);
-lhs = argn(1)
-rhs = argn(2)
-if (rhs < 1 | rhs > 3)
-error("Wrong number of input arguments.")
-end
-
-select(rhs)
-
- case 1 then
- res = callOctave("fft2", A)
-
- case 2 then
- error("Wrong number of input arguments.")
-
- case 3 then
- res = callOctave("fft2", A, m, n)
-
- end
-endfunction
+/* Description
+ Calculates the two-dimensional discrete Fourier transform of A using a Fast Fourier Transform algorithm.
+ It performs two-dimentional FFT on the matrix A. You can use the variables m and n to specify the number of rows and columns
+ of A that you want to use. If either of these variables is larger than the size of A,
+ then A will be resized, and zeros will be added as padding.
+ If A is a multi-dimensional matrix, the function will treat each two-dimensional sub-matrix of A separately.
+ Calling Sequence
+ fft21 (A)
+ fft21 (A, m, n)
+ Parameters
+ A: input matrix
+ m: number of rows of A to be used
+ n: number of columns of A to be used
+ Examples
+ A = [1 2 3; 4 5 6; 7 8 9]
+ m = 4
+ n = 4
+ fft21 (A, m, n)
+ ans =
+ 45 + 0i -6 - 15i 15 + 0i -6 + 15i
+ -18 - 15i -5 + 8i -6 - 5i 5 - 4i
+ 15 + 0i -2 - 5i 5 + 0i -2 + 5i
+ -18 + 15i 5 + 4i -6 + 5i -5 - 8i */
+function res = fft21 (A, m, n)
+ funcprot(0);
+ lhs = argn(1)
+ rhs = argn(2)
+ if (rhs < 1 | rhs > 3)
+ error("Wrong number of input arguments.")
+ end
+ siz=size(A)
+ len=length(siz)
+ select(rhs)
+ case 1 then
+ if len>2 then
+ last_dim=siz(len)
+ else
+ last_dim=1
+ end
+ res=[]
+ for i=1:last_dim
+ res(:,:,i)=fft(A(:,:,i),-1)
+ end
+ case 2 then
+ error("Wrong number of input arguments.")
+ case 3 then
+ if len>2 then
+ last_dim=siz(len)
+ else
+ last_dim=1
+ end
+ res=[]
+ for i=1:last_dim
+ res(:,:,i)=fft(resize_matrix(A(:,:,i),m,n),-1)
+ end;
+ end
+endfunction
diff --git a/macros/fftconv.sci b/macros/fftconv.sci
index d39441d..5028359 100644
--- a/macros/fftconv.sci
+++ b/macros/fftconv.sci
@@ -1,26 +1,48 @@
-function y = fftconv(X, Y, varargin)
-//Convolve two vectors using the FFT for computation.
-//Calling Sequence
-//Y = fftconv(X, Y)
-//Y = fftconv(X, Y, N)
-//Parameters
-//X, Y: Vectors
-//Description
-//Convolve two vectors using the FFT for computation. 'c' = fftconv (X, Y)' returns a vector of length equal to 'length(X) + length (Y) - 1'. If X and Y are the coefficient vectors of two polynomials, the returned value is the coefficient vector of the product polynomial.
-//Examples
-//fftconv([1,2,3], [3,4,5])
-//ans =
-// 3. 10. 22. 22. 15.
-funcprot(0);
-rhs = argn(2)
-if(rhs<2 | rhs>3)
-error("Wrong number of input arguments.");
-end
-
- select(rhs)
- case 2 then
- y = callOctave("fftconv", X, Y);
- case 3 then
- y = callOctave("fftconv",X, Y, varargin(1));
- end
-endfunction
+/*Description
+ Convolve two vectors using the FFT for computation. c = fftconv (X, Y) returns a vector of length equal to 'length(X) + length (Y) - 1'. If X and Y are the coefficient vectors of two polynomials, the returned value is the coefficient vector of the product polynomial.
+ If the optional argument n is specified, an N-point FFT is used.
+ Calling Sequence
+ Y = fftconv(X, Y)
+ Y = fftconv(X, Y, n)
+ Parameters
+ X, Y: Vectors
+ Examples
+ fftconv([1,2,3], [3,4,5])
+ ans =
+ 3. 10. 22. 22. 15.
+ */
+ function y = fftconv(X, Y, n)
+ funcprot(0);
+ rhs = argn(2);
+ if(rhs<2 | rhs>3)
+ error("Wrong number of input arguments.");
+ end
+ shape_x = size(X);
+ shape_y = size(Y);
+ if (shape_x(1) ~= 1 || length(shape_x) ~= 2 || shape_y(1) ~= 1 || length(shape_y) ~= 2)
+ error('The inputs must be a vector');
+ end
+ nx=length(X);
+ ny=length(Y);
+ select(rhs)
+ case 2 then
+ n=nx + ny;
+ X=resize_matrix(X,1,n);
+ Y=resize_matrix(Y,1,n);
+ fftX=fft(X);
+ fftY=fft(Y);
+ y=fft(fftX.*fftY,1);
+ y=y(1:nx+ny-1);
+ case 3 then
+ n = 2^(fix(log2(nx+ny))+1);
+ X=resize_matrix(X,1,n);
+ Y=resize_matrix(Y,1,n);
+ fftX=fft(X);
+ fftY=fft(Y);
+ y=fft(fftX.*fftY,1);
+ y=y(1:nx+ny-1);
+ end
+ y=clean(y);
+ endfunction
+
+
diff --git a/macros/fftn.sci b/macros/fftn.sci
index b8b4170..c90b096 100644
--- a/macros/fftn.sci
+++ b/macros/fftn.sci
@@ -1,26 +1,57 @@
+/*Description:
+ This function computes the N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
+ The optional vector argument SIZE may be used to specify the dimensions of the array to be used.
+ If an element of SIZE is smaller than the corresponding dimension of A, then the dimension of A is truncated prior to performing the FFT.
+ Otherwise, if an element of SIZE is larger than the corresponding dimension, then A is resized and padded with zeros.
+ Calling sequence:
+ Y = fftn(A)
+ Y = fftn(A, SIZE)
+ Parameters:
+ A: Matrix, the input data for which the FFT is computed.
+ SIZE: Optional vector specifying the dimensions of the output array. If provided, the dimensions of A are adjusted accordingly.
+ Examples:
+ fftn([6 9 7 ;2 9 9 ;0 3 1],[2 2])
+ ans =
+ 26. -10.
+ 4. 4.
+ */
function y = fftn(A, SIZE)
-//This function computes the N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
-//Calling Sequence
-//Y = fftn(A)
-//Y = fftn(A, size)
-//Parameters
-//A: Matrix
-//Description
-//This function computes the N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm. The optional vector argument SIZE may be used specify the dimensions of the array to be used. If an element of SIZE is smaller than the corresponding dimension of A, then the dimension of A is truncated prior to performing the FFT. Otherwise, if an element of SIZE is larger than the corresponding dimension then A is resized and padded with zeros.
-//Examples
-//fftn([2,3,4])
-//ans =
-// 9. - 1.5 + 0.8660254i - 1.5 - 0.8660254i
-funcprot(0);
-rhs = argn(2)
-if(rhs<1 | rhs>2)
-error("Wrong number of input arguments.");
-end
-
- select(rhs)
- case 1 then
- y = callOctave("fftn",A);
- case 2 then
- y = callOctave("fftn",A, SIZE);
- end
+ funcprot(0);
+ // Get the number of input arguments
+ rhs = argn(2);
+ // Check if the number of input arguments is valid
+ if rhs < 1 | rhs > 2 then
+ error("Wrong number of input arguments.");
+ end
+ // Perform action based on the number of input arguments
+ switch rhs
+ case 1 // If only A is provided
+ y = fft(A);
+ case 2 // If both A and SIZE are provided
+ // Check if A needs resizing
+ if size(A) == SIZE then
+ // No resizing needed
+ break;
+ elseif length(size(A)) ~= length(SIZE) then
+ error("Output size must have at least Ndims");
+ else
+ // Resize A using the resize_matrix function
+ A = resize_matrix(A, SIZE);
+ end
+ y = fft(A);
+ end
endfunction
+/*
+//test cases
+i=%i;tol = 0.00001; pi = %pi ;
+//test 1
+Y = [41.0000 + 0*i ,-2.5000 + 2.5981*i ,-2.5000 - 2.5981*i ;2.0000 + 8.6603*i , 2.0000 + 3.4641*i , -8.5000 + 11.2583*i ;2.0000 - 8.6603*i , -8.5000 - 11.2583*i , 2.0000 - 3.4641*i]
+assert_checkalmostequal(fftn([3 7 5;0 1 7;9 5 4]),Y,tol)
+// test
+assert_checkalmostequal(fftn([100 278;334 985]),[1697,-829;-941,473],tol)
+assert_checkalmostequal(fftn([2:5;8 7 5 1;7 3 4 5;0 0 1 6],[2 2]),[20,0;-10,-2],tol)
+assert_checkalmostequal(fftn([[i 2+3*i 2+pi;pi i+2 pi+i;1 5+2*5*i pi+10*i]],[2,2]),[7.1416 + 5.0000*i , -0.8584 - 3.0000*i; -3.1416 + 3.0000*i , -3.1416 - 1.0000*i],tol)
+//error
+fftn([2:5;8 7 5 1;7 3 4 5;0 0 1 6],[2]);
+*/
+
diff --git a/macros/fht.sci b/macros/fht.sci
index f7e5c8e..9bd6b38 100644
--- a/macros/fht.sci
+++ b/macros/fht.sci
@@ -1,29 +1,61 @@
-function y=fht(d,n,dim)
-//The Function calculates the Fast Hartley Transform of real input.
-//Calling Sequence
-//M = fht (D)
-//M = fht (D, N)
-//M = fht (D, N, DIM)
-//Parameters
-//Description
-//This function calculates the Fast Hartley transform of real input D. If D is a matrix, the Hartley transform is calculated along the columns by default.
-//Examples
-//fht(1:4)
-//ans =
-// 10 -4 -2 0
-//This function is being called from Octave.
-funcprot(0);
-rhs=argn(2);
-if(rhs<1 | rhs>3)
- error("Wrong number of input arguments.")
-end
-select(rhs)
-case 1 then
- y=callOctave("fht",d)
-case 2 then
- y=callOctave("fht",d,n)
-case 3 then
- y=callOctave("fht",d,n,dim)
-end
-
-endfunction
+/* Description
+ This function calculates the Fast Hartley transform of real input D.
+ If D is a matrix, the Hartley transform is calculated along the columns by default.
+ If N is specified, the first N elements along the specified dimension are used for the transform.
+ If DIM is specified, the transform is calculated along the specified dimension.
+ Calling Sequence
+ M = fht (D)
+ M = fht (D, N)
+ M = fht (D, N, DIM)
+ Parameters
+ D: Input data (real matrix or vector).
+ N: Number of elements of D to be used for the transform (optional).
+ DIM: Dimension along which the transform is to be computed (optional).
+ Examples
+ fht(1:4)
+ ans =
+ 10 -4 -2 0
+*/
+function M = fht(D, N, DIM)
+ funcprot(0);
+ rhs = argn(2);
+ if rhs < 1 | rhs > 3 then
+ error("Wrong number of input arguments.")
+ end
+ // The fht will be calculated along the first non-singleton dimension of the array i.e along the columns by default.
+ dimension = size(D);
+ nsdim = 1;
+ for i = 1:length(dimension)
+ if dimension(i) ~= 1 then
+ nsdim = i;
+ break;
+ end
+ end
+ // Process input arguments
+ select(rhs)
+ case 1 then
+ M = fft(D, -1, nsdim);
+ case 2 then
+ if isempty(N) then
+ n = size(D, nsdim);
+ else
+ n = N;
+ end
+ new_size = size(D);
+ new_size(nsdim) = n;
+ D = resize_matrix(D, new_size);
+ M = fft(D, -1, nsdim);
+ case 3 then
+ if isempty(N) then
+ n = size(D, DIM);
+ else
+ n = N;
+ end
+ new_size = size(D);
+ new_size(DIM) = n;
+ D = resize_matrix(D, new_size);
+ M = fft(D, -1, DIM);
+ end
+ // Return real part of the result
+ M = real(M) - imag(M);
+endfunction
diff --git a/macros/grpdelay.sci b/macros/grpdelay.sci
index a7ffdad..dec9823 100644
--- a/macros/grpdelay.sci
+++ b/macros/grpdelay.sci
@@ -1,51 +1,157 @@
-function [gd,w] = grpdelay(b,a,nfft,whole,Fs)
-//This function computes the group delay of a filter.
-//Calling Sequence
-//gd = grpdelay(b)
-//gd = grpdelay(b, a)
-//gd = grpdelay(b, a, nfft)
-//gd = grpdelay(b, a, nfft, whole)
-//gd = grpdelay(b, a, nfft, whole, Fs)
-//[gd, w] = grpdelay(...)
+/*Description:
+ Compute the group delay of a filter.
+ Theory: group delay, g(w) = -d/dw [arg{H(e^jw)}], is the rate of change of phase with respect to frequency. It can be computed as:
+ d/dw H(e^-jw)
+ g(w) = -------------
+ H(e^-jw)
+ where
+ H(z) = B(z)/A(z) = sum(b_k z^k)/sum(a_k z^k).
+ By the quotient rule,
+ A(z) d/dw B(z) - B(z) d/dw A(z)
+ d/dw H(z) = -------------------------------
+ A(z) A(z)
+ Substituting into the expression above yields:
+ A dB - B dA
+ g(w) = ----------- = dB/B - dA/A
+ A B
+ Note that,
+ d/dw B(e^-jw) = sum(k b_k e^-jwk)
+ d/dw A(e^-jw) = sum(k a_k e^-jwk)
+ which is just the FFT of the coefficients multiplied by a ramp.
+Calling Sequence
+ [g, w] = grpdelay (b) : returns the group delay g of the FIR filter with coefficients b. The response is evaluated at 512 angular frequencies between 0 and pi. w is a vector containing the 512 frequencies. The group delay is in units of samples. It can be converted to seconds by multiplying by the sampling period (or dividing by the sampling rate fs).
+ [g, w] = grpdelay (b, a) : returns the group delay of the rational IIR filter whose numerator has coefficients b and denominator coefficients a.
+ [g, w] = grpdelay (…, n) : returns the group delay evaluated at n angular frequencies. For fastest computation n should factor into a small number of small primes.
+ [g, w] = grpdelay (…, n, "whole") : evaluates the group delay at n frequencies between 0 and 2*pi.
+ [g, f] = grpdelay (…, n, Fs) : evaluates the group delay at n frequencies between 0 and Fs/2.
+ [g, f] = grpdelay (…, n, "whole", Fs) : evaluates the group delay at n frequencies between 0 and Fs.
+ [g, w] = grpdelay (…, w) : evaluates the group delay at frequencies w (radians per sample).
+ [g, f] = grpdelay (…, f, Fs) : evaluates the group delay at frequencies f (in Hz).
+ grpdelay(...) plots the group delay vs. frequency.
+ If the denominator of the computation becomes too small, the group delay is set to zero. (The group delay approaches infinity when there are poles or zeros very close to the unit circle in the z plane.)
+Parameters:
+ b : Coefficients of the numerator polynomial of the filter (FIR or IIR).
+ a : (optional): Coefficients of the denominator polynomial of the filter (only for IIR filters).
+ n : (optional): Number of angular frequencies at which to evaluate the group delay. For efficient computation, n should be a product of small primes.
+ "whole" : (optional): Specifies frequency range. If specified: Frequencies range from 0 to 2π radians per sample.
+ Fs : (numeric value): Frequencies range from 0 to Fs Hz or Fs radians per sample.
+ w : (optional): Vector of specific frequencies (in radians per sample) at which to evaluate the group delay.
+ f : (optional): Vector of specific frequencies (in Hz) at which to evaluate the group delay.
+ Fs : (optional): Sampling rate in Hz. Used to specify the frequency range when f or "whole" is specified.
+Dependencies: fft1
+*/
+function [gd,w] = grpdelay (b, a, n, whole, Fs)
+ lhs=argn(1);
+ rhs= argn(2);
+ if (rhs < 1 | rhs > 5) then
+ error("Invalid number of inputs")
+ end
+ HzFlag= %F;
+
+ select rhs
+ case 1 then
+ Fs=1; whole = "" ; n = 512 ; a = 1 ;
+ case 2 then
+ Fs=1; whole = "" ; n = 512 ;
+ case 3 then
+ Fs=1; whole = "" ;
+ case 4 then
+ Fs=1;
+ end
+ if (max(size(n)) > 1)
+ if (rhs > 4)
+ error("invalid inputs");
+ elseif (rhs > 3)
+ // grpdelay (B, A, F, Fs)
+ Fs = whole;
+ HzFlag = %T;
+ else
+ // grpdelay (B, A, W)
+ Fs = 1;
+ end
+ w = 2*%pi*n/Fs;
+ n = max(size (w) ) * 2;
+ whole = "";
+ else
+ if (rhs < 5)
+ Fs = 1; // return w in radians per sample
+ if (rhs < 4)
+ whole = "" ;
+ elseif (~type(whole)==10)
+ Fs = whole;
+ HzFlag = %T;
+ whole = "";
+ end
+ if (rhs < 3)
+ n = 512;
+ end
+ if (rhs < 2)
+ a = 1;
+ end
+ else
+ HzFlag = %T;
+ end
-//Parameters
-//b:
-//a:
-//nfft:
-
-//Description
-//This is an Octave function.
-//This function computes the group delay of a filter.
-//[g, w] = grpdelay(b) returns the group delay g of the FIR filter with coefficients b. The response is evaluated at 512 angular frequencies between 0 and pi. w is a vector containing the 512 frequencies.
-//[g, w] = grpdelay(b, a) returns the group delay of the rational IIR filter whose numerator has coefficients b and denominator coefficients a.
-//[g, w] = grpdelay(b, a, n) returns the group delay evaluated at n angular frequencies.
-//[g, w] = grpdelay(b, a, n, ’whole’) evaluates the group delay at n frequencies between 0 and 2*pi.
-//[g, f] = grpdelay(b, a, n, Fs) evaluates the group delay at n frequencies between 0 and Fs/2.
-//[g, f] = grpdelay(b, a, n, ’whole’, Fs) evaluates the group delay at n frequencies between 0 and Fs.
-//[g, w] = grpdelay(b, a, w) evaluates the group delay at frequencies w (radians per sample).
-//[g, f] = grpdelay(b, a, f, Fs) evaluates the group delay at frequencies f (in Hz).
-//Examples
-//grpdelay(1,2,3)
-//ans =
-// 0.
-// 0.
-// 0.
-
-funcprot(0);
-rhs = argn(2)
-if(rhs<1 | rhs>5)
-error("Wrong number of input arguments.")
-end
- select(rhs)
- case 1 then
- [gd,w] = callOctave("grpdelay",b)
- case 2 then
- [gd,w] = callOctave("grpdelay",b,a)
- case 3 then
- [gd,w] = callOctave("grpdelay",b,a,nfft)
- case 4 then
- [gd,w] = callOctave("grpdelay",b,a,nfft,whole)
- case 5 then
- [gd,w] = callOctave("grpdelay",b,a,nfft,whole,Fs)
- end
+ if (isempty (n))
+ n = 512;
+ end
+ if ( type(whole) == 10 && strcmp (whole, "whole"))
+ n = 2*n;
+ end
+
+ w = Fs*[0:n-1]/n;
+ end
+ if (~ HzFlag)
+ w = w * 2 * %pi;
+ end
+ a = a(:).';
+ b = b(:).';
+ oa = max(size(a)) -1; // order of a(z)
+ if (oa < 0) // a can be []
+ a = 1;
+ oa = 0;
+ end
+ ob = max(size(b)) -1; // order of b(z)
+ if (ob < 0) // b can be [] as well
+ b = 1;
+ ob = 0;
+ end
+ oc = oa + ob; // order of c(z)
+ c = conv (b, flipdim(conj (a),2)); // c(z) = b(z)*conj(a)(1/z)*z^(-oa)
+ cr = c.*(0:oc); // cr(z) = derivative of c wrt 1/z
+ num = fft1 (cr, n);
+ den = fft1 (c, n);
+ minmag = 10*%eps;
+ polebins = find (abs (den) < minmag);
+ for b = polebins
+ warning ("signal:grpdelay-singularity", "grpdelay: setting group delay to 0 at singularity");
+ num(b) = 0;
+ den(b) = 1;
+ //// try to preserve angle:
+ //// db = den(b);
+ //// den(b) = minmag*abs(num(b))*exp(j*atan2(imag(db),real(db)));
+ //// warning(sprintf('grpdelay: den(b) changed from %f to %f',db,den(b)));
+ end
+ gd = real (num ./ den) - oa;
+ if ( type(whole) == 10 && strcmp (whole, "whole"))
+ ns = n/2; // Matlab convention ... should be n/2 + 1
+ gd = gd(1:ns);
+ w = w(1:ns);
+ else
+ ns = n; // used in plot below
+ end
+ //// compatibility
+ gd = gd(:);
+ w = w(:);
+ if (lhs == 1)
+ if (HzFlag)
+ funits = "Hz";
+ else
+ funits = "radian/sample";
+ end
+ disp(" Plotting ")
+ plot (w(1:ns), gd(1:ns));
+ xlabel (["Frequency (" funits ")"]);
+ ylabel ("Group delay (samples)");
+ end
endfunction
diff --git a/macros/hilbert1.sci b/macros/hilbert1.sci
index fbcb136..476c00c 100644
--- a/macros/hilbert1.sci
+++ b/macros/hilbert1.sci
@@ -1,39 +1,106 @@
-function h= hilbert1(f, varargin)
-//Analytic extension of real valued signal.
-//Calling Sequence
-// h= hilbert1(f)
-// h= hilbert1(f,N)
-// h= hilbert1(f,N,dim)
-//Parameters
-//f: real or complex valued scalar or vector
-//N: The result will have length N
-//dim : It analyses the input in this dimension
-//Description
-//h = hilbert1 (f) computes the extension of the real valued signal f to an analytic signal. If f is a matrix, the transformation is applied to each column. For N-D arrays, the transformation is applied to the first non-singleton dimension.
-//
-//real (h) contains the original signal f. imag (h) contains the Hilbert transform of f.
-//
-//hilbert1 (f, N) does the same using a length N Hilbert transform. The result will also have length N.
-//
-//hilbert1 (f, [], dim) or hilbert1 (f, N, dim) does the same along dimension dim.
-//Examples
-//## notice that the imaginary signal is phase-shifted 90 degrees
-// t=linspace(0,10,256);
-// z = hilbert1(sin(2*pi*0.5*t));
-// grid on; plot(t,real(z),';real;',t,imag(z),';imag;');
-
-funcprot(0);
-rhs= argn(2);
-if(rhs<1 | rhs>3)
- error("Wrong number of Input Arguments")
-end
-
-select(rhs)
- case 1 then
- h= callOctave("hilbert", f);
- case 2 then
- h= callOctave("hilbert", f, varargin(1));
- case 3 then
- h= callOctave("hilbert", f, varargin(1), varargin(2));
-end
+/*Calling Sequence
+ h = hilbert1 (f)
+ h = hilbert1 (f, N)
+ h = hilbert1 (f, N, dim)
+Description
+ Analytic extension of real valued signal.
+ h = hilbert (f) computes the extension of the real valued signal f to an analytic signal.
+ If f is a matrix, the transformation is applied to each column.
+ For N-D arrays, the transformation is applied to the first non-singleton dimension.
+ real (h) contains the original signal f. imag (h) contains the Hilbert transform of f.
+ hilbert (f, N) does the same using a length N Hilbert transform. The result will also have length N.
+ hilbert (f, [], dim) or hilbert (f, N, dim) does the same along dimension dim.
+Dependencies
+ fft1, ifft1, ipermute
+Example
+ //the magnitude of the hilbert transform eliminates the carrier
+ t=linspace(0,10,1024);
+ x=5*cos(0.2*t).*sin(100*t);
+ plot(t,x,t,abs(hilbert(x)));
+ */
+function f=hilbert1(f, N ,dim )
+ // ------ PRE: initialization and dimension shifting ---------
+ nargin = argn(2);
+ if (nargin<1 || nargin>3)
+ error("Please enter valid number of inputs")
+ end
+ if ~isreal(f)
+ warning ('HILBERT: ignoring imaginary part of signal');
+ f = real (f);
+ end
+ D=ndims(f);
+ select nargin
+ case 1 then
+ N=[];
+ dim=[];
+ case 2 then
+ dim=[]
+ end
+ // Dummy assignment.
+ order=1;
+ if isempty(dim)
+ dim=1;
+ if sum(size(f)>1)==1
+ // We have a vector, find the dimension where it lives.
+ dim=find(size(f)>1);
+ end
+ else
+ if (length(dim)~=1 || ~or(type(dim)==[1 5 8]))
+ error('HILBERT: dim must be a scalar.');
+ end
+ if modulo(dim,1)~=0
+ error('HILBERT: dim must be an integer.');
+ end
+ if (dim<1) || (dim>D)
+ error('HILBERT: dim must be in the range from 1 to %d.',D);
+ end
+ end
+ if (length(N)>1 || ~or(type(N)==[1 5 8]))
+ error('N must be a scalar.');
+ elseif (~isempty(N) && modulo(N,1)~=0)
+ error('N must be an integer.');
+ end
+ if dim>1
+ order=[dim, 1:dim-1,dim+1:D];
+ // Put the desired dimension first.
+ f=permute(f,order);
+ end
+ Ls=size(f,1);
+ // If N is empty it is set to be the length of the transform.
+ if isempty(N)
+ N=Ls;
+ end
+ // moduloember the exact size for later and modify it for the new length
+ permutedsize=size(f);
+ permutedsize(1)=N;
+ // Reshape f to a matrix.
+ f=resize_matrix(f,size(f,1),length(f)/size(f,1));
+ W=size(f,2);
+ if ~isempty(N)
+ siz=size(f);
+ siz(1)=N;
+ f=resize_matrix(f,siz);
+ end
+ // ------- actual computation -----------------
+ if N>2
+ f=fft1(f);
+ if modulo(N,2)==0
+ f=[f(1,:);
+ 2*f(2:N/2,:);
+ f(N/2+1,:);
+ zeros(N/2-1,W)];
+ else
+ f=[f(1,:);
+ 2*f(2:(N+1)/2,:);
+ zeros((N-1)/2,W)];
+ end
+ f=ifft1(f);
+ end
+ // ------- POST: Restoration of dimensions ------------
+ // Restore the original, permuted shape.
+ f=matrix(f,permutedsize);
+ if dim>1
+ // Undo the permutation.
+ f=ipermute(f,order);
+ end
endfunction
diff --git a/macros/idct1.sci b/macros/idct1.sci
index 5015187..3f007fa 100644
--- a/macros/idct1.sci
+++ b/macros/idct1.sci
@@ -1,27 +1,39 @@
+/*Description
+ This function computes the inverse discrete cosine transform of input X.
+ If N is given, then X is padded or trimmed to length N before computing the transform.
+ If X is a matrix, compute the transform along the columns of the the matrix.
+ The transform is faster if X is real-valued and even length.
+Calling Sequence
+ Y = idct1(X)
+ Y = idct1(X, N)
+Parameters
+ X: Matrix or integer
+ N: If N is given, then X is padded or trimmed to length N before computing the transform.
+Examples
+ idct1([1,3,6])
+ ans =
+ 5.1481604 - 4.3216292 0.9055197
+*/
function y = idct1(x,n)
-//Compute the inverse discrete cosine transform of input.
-//Calling Sequence
-//Y = idct1(X)
-//Y = idct1(X, N)
-//Parameters
-//X: Matrix or integer
-//N: If N is given, then X is padded or trimmed to length N before computing the transform.
-//Description
-// This function computes the inverse discrete cosine transform of input X. If N is given, then X is padded or trimmed to length N before computing the transform. If X is a matrix, compute the transform along the columns of the the matrix. The transform is faster if X is real-valued and even length.
-//Examples
-//idct1([1,3,6])
-//ans =
-// 5.1481604 - 4.3216292 0.9055197
-funcprot(0);
-rhs=argn(2);
-if (rhs<1 | rhs>2) then
- error("Wrong number of input arguments.");
-end
-select(rhs)
-case 1 then
- y=callOctave("idct",x);
-case 2 then
- y=callOctave("idct",x,n);
-end
-
+ funcprot(0);
+ rhs=argn(2);
+ if (rhs<1 | rhs>2) then
+ error("Wrong number of input arguments.");
+ end
+ nsdim=1;
+ siz=size(x);
+ len=length(siz);
+ for i=1:len
+ if siz(i) ~= 1 then
+ nsdim=i//calculating along non-singlton dimension
+ break;
+ end;
+ end;
+ select(rhs)
+ case 1 then
+ y=idct(x,nsdim);
+ case 2 then
+ siz(nsdim)=n;
+ y=idct(resize_matrix(x,siz),nsdim)
+ end;
endfunction
diff --git a/macros/idct2.sci b/macros/idct2.sci
index c48980a..890927f 100644
--- a/macros/idct2.sci
+++ b/macros/idct2.sci
@@ -1,29 +1,31 @@
-function y = idct2(x,varargin)
-//This function computes the inverse 2-D discrete cosine transform of input matrix.
-//Calling Sequence
-//Y = idct2(X)
-//Y = idct2(X, M, N)
-//Y = idct2(X, [M, N])
-//Parameters
-//X: Matrix or integer
-//M, N: If specified Matrix X is padded with M rows and N columns.
-//Description
-// This function computes the inverse 2-D discrete cosine transform of matrix X. If M and N are specified, the input is either padded or truncated to have M rows and N columns.
-//Examples
-//idct2(3, 4, 6)
-//ans =
-// 2.811261 0.612372 -0.525856 0.250601 0.612372 -0.086516
-funcprot(0);
-rhs=argn(2);
-if (rhs<1 | rhs>3) then
- error("Wrong number of input arguments.");
-end
-select(rhs)
-case 1 then
- y=callOctave("idct2",x)
-case 2 then
- y=callOctave("idct2",x,varargin(1))
-case 3 then
- y=callOctave("idct2",x,varargin(1),varargin(2))
-end
+/*Description
+ This function computes the inverse 2-D discrete cosine transform of matrix X. If M and N are specified, the input is either padded or truncated to have M rows and N columns.
+Calling Sequence
+ Y = idct2(X)
+ Y = idct2(X, M, N)
+ Y = idct2(X, [M, N])
+Parameters
+ X: Matrix or integer
+ M, N: If specified Matrix X is padded with M rows and N columns.
+Examples
+ idct2(3, 4, 6)
+ ans =
+ 2.811261 0.612372 -0.525856 0.250601 0.612372 -0.086516 */
+function y = idct2 (x, m, n)
+ funcprot(0);
+ rhs=argn(2);
+ select (rhs)
+ case 1 then
+ [m,n]=size(x);
+ case 2 then
+ n=m(2);
+ m=m(1);
+ end
+ if m==1 then
+ y=idct1(x.',n).';
+ elseif n==1 then
+ y=idct1(x,m);
+ else
+ y=idct1(idct1(x,m).',n).';
+ end
endfunction
diff --git a/macros/idst1.sci b/macros/idst1.sci
index 98fc874..f7fdc6d 100644
--- a/macros/idst1.sci
+++ b/macros/idst1.sci
@@ -1,27 +1,26 @@
-function y = idst1(x,varargin)
-//This function computes the inverse type I discrete sine transform.
-//Calling Sequence
-//Y = idst(X)
-//Y = idst(X, N)
-//Parameters
-//X: Matrix or integer
-//N: If N is given, then X is padded or trimmed to length N before computing the transform.
-//Description
-//This function computes the inverse type I discrete sine transform of Y. If N is given, then Y is padded or trimmed to length N before computing the transform. If Y is a matrix, compute the transform along the columns of the the matrix.
-//Examples
-//idst([1,3,6])
-//ans =
-// 3.97487 -2.50000 0.97487
-funcprot(0);
-rhs=argn(2);
-if(rhs<1 | rhs>2) then
- error("Wrong number of input arguments.");
-end
-select(rhs)
-case 1 then
- y=callOctave("idst",x);
-case 2 then
- y=callOctave("idst",x,varargin(1));
-end
-
+/*Description
+ This function computes the inverse type I discrete sine transform of X If N is given,
+ then X is padded or trimmed to length N before computing the transform.
+ If X is a matrix, compute the transform along the columns of the the matrix.
+Calling Sequence
+ Y = idst1(X)
+ Y = idst1(X, N)
+Parameters
+ X: Matrix or integer
+ N: If N is given, then X is padded or trimmed to length N before computing the transform.
+Examples
+ idst1([1,3,6])
+ ans =
+ 3.97487 -2.50000 0.97487 */
+function x = idst1 (y, n)
+ nargin=argn(2)
+ if (nargin < 1 || nargin > 2)
+ error("invalid input arguments")
+ end
+ if nargin == 1,
+ n = size(y,1);
+ if n==1, n = size(y,2); end
+ end
+ x = dst1(y, n) * 2/(n+1);
endfunction
+
diff --git a/macros/ifft1.sci b/macros/ifft1.sci
index 3e94934..7c66b19 100644
--- a/macros/ifft1.sci
+++ b/macros/ifft1.sci
@@ -1,51 +1,63 @@
-function res = ifft1 (x, n, dim)
-//Calculates the inverse discrete Fourier transform of a matrix using Fast Fourier Transform algorithm.
-//Calling Sequence
-//ifft (x, n, dim)
-//ifft (x, n)
-//ifft (x)
-//Parameters
-//x: input matrix
-//n: Specifies the number of elements of x to be used
-//dim: Specifies the dimention of the matrix along which the inverse FFT is performed
-//Description
-//This is an Octave function.
-//Description
-//This is an Octave function.
-//The inverse FFT is calculated along the first non-singleton dimension of the array. Thus, inverse FFT is computed for each column of x.
-//
-//n is an integer specifying the number of elements of x to use. If n is larger than dimention along. which the inverse FFT is calculated, then x is resized and padded with zeros.
-//Similarly, if n is smaller, then x is truncated.
-//
-//dim is an integer specifying the dimension of the matrix along which the inverse FFT is performed.
-//Examples
-//x = [1 2 3; 4 5 6; 7 8 9]
-//n = 3
-//dim = 2
-//ifft1 (x, n, dim)
-//ans =
-//
-// 2.00000 + 0.00000i -0.50000 - 0.28868i -0.50000 + 0.28868i
-// 5.00000 + 0.00000i -0.50000 - 0.28868i -0.50000 + 0.28868i
-// 8.00000 + 0.00000i -0.50000 - 0.28868i -0.50000 + 0.28868i
-
-funcprot(0);
-lhs = argn(1)
-rhs = argn(2)
-if (rhs < 1 | rhs > 3)
-error("Wrong number of input arguments.")
-end
-
-select(rhs)
-
- case 1 then
- res = callOctave("ifft", x)
-
- case 2 then
- res = callOctave("ifft", x, n)
-
- case 3 then
- res = callOctave("ifft", x, n, dim)
-
- end
-endfunction
+/* Description
+ Calculates the inverse discrete Fourier transform of a matrix using Fast Fourier Transform algorithm.
+ The inverse FFT is calculated along the first non-singleton dimension of the array. Thus, inverse FFT is computed for each column of x.
+ n is an integer specifying the number of elements of x to use. If n is larger than dimention along. which the inverse FFT is calculated, then x is resized and padded with zeros.
+ Similarly, if n is smaller, then x is truncated.
+ dim is an integer specifying the dimension of the matrix along which the inverse FFT is performed.
+Calling Sequence
+ ifft1 (x)
+ ifft1 (x, n)
+ ifft1 (x, n, dim)
+Parameters
+ x: input matrix
+ n: Specifies the number of elements of x to be used
+ dim: Specifies the dimention of the matrix along which the inverse FFT is performed
+Examples
+ x = [1 2 3; 4 5 6; 7 8 9]
+ n = 3
+ dim = 2
+ ifft1 (x, n, dim)
+ ans =
+ 2.00000 + 0.00000i -0.50000 - 0.28868i -0.50000 + 0.28868i
+ 5.00000 + 0.00000i -0.50000 - 0.28868i -0.50000 + 0.28868i
+ 8.00000 + 0.00000i -0.50000 - 0.28868i -0.50000 + 0.28868i */
+function res = ifft1 (x, n, dim)
+ funcprot(0);
+ lhs = argn(1)
+ rhs = argn(2)
+ if (rhs < 1 | rhs > 3)
+ error("Wrong number of input arguments.")
+ end
+ dimension = size(x);
+ nsdim = 1;
+ for i = 1:length(dimension)
+ if dimension(i) ~= 1 then
+ nsdim = i;
+ break;
+ end
+ end
+ select(rhs)
+ case 1 then
+ res=fft(x,1,nsdim)
+ case 2 then
+ if isempty(n) then
+ res=fft(x,1,nsdim)
+ else
+ dimension(nsdim)=n;
+ res=fft(resize_matrix(x,dimension),1,nsdim)
+ end
+ case 3 then
+ if isempty(n) then
+ res=fft(x,1,dim)
+ else
+ if (length(dimension) <dim )then
+ error("ifft1: DIM must be a valid dimension along which to perform FFT")
+ end
+ dimension(dim)=n;
+ res=resize_matrix(x,dimension);
+ res=fft(res,1,dim);
+ end
+ end
+endfunction
+
+
diff --git a/macros/ifft2.sci b/macros/ifft2.sci
index 8ecb1a5..762631d 100644
--- a/macros/ifft2.sci
+++ b/macros/ifft2.sci
@@ -1,45 +1,55 @@
-function res = ifft2 (A, m, n)
-//Calculates the inverse two-dimensional discrete Fourier transform of A using a Fast Fourier Transform algorithm.
-//Calling Sequence
-//ifft2 (A, m, n)
-//ifft2 (A)
-//Parameters
-//A: input matrix
-//m: number of rows of A to be used
-//n: number of columns of A to be used
-//Description
-//This is an Octave function.
-//It performs inverse two-dimensional FFT on the matrix A. m and n may be used specify the number of rows and columns of A to use. If either of these is larger than the size of A, A is resized and padded with zeros.
-//If A is a multi-dimensional matrix, each two-dimensional sub-matrix of A is treated separately.
-//Examples
-//x = [1 2 3; 4 5 6; 7 8 9]
-//m = 4
-//n = 4
-//ifft2 (A, m, n)
-//ans =
-//
-// 2.81250 + 0.00000i -0.37500 + 0.93750i 0.93750 + 0.00000i -0.37500 - 0.93750i
-// -1.12500 + 0.93750i -0.31250 - 0.50000i -0.37500 + 0.31250i 0.31250 + 0.25000i
-// 0.93750 + 0.00000i -0.12500 + 0.31250i 0.31250 + 0.00000i -0.12500 - 0.31250i
-// -1.12500 - 0.93750i 0.31250 - 0.25000i -0.37500 - 0.31250i -0.31250 + 0.50000i
-
-funcprot(0);
-lhs = argn(1)
-rhs = argn(2)
-if (rhs < 1 | rhs > 3)
-error("Wrong number of input arguments.")
-end
-
-select(rhs)
-
- case 1 then
- res = callOctave("ifft2", A)
-
- case 2 then
- error("Wrong number of input arguments.")
-
- case 3 then
- res = callOctave("ifft2", A, m, n)
-
- end
-endfunction
+Author: Abinash Singh <abinashsinghlalotra@gmail.com>
+*/
+/*Description
+ Calculates the inverse two-dimensional discrete Fourier transform of A using a Fast Fourier Transform algorithm.
+ It performs inverse two-dimensional FFT on the matrix A. m and n may be used specify the number of rows and columns of A to use. If either of these is larger
+ than the size of A, A is resized and padded with zeros.
+ If A is a multi-dimensional matrix, each two-dimensional sub-matrix of A is treated separately.
+Calling Sequence
+ ifft2 (A)
+ ifft2 (A, m, n)
+Parameters
+ A: input matrix
+ m: number of rows of A to be used
+ n: number of columns of A to be used
+Examples
+ A= [1 2 3; 4 5 6; 7 8 9]
+ m = 4
+ n = 4
+ ifft2 (A, m, n) --functionCall
+ ans =
+ 2.81250 + 0.00000i -0.37500 + 0.93750i 0.93750 + 0.00000i -0.37500 - 0.93750i
+ -1.12500 + 0.93750i -0.31250 - 0.50000i -0.37500 + 0.31250i 0.31250 + 0.25000i
+ 0.93750 + 0.00000i -0.12500 + 0.31250i 0.31250 + 0.00000i -0.12500 - 0.31250i
+ -1.12500 - 0.93750i 0.31250 - 0.25000i -0.37500 - 0.31250i -0.31250 + 0.50000i
+*/
+function res = ifft2(A, m, n)
+ funcprot(0);
+ lhs = argn(1)
+ rhs = argn(2)
+ if (rhs < 1 | rhs > 3)
+ error("Wrong number of input arguments.")
+ end
+ size_x=size(A)
+ len=length(size_x)
+ //to figure out size of multidimensional array
+ if len>2 then
+ last_dim=size_x(len)
+ else
+ last_dim=1
+ end
+ select(rhs)
+ case 1 then
+ res=[]
+ for i=1:last_dim //treating each submatrix seperately
+ res(:,:,i)=fft(A(:,:,i),1)
+ end
+ case 2 then
+ error("Wrong number of input arguments.")
+ case 3 then
+ res=[]
+ for i=1:last_dim
+ res(:,:,i)=fft(resize_matrix(A(:,:,i),m,n),1)
+ end
+ end
+endfunction
diff --git a/macros/ifftn.sci b/macros/ifftn.sci
index 3d26c04..941dc67 100644
--- a/macros/ifftn.sci
+++ b/macros/ifftn.sci
@@ -1,27 +1,42 @@
-function y = ifftn(A, varargin)
-//Compute the inverse N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
-//Calling Sequence
-//Y = ifftn(A)
-//Y = ifftn(A, size)
-//Parameters
-//A: Matrix
-//Description
-//Compute the inverse N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm. The optional vector argument SIZE may be used specify the dimensions of the array to be used. If an element of SIZE is smaller than the corresponding dimension of A, then the dimension of A is truncated prior to performing the inverse FFT. Otherwise, if an element of SIZE is larger than the corresponding dimension then A is resized and padded with zeros.
-//Examples
-//ifftn([2,3,4])
-//ans =
-// 3. - 0.5 - 0.2886751i - 0.5 + 0.2886751i
-funcprot(0);
-funcprot(0);
-rhs = argn(2)
-if(rhs<1 | rhs>2)
-error("Wrong number of input arguments.");
-end
-
- select(rhs)
- case 1 then
- y = callOctave("ifftn",A);
- case 2 then
- y = callOctave("ifftn",A, varargin(1));
- end
-endfunction
+*/
+/*Description
+ Compute the inverse N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
+ The optional vector argument SIZE may be used specify the dimensions of the matrix to be used.
+ If an element of SIZE is smaller than the corresponding dimension of A, then the dimension of A is truncated prior to performing the inverse FFT.
+ Otherwise, if an element of SIZE is larger than the corresponding dimension then A is resized and padded with zeros.
+Calling Sequence
+ Y = ifftn(A)
+ Y = ifftn(A, size)
+Parameters
+ A: Matrix
+ SIZE : (optional) dimension of matrix to be used
+Examples
+ ifftn([2,3,4])
+ ans =
+ 3. - 0.5 - 0.2886751i - 0.5 + 0.2886751i */
+function y = ifftn(A, SIZE)
+ funcprot(0);
+ funcprot(0);
+ rhs = argn(2)
+ if(rhs<1 | rhs>2)
+ error("Wrong number of input arguments.");
+ end
+ select(rhs)
+ case 1 then
+ y=fft(A,1);
+ case 2 then
+ // Check if A needs resizing
+ if size(A) == SIZE then
+ // No resizing needed
+ break;
+ elseif length(size(A)) ~= length(SIZE) then
+ error("Output size must have at least Ndims");
+ else
+ // Resize A using the resize_matrix function
+ A = resize_matrix(A, SIZE);
+ end
+ y = fft(A,1);
+ end
+ y = clean( y ) ;
+endfunction
+
diff --git a/macros/ipermute.sci b/macros/ipermute.sci
new file mode 100644
index 0000000..ed78383
--- /dev/null
+++ b/macros/ipermute.sci
@@ -0,0 +1,25 @@
+/*
+Description
+ The inverse of the permute function.
+ The expression
+ ipermute (permute (A, perm), perm)
+ returns the original array A.
+Calling Sequence
+ ipermute (A, iperm)
+*/
+function B = ipermute(A, perm)
+ // ipermute : Inverse permute the dimensions of a matrix A.
+ // B = ipermute(A, perm) returns the array A with dimensions inverted
+ // according to the permutation vector `perm`.
+ // Validate the permutation vector
+ if max(size(perm)) ~= ndims(A) || or(gsort(perm, "g", "i") ~= 1:ndims(A))
+ error('Permutation vector must contain unique integers from 1 to ndims(A).');
+ end
+ // Compute the inverse permutation vector
+ invPerm = zeros(size(perm,1),size(perm , 2));
+ for i = 1:max(size(perm))
+ invPerm(perm(i)) = i;
+ end
+ // Use the permute function with the inverse permutation
+ B = permute(A, invPerm);
+endfunction
diff --git a/macros/ols.sci b/macros/ols.sci
new file mode 100644
index 0000000..f2b0b35
--- /dev/null
+++ b/macros/ols.sci
@@ -0,0 +1,70 @@
+/*
+Description:
+ Ordinary least squares estimation.
+ OLS applies to the multivariate model y = x*b + e with mean (e) = 0 and
+ cov (vec (e)) = kron (s, I). where y is a t by p matrix, x is a t by k matrix, b is a k by p matrix, and e is a t by p matrix.
+ Each row of y and x is an observation and each column a variable.
+ The return values beta, sigma, and r are defined as follows.
+Calling Sequence:
+ [beta, sigma, r] = ols (y, x)
+Arguments:
+ beta:
+ The OLS estimator for b. beta is calculated directly via inv (x'*x) * x' * y if the matrix x'*x is of full rank. Otherwise, beta = pinv (x) * y where pinv (x) denotes the pseudoinverse of x.
+ sigma
+ The OLS estimator for the matrix s,
+ sigma = (y-x*beta)'* (y-x*beta) / (t-rank(x))
+ r
+ The matrix of OLS residuals, r = y - x*beta.
+*/
+function [bt, sigma, r] = ols (y, x)
+ function [u , p] = formatted_chol(z)
+ //p flags whether the matrix A was positive definite and chol does not fail. A zero value of p indicates that matrix A is positive definite and R gives the factorization. Otherwise, p will have a positive value.
+ ierr = execstr (" u = chol (z);",'errcatch' )
+ if ( ierr == 29 )
+ p = %T ;
+ warning("chol: Matrix is not positive definite.")
+ u = %nan
+ else
+ p = %F ;
+ end
+ endfunction
+ nargin = argn ( 2 )
+ if (nargin ~= 2)
+ error ("null");
+ end
+ if (~ (or (type(x) == [ 1 5 8] ) && or (type(y) == [1 5 8])))
+ error ("ols: X and Y must be numeric matrices or vectors");
+ end
+ if (ndims (x) ~= 2 || ndims (y) ~= 2)
+ error ("ols: X and Y must be 2-D matrices or vectors");
+ end
+ [nr, nc] = size (x);
+ [ry, cy] = size (y);
+ if (nr ~= ry)
+ error ("ols: number of rows of X and Y must be equal");
+ end
+ if (type(x) == 8)
+ x = double (x);
+ end
+ if ( type(y) == 8 )
+ y = double (y);
+ end
+ // Start of algorithm
+ z = x' * x;
+ [u, p] = formatted_chol (z);
+ if (p)
+ bt = pinv (x) * y;
+ else
+ bt = u \ (u' \ (x' * y));
+ end
+ if (nargout > 1)
+ r = y - x * bt;
+ // z is of full rank, avoid the SVD in rnk
+ if (p == 0)
+ rnk = size (z,2);
+ else
+ rnk = rank (z);
+ end
+ sigma = r' * r / (nr - rnk);
+ end
+endfunction
diff --git a/macros/rceps.sci b/macros/rceps.sci
index f0433a3..831611f 100644
--- a/macros/rceps.sci
+++ b/macros/rceps.sci
@@ -1,48 +1,48 @@
+ /*Description
+ Real cepstrum and minimum-phase reconstruction
+ If called with two output arguments,
+ the minimum phase reconstruction of the signal x is returned in ym.Calling Sequence
+ [y,ym] = rceps(x)
+ Parameters
+ x : A vector or a Matirx
+ y : Real cepstrum
+ ym : Minimum-phase reconstruction
+ Dependencies fft1 , ifft1
+ Example:
+ // create a 45 Hz sine wave sampled at 100 Hz.
+ t = 0:0.01:1.27;
+ s1 = sin(2*%pi*45*t);
+ s2 = s1 + 0.5*[zeros(1,20) s1(1:108)]; //Add an echo of the signal, with half the amplitude, 0.2 seconds after the beginning of the signal.
+ c = rceps(s2); // real cepstrum of signal
+ plot(t,c)
+*/
function [y, xm]= rceps(x)
-//Produce the cepstrum of the signal x, and if desired, the minimum phase reconstruction of the signal x.
-//Calling Sequence
-//[y, xm] = rceps(x)
-//Parameters
-//x: real or complex vector input
-//Produce the cepstrum of the signal x, and if desired, the minimum phase reconstruction of the signal x. If x is a matrix, do so for each column of the matrix.
-//Examples
-// f0 = 70; Fs = 10000; # 100 Hz fundamental, 10kHz sampling rate
-// a = poly (0.985 * exp (1i*pi*[0.1, -0.1, 0.3, -0.3])); # two formants
-// s = 0.005 * randn (1024, 1); # Noise excitation signal
-// s(1:Fs/f0:length(s)) = 1; # Impulse glottal wave
-// x = filter (1, a, s); # Speech signal in x
-// [y, xm] = rceps (x .* hanning (1024)); # cepstrum and min phase reconstruction
-
-if(argn(2)~= 1 )
-error("Wrong number of Input Arguments");
-end
-
-if(argn(1)>2)
-error("Wrong number of Output Arguments")
-end
- f = abs(fft1(x));
- if (or(f == 0))
- error ("The spectrum of x contains zeros, unable to compute real cepstrum");
- end
-
- y = real(ifft1(log(f)));
-
- if argn(1) == 2 then
- n=length(x);
- if size(x,1)==1 then
- if (n-fix(n./2).*2) ==1 then
- xm = [y(1), 2*y(2:n/2+1), zeros(1,n/2)];
- else
- xm = [y(1), 2*y(2:n/2), y(n/2+1), zeros(1,n/2-1)];
+ if(argn(2)~= 1 )
+ error("Wrong number of Input Arguments");
+ end
+ if(argn(1)>2)
+ error("Wrong number of Output Arguments")
+ end
+ f = abs(fft1(x));
+ if (or(f == 0))
+ error ("The spectrum of x contains zeros, unable to compute real cepstrum");
end
- else
- if (n-fix(n./2).*2)==1
- xm = [y(1,:); 2*y(2:n/2+1,:); zeros(n/2,size(y,2))];
- else
- xm = [y(1,:); 2*y(2:n/2,:); y(n/2+1,:); zeros(n/2-1,size(y,2))];
+ y = real(ifft1(log(f)));
+ if argn(1) == 2 then
+ n=max(size(x));
+ if size(x,1)==1 then
+ if (n-fix(n./2).*2) ==1 then
+ xm = [y(1), 2*y(2:n/2+1), zeros(1,n/2)];
+ else
+ xm = [y(1), 2*y(2:n/2), y(n/2+1), zeros(1,n/2-1)];
+ end
+ else
+ if (n-fix(n./2).*2)==1
+ xm = [y(1,:); 2*y(2:n/2+1,:); zeros(n/2,size(y,2))];
+ else
+ xm = [y(1,:); 2*y(2:n/2,:); y(n/2+1,:); zeros(n/2-1,size(y,2))];
+ end
+ end
+ xm = real(ifft1(exp(fft1(xm))));
end
- end
- xm = real(ifft1(exp(fft1(xm)')));
- end
-
endfunction
diff --git a/macros/shanwavf.sci b/macros/shanwavf.sci
index a597214..e088f60 100644
--- a/macros/shanwavf.sci
+++ b/macros/shanwavf.sci
@@ -1,30 +1,39 @@
+/*Description
+ Compute the Complex Shannon wavelet.
+ The complex Shannon wavelet is defined by a bandwidth parameter fb, a wavelet center frequency fc, and the expression
+ psi(x) = f * b^{1/2}sinc(fb . x) e^{2 pi i f c x}
+ on an n-point regular grid in the interval of lb to ub.
+Calling Sequence
+ [psi, x]= shanwavf(lb, ub, n, fb, fc)
+Input Parameters
+ lb, ub (Real valued scalers) : Interval endpoints lb ≤ ub, specified as a pair of real-valued scalars.
+ n (Real valued integer strictly positive)` : Number of regularly spaced points in the interval [lb,ub], specified as a positive integer.
+ fb : Time-decay parameter of the wavelet (bandwidth in the frequency domain). Must be a positive scalar.
+ fc : Center frequency of the complex Shannon wavelet, specified as a positive scalar.
+Output Parameters
+ psi : Complex Shannon wavelet evaluated on the n point regular grid x in the interval [lb,ub], returned as a 1-by-n vector.
+ x : Grid where the complex Shannon wavelet is evaluated, returned as a 1-by-n vector. The sample points are evenly distributed between lb and ub.
+Examples
+ 1.[a,b]=shanwavf (2,8,3,1,6)
+ a = [-3.8982e-17 + 1.1457e-31i 3.8982e-17 - 8.4040e-31i -3.8982e-17 + 4.5829e-31i]
+ b = [2 5 8] */
function [psi,x]=shanwavf(lb,ub,n,fb,fc)
-
-// Complex Shannon Wavelet
-// Calling Sequence
-// [psi,x]=shanwavf(lb,ub,n,fb,fc)
-// Parameters
-// lb: Real or complex valued vector or matrix
-// ub: Real or complex valued vector or matrix
-// n: Real valued integer strictly positive
-// fb: Real or complex valued vector or matrix, strictly positive value for scalar input
-// fc: Real or complex valued vector or matrix, strictly positive value for scalar input
-// Description
-// This is an Octave function
-// This function implements the complex Shannon wavelet function and returns the value obtained. The complex Shannon wavelet is defined by a bandwidth parameter FB, a wavelet center frequency FC on an N point regular grid in the interval [LB,UB].
-// Examples
-// 1. [a,b]=shanwavf (2,8,3,1,6)
-// a = [-3.8982e-17 + 1.1457e-31i 3.8982e-17 - 8.4040e-31i -3.8982e-17 + 4.5829e-31i]
-// b = [2 5 8]
-// 2. [a,b]=shanwavf(1,2,1,[2,2;i,2],[-1,2;-i,i])
-// a = [-5.5128e-17 - 2.7005e-32i -5.5128e-17 + 5.4010e-32i;
-// 8.6404e+06 + 8.6404e+06i -1.9225e-22 - 0.0000e+00i]
-// b = 2
-
-funcprot(0);
-rhs=argn(2);
-if (rhs~=5) then
- error ("Wrong number of input arguments.")
-else [psi,x]=callOctave("shanwavf",lb,ub,n,fb,fc)
-end
+ funcprot(0);
+ rhs=argn(2);
+ if (rhs~=5) then
+ error ("Wrong number of input arguments.")
+ else
+ if (n <= 0 || floor(n) ~= n)
+ error("n must be an integer strictly positive");
+ elseif (fc <= 0 || fb <= 0)
+ error("fc and fb must be strictly positive");
+ end
+ x = linspace(lb,ub,n);
+ sincx=x;
+ for i=1:n
+ sincx(i)=sin(fb*x(i)*%pi)/(fb*x(i)*%pi);
+ end
+ psi = (fb.^0.5).*(sincx.*exp(2.*%i.*%pi.*fc.*x));
+ end
endfunction
+
diff --git a/macros/spectral_adf.sci b/macros/spectral_adf.sci
index 38b3990..e1cc5a2 100644
--- a/macros/spectral_adf.sci
+++ b/macros/spectral_adf.sci
@@ -1,33 +1,67 @@
-function y= spectral_adf(x, varargin)
-// Return the spectral density estimator given a vector of autocovariances C, window name WIN, and bandwidth, B.
-//Calling Sequence
-//spectral_adf(C)
-//spectral_adf(C, WIN)
-//spectral_adf(C, WIN, B)
-//Parameters
-//C: Autocovariances
-//WIN: Window names
-//B: Bandwidth
-//Description
-//Return the spectral density estimator given a vector ofautocovariances C, window name WIN, and bandwidth, B.
-//The window name, e.g., "triangle" or "rectangle" is used to search for a function called 'WIN_lw'.
-//If WIN is omitted, the triangle window is used.
-//If B is omitted, '1 / sqrt (length (C))' is used.
-
-
-funcprot(0);
-rhs= argn(2);
-if(rhs<1 | rhs>3)
-error("Wrong number of input arguments")
-end
-
-select(rhs)
- case 1 then
- y= callOctave("spectral_adf", x);
- case 2 then
- y= callOctave("spectral_adf", x , varargin(1));
- case 3 then
- y= callOctave("spectral_adf", x , varargin(1), varargin(2));
-
-end
-endfunction
+/* spectral_adf
+ Calling Sequence
+ spectral_adf (c)
+ spectral_adf (c, win)
+ spectral_adf (c, win, b)
+ Parameters
+ c : Vector of autocovariances
+ win : The window name . Default window is "triangle"
+ b : Bandwidth. Default is 1/sqrt(length(c))
+ Description
+ Return the spectral density estimator given a vector of autocovariances c, window name win, and bandwidth, b.
+ The window name, e.g., "triangle" or "rectangle" is used to search for a function called win_lw.
+ If win is omitted, the triangle window is used.
+ If b is omitted, 1 / sqrt (length (c)) is used.
+ Dependencies: fft1 */
+function sde = spectral_adf (c, win, b)
+ //c should be a vector
+ if ~isvector(c)
+ error("spectral_adf: input c should be a vector")
+ end
+ // maximum along the columns
+ function max_value = col_max (A)
+ max_value = zeros ( 1, size(A,2))
+ for i = 1:length(max_value)
+ max_value(i) = max(A(:,i))
+ end
+ endfunction
+ //window functions
+ function c = triangle_lw (n, b)
+ c = 1 - (0 : n-1)' * b;
+ c = [c' ; zeros(1, n)]
+ c = col_max (c)'
+ endfunction
+ function c = rectangle_lw (n, b)
+ c = zeros (n, 1);
+ t = floor (1 / b);
+ c(1:t) = 1;
+ endfunction
+ // main part
+ nargin = argn(2)
+ if (nargin < 1)
+ error("wrong number of inputs.");
+ end
+ cr = max(size (c) );
+ if (size (c , 2) > 1)
+ c = c';
+ end
+ if (nargin < 3)
+ b = 1 / ceil (sqrt (cr));
+ end
+ if (nargin == 1)
+ w = triangle_lw (cr, b);
+ elseif (~ (type (win) == 10) )
+ error ("spectral_adf: WIN must be a string");
+ elseif (~strcmp (win , "rectangle" ) )
+ w = rectangle_lw(cr , b) ;
+ elseif (~strcmp (win , "triangle" ) )
+ w = triangle_lw(cr , b) ;
+ else
+ error("Invalid window or this window is not supported yet")
+ end
+ c=c .* w;
+ sde = 2 * real (fft1 (c)) - c(1);
+ zer= zeros(cr, 1);
+ sde = [zer sde];
+ sde(:, 1) = (0 : cr-1)' / cr;
+ endfunction
diff --git a/macros/spectral_xdf.sci b/macros/spectral_xdf.sci
index f0d457b..6081c71 100644
--- a/macros/spectral_xdf.sci
+++ b/macros/spectral_xdf.sci
@@ -1,31 +1,66 @@
-function y= spectral_xdf(x, varargin)
-// Return the spectral density estimator given a data vector X, window name WIN, and bandwidth, B.
-//Calling Sequence
-//spectral_xdf(X)
-//spectral_xdf(X, WIN)
-//spectral_xdf(X, WIN, B)
-//Parameters
-//X: Data Vector
-//WIN: Window names
-//B: Bandwidth
-//Description
-//Return the spectral density estimator given a data vector X, window name WIN, and bandwidth, B.
-//The window name, e.g., "triangle" or "rectangle" is used to search for a function called 'WIN_lw'.
-//If WIN is omitted, the triangle window is used.
-//If B is omitted, '1 / sqrt (length (X))' is used.
-funcprot(0);
-rhs= argn(2);
-if(rhs<1 | rhs>3)
-error("Wrong number of input arguments")
-end
-
-select(rhs)
- case 1 then
- y= callOctave("spectral_xdf", x);
- case 2 then
- y= callOctave("spectral_xdf", x , varargin(1));
- case 3 then
- y= callOctave("spectral_xdf", x , varargin(1), varargin(2));
-
-end
+/* Description
+ Return the spectral density estimator given a data vector x, window name win, and bandwidth, b.
+ The window name, e.g., "triangle" or "rectangle" is used to search for a function called win_sw.
+ If win is omitted, the triangle window is used.
+ If b is omitted, 1 / sqrt (length (x)) is used.
+ Calling Sequence
+ spectral_xdf (x)
+ spectral_xdf (x, win)
+ spectral_xdf (x, win, b)
+ Parameters
+ x : Data vector
+ win : the window name . Default "triangle" is used .
+ b : Bandwidth . Default value 1/sqrt(length(x))
+Dependencies:fft1 ifft1 */
+function sde = spectral_xdf (x, win, b)
+ // check x is a vector or not
+ if ~isvector(x)
+ error("spectral_xdf : x must a data vector")
+ end
+ // available windows - rectangle
+ function c = rectangle_sw (n, b)
+ c = zeros (n, 1);
+ c(1) = 2 / b + 1;
+ l = (2:n)' - 1;
+ l = 2 * %pi * l / n;
+ c(2:n) = sin ((2/b + 1) * l / 2) ./ sin (l / 2);
+ endfunction
+ // triangle
+ function retval = triangle_sw (n, b)
+ retval = zeros (n,1);
+ retval(1) = 1 / b;
+ l = (2:n)' - 1;
+ l = 2 * %pi * l / n;
+ retval(2:n) = b * (sin (l / (2*b)) ./ sin (l / 2)).^2;
+ endfunction
+ // main function
+ nargin = argn(2)
+ if (nargin < 1)
+ error("invalid inputs");
+ end
+ xr = max(size (x) );
+ if (size (x, 2) > 1)
+ x = x';
+ end
+ if (nargin < 3)
+ b = 1 / ceil (sqrt (xr));
+ end
+ if (nargin == 1)
+ w = triangle_sw (xr, b);
+ elseif (~ (type(win)== 10))
+ error ("spectral_xdf: WIN must be a string");
+ elseif (~strcmp (win , "triangle" ) )
+ w = triangle_sw (xr , b);
+ elseif (~strcmp (win , "rectangle" ) )
+ w = rectangle_sw ( xr , b);
+ else
+ error("Invalid window or this window is not supported yet");
+ end
+ x = x - sum (x) / xr;
+ sde = (abs (fft1 (x)) / xr).^2;
+ sde = real (ifft1 (fft1 (sde) .* fft1 (w)));
+ zer = zeros(xr,1);
+ sde = [zer sde];
+ sde(:, 1) = (0 : xr-1)' / xr;
+ sde = clean(sde);
endfunction
diff --git a/macros/unwrap2.sci b/macros/unwrap2.sci
index b8ea9de..7844e38 100644
--- a/macros/unwrap2.sci
+++ b/macros/unwrap2.sci
@@ -1,35 +1,211 @@
-function Y = unwrap2 (X, TOL, DIM)
-//Unwrap radian phases by adding or subtracting multiples of 2*pi.
-//Calling Sequence
-//B = unwrap(X)
-//B = unwrap(X, TOL)
-//B = unwrap(X, TOL, DIM)
-//Parameters
-//Description
-//This function unwraps radian phases by adding or subtracting multiples of 2*pi as appropriate to remove jumps greater than TOL.
-//
-// TOL defaults to pi.
-//
-//Unwrap will work along the dimension DIM. If DIM is unspecified it defaults to the first non-singleton dimension.
-//Examples
-//unwrap2([1,2,3])
-//ans =
-// 1. 2. 3.
-funcprot(0);
-lhs = argn(1);
-rhs = argn(2);
-if (rhs < 1 | rhs > 3)
-error("Wrong number of input arguments.");
-end
-
-select(rhs)
-
- case 1 then
- Y = callOctave("unwrap",X);
- case 2 then
- Y = callOctave("unwrap",X,TOL);
- case 3 then
- Y = callOctave("unwrap",X,TOL,DIM);
- end
-
+/*Description:
+ The unwrap function adjusts radian phases in the input array x by adding or subtracting multiples of
+ 2π as necessary to remove phase jumps that exceed the specified tolerance tol. If tol is not provided, it defaults to 𝜋
+ Radian Phases: These are typically angles or phases expressed in radians, commonly encountered in signal processing and communication systems.
+ Tolerance (tol): Determines the maximum allowable discontinuity in the phases.
+ If the difference between consecutive phases exceeds tol, unwrap adjusts the phase by adding or subtracting 2π.
+ Dimension (dim): Specifies the dimension along which the unwrapping operation is applied.
+ By default, unwrap operates along the first non-singleton dimension of the input array x.
+Calling Sequence:
+ b = unwrap(x)
+ b = unwrap(x, tol)
+ b = unwrap(x, tol, dim)
+Parameters:
+ x: Input array containing radian phases to be unwrapped.
+ tol (optional): Tolerance parameter specifying the maximum jump allowed between consecutive phases before adding or subtracting 2π. Defaults to 𝜋
+ dim (optional): Dimension along which to unwrap the phases. If unspecified, dim defaults to the first non-singleton dimension of the array x.
+Dependencies : ipermute*/
+function retval = unwrap2 (x, tol, dim)
+ nargin = argn(2)
+ if (nargin < 1)
+ error("invalid number of inputs");
+ end
+ if (~ (type(x) == [ 1 5 8]) || or(type(x)==[4,6]))
+ error ("unwrap2: X must be numeric");
+ end
+ if (nargin < 2 || isempty (tol))
+ tol = %pi;
+ end
+ // Don't let anyone use a negative value for TOL.
+ tol = abs (tol);
+ nd = ndims (x);
+ sz = size (x);
+ if (nargin == 3)
+ if (~(or(type(dim)==[1 5 8])&& isscalar (dim) && ...
+ dim == fix (dim)) || ~(1 <= dim))
+ error ("unwrap2: DIM must be an integer and a valid dimension");
+ end
+ else
+ // Find the first non-singleton dimension.
+ dim = find (sz > 1, 1)
+ if isempty(dim)
+ dim = 1;
+ end
+ end
+ rng = 2*%pi;
+ // Handle case where we are trying to unwrap a scalar, or only have
+ // one sample in the specified dimension (a given when dim > nd).
+ if ((dim > nd) || ( sz(dim) == 1))
+ retval = x;
+ return;
+ end
+ if (and(abs(x(:))<%inf ) )
+ // Take first order difference so that wraps will show up as large values
+ // and the sign will show direction.
+ if length(sz) < 3
+ sz(3) = 1 ;
+ end
+ sz(dim) = 1;
+ zero_padding = zeros (sz(1),sz(2),sz(3));
+ d = cat (dim, zero_padding, -diff (x, 1, dim));
+ // Find only the peaks and multiply them by the appropriate amount
+ // of ranges so that there are kronecker deltas at each wrap point
+ // multiplied by the appropriate amount of range values.
+ p = round (abs (d)./rng) .* rng .* (double(double(d > tol) > 0) - double(double(d < -tol) > 0));
+ // Integrate this so that the deltas become cumulative steps to shift
+ // the original data.
+ retval = cumsum (p, dim) + x;
+ else
+ // Unwrap needs to skip over NaN, NA, Inf in wrapping calculations.
+ if (isvector (x))
+ // Simlpified path for vector inputs.
+ retval = x;
+ xfin_idx = abs(x)<%inf ;
+ xfin = x(xfin_idx);
+ d = cat (dim, 0, -diff(xfin, 1, dim));
+ p = round (abs (d)./rng) .* rng .* (double(double(d > tol) > 0) - double(double(d < -tol) > 0));
+ retval(xfin_idx) = xfin + cumsum (p, dim);
+ else
+ // For n-dimensional arrays with a possibly unequal number of non-finite
+ // values, mask entries with values that do not impact calcualation.
+ // Locate nonfinite values.
+ nf_idx = ~ abs(x)<%inf;
+ if (and(nf_idx(:)))
+ // Trivial case, all non-finite values
+ retval = x;
+ return;
+ end
+ // Permute all operations to occur along dim 1. Inverse permute at end.
+ permuteflag = dim ~= 1;
+ if (permuteflag)
+ perm_idx = [1 : nd];
+ perm_idx([1, dim]) = [dim, 1];
+ x = permute (x, perm_idx);
+ nf_idx = permute (nf_idx, perm_idx);
+ sz([1, dim]) = sz([dim, 1]);
+ dim = 1;
+ end
+ // Substitute next value in dim direction for nonfinite values(ignoring
+ // any at trailing end) to prevent calculation impact.
+ x_nf = x(nf_idx); // Store nonfinite values.
+ zero_padding = zeros ([1, sz(2:$)]);
+ x = __fill_nonfinite_columnwise__ (x, nf_idx, zero_padding, sz, nd);
+ d = [zero_padding; -diff(x, 1, 1)];
+ p = round (abs (d)./rng) .* rng .* ...
+ (((d > tol) > 0) - ((d < -tol) > 0));
+ retval = x + cumsum (p, 1);
+ // Restore nonfinite values.
+ retval(nf_idx) = x_nf;
+ // Invert permutation.
+ if (permuteflag)
+ retval = ipermute (retval, perm_idx);
+ end
+ end
+ end
endfunction
+function y = repelems(x,r)
+ y = [];
+ for i = 1:size(r,2)
+ y = [y, x(r(1,i)*ones(1, r(2,i)))];
+ end
+endfunction
+function x = __fill_nonfinite_columnwise__ (x, nonfinite_loc, zero_padding, szx, ndx)
+ // Replace non-finite values of x, as indicated by logical index
+ // nonfinite_loc, with next values.
+ flip_idx(1:ndx) = {':'};
+ flip_idx(1) = {szx(1):-1:1};
+ // Isolate nf values by location:
+ nf_front = cumprod (nonfinite_loc, 1);
+ nf_back = cumprod (nonfinite_loc(flip_idx{:}), 1)(flip_idx{:});
+ nf_middle = nonfinite_loc & ~ (nf_back | nf_front);
+ // Process bound/middle elements
+ locs_before = [diff(nf_middle, 1, 1); zero_padding] == 1;
+ locs_after = diff ([zero_padding; nf_middle], 1, 1) == -1;
+ mid_gap_sizes = find (locs_after) - find (locs_before) - 1;
+ x(nf_middle) = repelems (x(locs_after), ...
+ [1 : numel(mid_gap_sizes); mid_gap_sizes'])';
+ // Process front edge elements
+ nf_front = nf_front & ~ and (nonfinite_loc, 1); // Remove all nf columns.
+ locs_after = diff ([zero_padding; nf_front], 1, 1) == -1;
+ front_gap_sizes = (sum (nf_front, 1))(any (nf_front, 1))(:);
+ x(nf_front) = repelems (x(locs_after), ...
+ [1:length(front_gap_sizes); front_gap_sizes'])';
+endfunction
+/*
+//Test cases
+i = 0;
+t = [];
+r = [0:100]; // original vector
+w = r - 2*%pi*floor ((r+%pi)/(2*%pi)); // wrapped into [-pi,pi]
+tol = 1e3*%eps;
+assert_checkalmostequal (r, unwrap2 (w), tol)
+assert_checkalmostequal (r', unwrap2 (w'), tol)
+assert_checkalmostequal ([r',r'], unwrap2 ([w',w']), tol)
+assert_checkalmostequal ([r; r ], unwrap2 ([w; w ], [], 2), tol)
+assert_checkalmostequal(r + 10, unwrap2 (10 + w), tol)
+assert_checkequal (w', unwrap2 (w', [], 2))
+assert_checkequal(w, unwrap2 (w, [], 1))
+assert_checkequal([w; w], unwrap2 ([w; w]))
+// Test that small values of tol have the same effect as tol = pi
+assert_checkalmostequal(r, unwrap2 (w, 0.1), tol)
+assert_checkalmostequal(r, unwrap2 (w, %eps), tol)
+// Test that phase changes larger than 2*pi unwrap properly
+assert_checkalmostequal([0; 1], unwrap2([0; 1]))
+assert_checkalmostequal([0; 4 - 2*%pi], unwrap2 ([0; 4]))
+assert_checkalmostequal([0; 7 - 2*%pi], unwrap2 ([0; 7]))
+assert_checkalmostequal([0; 10 - 4*%pi], unwrap2 ([0; 10]))
+assert_checkalmostequal([0; 13 - 4*%pi], unwrap2 ([0; 13]))
+assert_checkalmostequal([0; 16 - 6*%pi], unwrap2 ([0; 16]))
+assert_checkalmostequal([0; 19 - 6*%pi], unwrap2 ([0; 19]))
+//test
+A = [%pi*(-4), %pi*(-2+1/6), %pi/4, %pi*(2+1/3), %pi*(4+1/2), %pi*(8+2/3), %pi*(16+1), %pi*(32+3/2), %pi*64];
+assert_checkalmostequal (unwrap2 (A), unwrap2 (A, %pi));
+assert_checkalmostequal (unwrap2 (A, %pi), unwrap2 (A, %pi, 2));
+assert_checkalmostequal (unwrap2 (A', %pi), unwrap2 (A', %pi, 1));
+//test
+A = [%pi*(-4); %pi*(2+1/3); %pi*(16+1)];
+B = [%pi*(-2+1/6); %pi*(4+1/2); %pi*(32+3/2)];
+C = [%pi/4; %pi*(8+2/3); %pi*64];
+D = [%pi*(-2+1/6); %pi*(2+1/3); %pi*(8+2/3)];
+E(:, :, 1) = [A, B, C, D];
+E(:, :, 2) = [A+B, B+C, C+D, D+A];
+F(:, :, 1) = [unwrap2(A), unwrap2(B), unwrap2(C), unwrap2(D)];
+F(:, :, 2) = [unwrap2(A+B), unwrap2(B+C), unwrap2(C+D), unwrap2(D+A)];
+assert_checkalmostequal (unwrap2 (E), F);
+// Test trivial return for m = 1 and dim > nd
+assert_checkalmostequal (unwrap2 (ones(4,1), [], 1), ones(4,1))
+assert_checkalmostequal (unwrap2 (ones(4,1), [], 2), ones(4,1))
+assert_checkalmostequal (unwrap2 (ones(4,1), [], 3), ones(4,1))
+assert_checkalmostequal (unwrap2 (ones(4,3,2), [], 99), ones(4,3,2))
+// Test empty input return
+assert_checkalmostequal (unwrap2 ([]), [])
+assert_checkalmostequal (unwrap2 (ones (1,0)), ones (1,0))
+assert_checkalmostequal (unwrap2 (ones (1,0), [], 1), ones (1,0))
+assert_checkalmostequal (unwrap2 (ones (1,0), [], 2), ones (1,0))
+assert_checkalmostequal (unwrap2 (ones (1,0), [], 3), ones (1,0))
+// Test trivial return for m = 1 and dim > nd
+assert_checkalmostequal (unwrap2 (ones(4,1), [], 1), ones(4,1))
+assert_checkalmostequal (unwrap2 (ones(4,1), [], 2), ones(4,1))
+assert_checkalmostequal (unwrap2 (ones(4,1), [], 3), ones(4,1))
+assert_checkalmostequal (unwrap2 (ones(4,3,2), [], 99), ones(4,3,2))
+// Test empty input return
+assert_checkalmostequal (unwrap2 ([]), [])
+assert_checkalmostequal (unwrap2 (ones (1,0)), ones (1,0))
+assert_checkalmostequal (unwrap2 (ones (1,0), [], 1), ones (1,0))
+assert_checkalmostequal (unwrap2 (ones (1,0), [], 2), ones (1,0))
+assert_checkalmostequal (unwrap2 (ones (1,0), [], 3), ones (1,0))
+// Test handling of non-finite values
+x = %pi * [-%inf, 0.5, -1, %nan, %inf, -0.5, 1];
+assert_checkalmostequal (unwrap2 (x), %pi * [-%inf, 0.5, 1, %nan, %inf, 1.5, 1], %eps)
+assert_checkalmostequal (unwrap2 (x.'), %pi * [-%inf, 0.5, 1, %nan, %inf, 1.5, 1].', %eps)
+*/ \ No newline at end of file
diff --git a/macros/xcorr2.sci b/macros/xcorr2.sci
index 688dc3a..40d3b57 100644
--- a/macros/xcorr2.sci
+++ b/macros/xcorr2.sci
@@ -1,34 +1,70 @@
-function c = xcorr2 (a, b, biasflag)
-//
-//Calling Sequence
-//c = xcorr2 (a)
-//c = xcorr2 (a, b)
-//c = xcorr2 (a, b, biasflag)
-//Parameters
-//a:
-//b:
-//biasflag:
-//Description
-//This is an Octave function.
-
-//Examples
-//xcorr2(5,0.8,'coeff')
-//ans = 1
-
-funcprot(0);
-
-rhs = argn(2)
-if(rhs<1 | rhs>3)
-error("Wrong number of input arguments.");
-end
-
- select(rhs)
- case 1 then
- c = callOctave("xcorr2",a);
- case 2 then
- c = callOctave("xcorr2",a,b);
- case 3 then
- c = callOctave("xcorr2",a,b,biasflag);
- end;
+/*Calling Sequence
+ c = xcorr2 (a)
+ c = xcorr2 (a, b)
+ c = xcorr2 (a, b, scale)
+Description:
+ Compute the 2D cross-correlation of matrices a and b.
+ If b is not specified, computes autocorrelation of a, i.e., same as xcorr (a, a).
+ The optional argument scale, defines the type of scaling applied to the cross-correlation matrix. Possible values are:
+ "none" (default)
+ No scaling.
+ "biased"
+ Scales the raw cross-correlation by the maximum number of elements of a and b involved in the generation of any element of c.
+ "unbiased"
+ Scales the raw correlation by dividing each element in the cross-correlation matrix by the number of products a and b used to generate that element.
+ "coeff"
+ Scales the normalized cross-correlation on the range of [0 1] so that a value of 1 corresponds to a correlation coefficient of 1.
+ Examples
+ xcorr2(5,0.8,'coeff')
+ ans = 1 */
+function c = xcorr2 (a, b, scale)
+ funcprot(0);
+ nargin=argn(2);
+ if nargin < 3 then
+ scale = "none"
+ end
+ if (nargin < 1 || nargin > 3)
+ error("Wrong number of inputs")
+ elseif (nargin == 2 && type (b) == 10 )
+ scale = b;
+ b = a;
+ elseif (nargin == 1)
+ // we have to set this case here instead of the function line, because if
+ // someone calls the function with zero argument, since a is never set, we
+ // will fail with "`a' undefined" error rather that print_usage
+ b = a;
+ end
+ if (ndims (a) ~= 2 || ndims (b) ~= 2)
+ error ("xcorr2: input matrices must must have only 2 dimensions");
+ end
+ // compute correlation
+ [ma,na] = size(a);
+ [mb,nb] = size(b);
+ c = conv2 (a, conj (b (mb:-1:1, nb:-1:1)));
+ // bias routines by Dave Cogdell (cogdelld@asme.org)
+ // optimized by Paul Kienzle (pkienzle@users.sf.net)
+ // coeff routine by Carnë Draug (carandraug+dev@gmail.com)
+ switch (scale)
+ case {"none"}
+ // do nothing, it's all done
+ case {"biased"}
+ c = c / ( min ([ma, mb]) * min ([na, nb]) );
+ case {"unbiased"}
+ lo = min ([na,nb]);
+ hi = max ([na, nb]);
+ row = [ 1:(lo-1), lo*ones(1,hi-lo+1), (lo-1):-1:1 ];
+ lo = min ([ma,mb]);
+ hi = max ([ma, mb]);
+ col = [ 1:(lo-1), lo*ones(1,hi-lo+1), (lo-1):-1:1 ]';
+ bias = col*row;
+ c = c./bias;
+ case {"coeff"}
+ a = double (a);
+ b = double (b);
+ a = conv2 (a.^2, ones (size (b,1) , size( b ,2)));
+ b = sum(b(:).* conj(b(:)));
+ c(:,:) = c(:,:) ./ sqrt (a(:,:) * b);
+ else
+ error ("xcorr2: invalid type of scale %s", scale);
+ end
endfunction
-