text:
function demo_gpfa(seed)

if nargin >= 1
  randn('state', seed);
  rand('state', seed);
end

D = 4;

%
% Generate some data
%

%
% Generate X
%

covfunc_x = cell(D,1);

N_x = 300;
in_x = 1:N_x;

X = zeros(D,N_x);
D2_xx = sq_dist(in_x);
D_xx = sqrt(D2_xx);

pseudo_x = in_x(:,1:8:end);
D2_pp = sq_dist(pseudo_x);
D2_px = sq_dist(pseudo_x, in_x);
d2_x = diag(D2_xx);

is_pseudos_x = false(D,1);

% Trend component
covfunc = @(D2) gp_cov_se(D2);
covfunc_x{1} = gp_cov_pseudo(gp_cov_jitter(covfunc(D2_pp), 1e-3), ...
                             covfunc(D2_px), ...
                             covfunc(d2_x));
theta_x{1} = [100]; % true length scale
theta_init_x{1} = [50]; % init length scale
is_pseudos_x(1) = true;

% Almost periodic component (with fixed wave length)
covfunc = @(D2) gp_cov_product(gp_cov_periodic(sqrt(D2), ...
                                               'wavelength', 30), ...
                               gp_cov_se(D2));
covfunc_x{2} = gp_cov_pseudo(gp_cov_jitter(covfunc(D2_pp), 1e-3), ...
                             covfunc(D2_px), ...
                             covfunc(d2_x));
theta_x{2} = [1  % smoothness
              400]; % length scale of the decay
theta_init_x{2} = [0.5  % smoothness
                   800]; % length scale of the decay
is_pseudos_x(2) = true;

% Slow component
covfunc_x{3} = gp_cov_jitter(gp_cov_rq(D2_xx));
theta_x{3} = [5   % length scale
              1]; % alpha ("degrees of freedom")
theta_init_x{3} = [5     % length scale
                   1]; % alpha ("degrees of freedom")
is_pseudos_x(3) = false;

% Fast component
covfunc_x{4} = gp_cov_jitter(gp_cov_pp(D_xx, 1));
theta_x{4} = [4]; % length scale
theta_init_x{4} = [2.5]; % length scale
is_pseudos_x(4) = false;

% Generate X by random samples
for d=1:D
  if ~is_pseudos_x(d)
    K = covfunc_x{d}(theta_x{d});
    L = chol(K, 'lower');
    X(d,:) = L*randn(N_x,1);
  else
    [K_pp, K_px, k_x] = covfunc_x{d}(theta_x{d});
    L = chol(K_pp, 'lower');
    X(d,:) = K_px'*linsolve_lchol(L, L*randn(size(L,1),1));
  end
end

%
% Generate W
%

N_w = 30;
in_w = rand(2,N_w);

D2_ww = sq_dist(in_w);
W = zeros(D,N_w);

% Meshgrid for showing the spatial functions
[grid_w1,grid_w2] = meshgrid(0:0.03:1, 0:0.03:1);
grid_w = [grid_w1(:)'; grid_w2(:)'];
D2_grid = sq_dist([grid_w, in_w]);
N_grid = size(grid_w, 2);
W_grid = zeros(D,N_grid);

% RQ covariance function for all spatial components
covfunc_w = cell(D,1);
covfunc_grid = cell(D,1);
covfunc_w(:) = {gp_cov_scale(gp_cov_jitter(gp_cov_rq(D2_ww)))};
covfunc_grid(:) = {gp_cov_scale(gp_cov_jitter(gp_cov_rq(D2_grid)))};
% True parameter values
theta_w{1} = [2     % signal magnitude
              0.4   % length scale
              3.0]; % alpha ("degrees of freedom")
theta_w{2} = [1     % signal magnitude
              0.2  % length scale
              2.0]; % alpha ("degrees of freedom")
theta_w{3} = [1     % signal magnitude
              0.1  % length scale
              1.0]; % alpha ("degrees of freedom")
theta_w{4} = [0.5   % signal magnitude
              0.05  % length scale
              1.0]; % alpha ("degrees of freedom")
% Parameter value initializations
theta_init_w = cell(D,1);
theta_init_w(:) = columns_to_cells(...
    [ones(1,D)            % signal magnitude
     linspace(0.3,0.01,D) % length scale
     ones(1,D)]);         % alpha ("degrees of freedom")
% $$$ theta_init_w(:) = {[1    % signal magnitude
% $$$                     0.02 % length scale
% $$$                     1]}; % alpha ("degrees of freedom")

% Generate W by random samples
for d=1:D
  K = covfunc_grid{d}(theta_w{d});
  L = chol(K, 'lower');
  w = L*randn(length(L),1);
  W_grid(d,:) = w(1:N_grid);
  W(d,:) = w((N_grid+1):end);
end

%
% Generate Y
%

% Noisy observations
Y_noiseless = W'*X;
s = 1;
Y = Y_noiseless + s*randn(N_w,N_x);

% Missing values
Y(rand(size(Y))<0.0) = nan;

%
% Plot
%

% True spatial components
figure
for d=1:D
  subplot(ceil(sqrt(D)), ceil(sqrt(D)), d);
  % Plot contours of W
  cmax = max(abs(W_grid(d,:)));
  contourf(grid_w1, grid_w2, reshape(W_grid(d,:), size(grid_w1)));
  set(gca, 'clim', [-cmax, cmax])
  map_colormap();
  % Plot locations
  hold on
  plot(in_w(1,:), in_w(2,:), 'k+');
end

% True temporal components
tsplot(X);

%
% Inference with GPFA
%

% GP module with component-wise factorization for X
%theta_init_x = theta_x; % initialize with true parameter values
X_module = factor_module_gp_factorized(N_x, covfunc_x, theta_init_x, ...
                                       'update_hyperparameters', [5 10:10:100], ...
                                       'maxiter_hyperparameters', 10, ...
                                       'is_pseudo', is_pseudos_x, ...
                                       'init', zeros(D,N_x));

% GP module with component-wise factorization for W
%theta_init_w = theta_w; % initialize with true parameter values
W_module = factor_module_gp_factorized(N_w, covfunc_w, theta_init_w, ...
                                       'update_hyperparameters', [5 10:10:100], ...
                                       'maxiter_hyperparameters', 10);

% Isotropic noise
noise_module = noise_module_isotropic(N_w, N_x, ...
                                      'prior', struct('a_tau', 1e-3, ...
				                      'b_tau', 1e-3), ...
                                      'init', struct('a_tau', 10, ...
				                     'b_tau', 1));

% Run GPFA
Q = gpfa(D, Y, W_module, X_module, noise_module, ...
         'maxiter', 50, ...
         'debug', false, ...
...%         'rotate', 1:10, ...
         'rotate', 1:15, ...
         'rotation_checkgrad', false, ...
         'rotation_show', false, ...
         'rotation_maxiter', 30);
% 'predict', true

fprintf('RMSE of the noiseless reconstruction: %f\n',  rmse(Y_noiseless, Q.W'*Q.X));
fprintf('STD of the noiseless predictions: %f\n', ...
        sqrt(mean(mean(Q.W.^2'*Q.CovX + Q.CovW'*Q.X.^2 + Q.CovW'*Q.CovX))));
fprintf('Estimated noise STD: %f\n', Q.Tau(1).^(-0.5))

% The development of the loglikelihood lower bound during the iteration
figure
plot(Q.loglikelihood)

% Estimated latent temporal signals
figure
for d=1:D
  subplot(D,1,d);
  errorplot(Q.X(d,:), 2*sqrt(Q.CovX(d,:)))
end

return

% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$
% $$$ % $$$ tsplot(X)
% $$$ % $$$ tsplot(W)
% $$$ % $$$ tsplot(Y, 'k+')
% $$$ % $$$ return
% $$$
% $$$ % $$$ regularize = @(covfunc,N) gp_cov_sum(covfunc, ...
% $$$ % $$$                                      gp_cov_scale(gp_cov_delta(N), ...
% $$$ % $$$                                                   'scale', 1e-6));
% $$$
% $$$ %
% $$$ % GP module for X
% $$$ %
% $$$
% $$$ N_p = 2;
% $$$ pseudo_x = linspace(min(in_x),max(in_x), N_p);
% $$$ is_pseudo_x = false(D,1);
% $$$
% $$$ D2_xx = sq_dist(in_x);
% $$$ D2_pp = sq_dist(pseudo_x);
% $$$ D2_xp = sq_dist(in_x, pseudo_x);
% $$$
% $$$ % Covariance functions
% $$$ covfunc = @(D2) gp_cov_se(D2);
% $$$ covfunc_x = cell(D,1);
% $$$ covfunc_x{1} = gp_cov_jitter(gp_cov_se(D2_xx));
% $$$ % $$$ covfunc_x{1} = gp_cov_pseudo(gp_cov_jitter(gp_cov_se(D2_pp)), ...
% $$$ % $$$                              gp_cov_se(D2_xp), ...
% $$$ % $$$                              gp_cov_se(diag(D2_xx)));
% $$$ % $$$ is_pseudo_x(1) = true
% $$$ theta_x{1} = 30;
% $$$
% $$$ covfunc_x{2} = gp_cov_jitter(covfunc(D2_xx));
% $$$ theta_x{2} = 3;
% $$$ covfunc_x{3} = gp_cov_jitter(gp_cov_pp(sqrt(D2_xx),1));
% $$$ theta_x{3} = 1;
% $$$
% $$$ % $$$ figure
% $$$ % $$$ imagesc(covfunc_x{1}(theta_x{1}));
% $$$ % $$$ figure
% $$$ % $$$ imagesc(covfunc_x{2}(theta_x{2}));
% $$$ % $$$ return
% $$$
% $$$ % GP module with component-wise factorization
% $$$ X_module = factor_module_gp_factorized(N_x, ...
% $$$                                        covfunc_x, ...
% $$$                                        theta_x, ...
% $$$                                        'is_pseudo', is_pseudo_x, ...
% $$$                                        'update_hyperparameters', 2);
% $$$
% $$$ %
% $$$ % GP module for W
% $$$ %
% $$$
% $$$ D2_ww = sq_dist(in_w);
% $$$
% $$$ % Covariance functions
% $$$ covfunc_w = cell(D,1);
% $$$ covfunc_w{1} = gp_cov_scale(gp_cov_jitter(gp_cov_se(D2_ww)));
% $$$ theta_w{1} = [1; 4];
% $$$ covfunc_w{2} = gp_cov_scale(gp_cov_jitter(gp_cov_se(D2_ww)));
% $$$ theta_w{2} = [1; 3];
% $$$ covfunc_w{3} = gp_cov_scale(gp_cov_jitter(gp_cov_pp(sqrt(D2_ww),1)));
% $$$ theta_w{3} = [1; 2];
% $$$
% $$$ % GP module with component-wise factorization
% $$$ W_module = factor_module_gp_factorized(N_w, covfunc_w, theta_w, ...
% $$$                                        'update_hyperparameters', 2);
% $$$
% $$$ %
% $$$ % Isotropic noise module
% $$$ %
% $$$
% $$$ %noise_module = noise_module_fixed(1/s^2 * ones(N_w, N_x));
% $$$ noise_module = noise_module_isotropic(N_w, N_x, 1e-3, 1e-3, 'init', 100);
% $$$
% $$$ %
% $$$ % VB inference
% $$$ %
% $$$
% $$$ %
% $$$ % TODO:
% $$$ %
% $$$ % - pseudo inputs
% $$$ %
% $$$ % - put the noise to Q(W)
% $$$ %
% $$$ % - test more components
% $$$ %
% $$$ % - rotation, learn the hyperparameters jointly?
% $$$ %
% $$$ % - weighted noise
% $$$ %
% $$$
% $$$ Q = gpfa(D, Y, W_module, X_module, noise_module, ...
% $$$          'maxiter', 30, ...
% $$$          'update_noise', 2, ...
% $$$          'rotate', false);
% $$$
% $$$ noise_std = Q.Tau(1)^(-0.5)
% $$$
% $$$ tsplot(Q.X)
% $$$ tsplot(Q.W)
% $$$ %tsplot(Y, 'k+')
% $$$
% $$$ figure
% $$$ plot(Q.loglikelihood)
% $$$
% $$$ recon_error = rmse(Y_noiseless, Q.W'*Q.X)


text:
classdef ParadigmBaseSimplified < ParadigmBase
    % Simplified base class for BCI paradigms.
    %
    % Derive from this class if in your paradigm, calibration is done based on a single data set
    % (i.e. neither dataset collections nor stream bundles are handled meaningfully by it).
    % * you supply a calibrate_simple() function that takes a single recording and derives a model
    %   from it (optionally specifying a filter chain for efficient pre-processing)
    % * you supply a predict_simple() function that takes a single data set and calculates outputs
    %   from it
    % * (optionally, you may specify a visualization function)
    %
    %
    % If your paradigm can be understood as a dataflow model (i.e. a sequence of signal processing,
    % feature extraction, and machine learning), consider deriving from a simpler dataflow base class
    % instead (ParadigmDataflowSimplified).
    %
    % Notes:
    %   Most BCI paradigms (e.g., almost all from before 2008) do not support the full generality of
    %   possible inputs that are allowed by ParadigmBase (the general definition and implementation
    %   contract of a BCI paradigm, see ParadigmBase.m). Instead, firstly, most traditional BCI
    %   paradigms operate during online processing only on a single (multi-channel) signal instead
    %   of multiple concurrent signals, and secondly, most paradigms are initially calibrated based
    %   on a single calibration recording (usually a 30-60 minute recording of calibration data)
    %   instead of a (possibly tagged) collection of multiple data sets. For any such paradigm, the
    %   additional flexibility is useless and the corresponding organizational structure is an
    %   unnecessary implementation burden.
    %
    %   This base class is a refinement of ParadigmBase which omits the additional flexibility and
    %   provides an interface for simple paradigms. Any such paradigm should implement the
    %   calibrate_simple() method and the predict_simple() method, which are the simplified
    %   equivalents the calibrate() and predict() functions in ParadigmBase (without multiple
    %   concurrent streams and without multiple calibration data sets).
    %
    %   There exists a further specialization of this base class, ParadigmDataflowSimplified, which
    %   provides an additional layer of convenience for BCI paradigms that adhere to a standard
    %   "dataflow" (multi-stage) structure. If a paradigm can be expressed as a sequence of signal
    %   processing, feature extraction and machine learning, it is recommended to derive from this
    %   more specialized class instead (see ParadigmDataflowSimplified.m).
    %
    % Name:
    %   Simplified Base Paradigm (abstract)
    %
    %                            Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
    %                            2011-08-28

    methods

        function model = calibrate_simple(self,varargin)
            % Override this function to implement your model calibration code
            % Model = calibrate_simple(Signal,Arguments...)
            %
            % This function defines how a BCI is calibrated (i.e. adapted) to an individual based on
            % a given calibration recording. The calibration recording is a single EEGLAB data set
            % (though may contain arbitrary signal contents) annotated with target markers that
            % contain information about the desired BCI output at various time points in the
            % recording. Based on these markers and the data a relationship between signal contents
            % and the value of some (assumed) 'cognitive state variable' (to be approximated by the
            % BCI's outputs) is inferred by this function and captured in the predictive model
            % returned by it (a struct with any parameters necessary for predict_simple).
            %
            % Implementations of this function should declare at least a parameter named "Signal",
            % plus any desired custom user options. These parameters should be declared using the
            % arg_define() facility to allow the framework to query the parameter names and defaults
            % (e.g. for GUI display). The returned model also describes any signal (pre-)processing that
            % shall be performed by BCILAB before the predict_simple() function is called by it,
            % by means of its .filter_graph field.
            %
            % In:
            %   Signal : a single continuous EEGLAB data set (annotated with target markers; see
            %            set_targetmarkers for more info)
            %
            %   Arguments : further optional user arguments
            %
            % Out:
            %   Model : a model struct with a mandatory field .filter_graph and arbitrary other content
            %           * The .filter_graph filed is a 1x1 cell array that contains the desciption of
            %             filter steps that is to be applied to the data, and is usually passed as either
            %             the .tracking.online_expression field of the processed Signal or the processed
            %             Signal itself. If no signal processing is performed by this paradigm, the raw
            %             signal may be passed.
            %
            %           * May have optional fields .prediction_function, .prediction_window and
            %             .prediction_channels - though these are generally auto-deduced
            %
            %           The rest of the model struct is arbitrary and should contain whatever
            %           parameters are needed by predict_simple() to perform its operation.
            %
            % Notes:
            %   Overridden functions should declare their arguments using arg_define().

            error('This paradigm implements no calibrate_simple() function.');
        end

        function outputs = predict_simple(self,signal,model)
            % Override this function to implement your prediction code
            % Outputs = predict_simple(Signal,Model)
            %
            % This function defines how this BCI paradigm responds to "prediction" queries, i.e.
            % how, for a given piece of signal, an estimate of (or inference about) the user's
            % cognitive state shall be computed. It receives a segment of a pre-processed signal, as
            % well as a predictive model and shall produce an estimate about the most recent sample
            % in the given signal (although it may utilize any previous samples in its computation).
            % The signal is implicitly pre-processed before the function is called as defined by the
            % .filter_graph field of the predictive model (set by the calibrate_simple) function.
            %
            % The signal may also be "epoched", i.e. contain multiple segments, in which case the
            % output of this function shall be an array of predictions (one for each segment).
            %
            % In:
            %   Signal : a signal pre-processed according to the model's filter graph
            %
            %   Model : a predictive model as created by your calibrate_simple() function
            %
            % Out:
            %   Outputs : a prediction/estimate for the most recent time point in the data (or one for
            %             every epoch if the signal is epoched); see ml_predict for the allowed formats

            error('This paradigm implements no predict_simple() function.');
        end

        function visualize(self,model,varargin)
            % Optionally override this function to implement your visualization code
            % visualize(Model)
            %
            % In:
            %   Model: a model as created by your calibrate() function;
            %          a plot or GUI will be produced to inspect the model
            %
            %   Options : cell array or struct of name-value pairs

            error('This paradigm implements no visualize() function.');
        end

        % --- implementation ----

        function model = calibrate(self,varargin)
            % Implementation of the calibrate() function (see ParadigmBase)
            % Model = calibrate(Collection,GoalIdentifier,Arguments...)
            %
            % This is essentially a wrapper around calibrate_simple() which peels off any unused
            % organizational ballast (for multiple collections and stream bundles) before passing it
            % on. If multiple data sets are passed, they are implicitly merged.
            %
            % In:
            %   Collection : a collection (cell array) of stream bundles
            %
            %   GoalIdentifier: the goal-identifier
            %
            %   Arguments... : further optional user arguments
            %
            % Out:
            %   Model : The returned model struct
            dp;

            % separate the collection argument from the rest
            collection = arg_extract(varargin,{'collection','Collection'},[],{});
            remove = find(strcmpi(varargin(1:2:end),'collection'))-1;
            retain = setdiff(1:length(varargin),[1 + 2*remove,2 + 2*remove]);
            varargin = varargin(retain);
            % also remove the goal identifier argument
            remove = find(strcmpi(varargin,'goal_identifier'));
            varargin([remove remove+1]) = [];
            % and extract the signal argument
            if ~isempty(collection)
                % check if any of the data sets in the collection has more than one stream
                if any(cellfun(@(x)length(x.streams) > 1,collection))
                    error('This paradigm does not support more than one stream in parallel.'); end
                if length(collection) == 1
                    signal = collection{1}.streams{1};
                else
                    % merge all data sets in the collection
                    tmp = cellfun(@(x)x.streams{1},collection,'UniformOutput',false);
                    signal = set_concat(tmp{:});
                end
            else
                signal = {};
            end

            % call calibrate_simple with the signal passed in as additional argument
            model = self.calibrate_simple('signal',signal,varargin{:});
        end

        function outputs = predict(self,bundle,model)
            % Override this function to implement your prediction code
            % Outputs = predict(Bundle,Model)
            %
            % This is a wrapper around the predict_simple() function which peels off the stream bundle
            % representation and just passes on the contained signal.
            %
            % In:
            %   Bundle : stream bundle preprocessed by the model's filter graph
            %
            %   Model : a predictive model
            %
            % Out:
            %   Outputs : the outputs of calibrate_simple()
            dp;

            if length(bundle.streams) > 1
                error('This paradigm does not support more than one stream in parallel.'); end
            outputs = self.predict_simple(bundle.streams{1},model);
        end

    end
end

% (turn off a few editor warnings because some actual implementations are missing in this file)
%#ok<*INUSD,*STOUT,*MANU>

repo: REST


text:
% Script to extract gray matter from pial and smoothwm surfaces
% Uses mri_surfacemask routine. Only runs on RH / i386 I think

fs_dir='/raid/MRI/toolbox/MGH/freesurfer/bin/Linux';
fsl_dir='/raid/MRI/toolbox/FSL/fsl/bin/';

hemi='rh';
subjid='norcia_fs_WB';

% Run mri_surfacemask on both the rh.smoothwm and rh.pial
fileBase=['/raid/MRI/anatomy/FREESURFER_SUBS/',subjid];
fileNameToProcess=[fileBase,'/surf/',hemi,'.pial'];
anatomyToUse=[fileBase,'/mri/T1/'];
outFileName=[fileBase,'/mri/',hemi,'_pial'];
fs_command=['echo ',fs_dir,'/mri_surfacemask ',anatomyToUse,' ',fileNameToProcess,' ',outFileName,'.img | csh'];
disp(fs_command);
tic

system(fs_command);
toc
% Load in the pial image
[pialIm,dims,scalesmbpp,endian]=read_avw([outFileName]);

fileNameToProcess=[fileBase,'/surf/',hemi   ,'.smoothwm'];
outFileName=[fileBase,'/mri/',hemi,'_smoothwm'];
fs_command=['echo ',fs_dir,'/mri_surfacemask ',anatomyToUse,' ',fileNameToProcess,' ',outFileName,'.img | csh'];
disp(fs_command);
tic
dos(fs_command);
toc

% Load in the smoothwm image
[wmIm,dims,scalesmbpp,endian]=read_avw(outFileName);

% Binarize and 'and' them
wmIm(wmIm>0)=1;

pialIm(pialIm>0)=1;
grayIm=pialIm-wmIm;
grayIm(grayIm~=1)=0;
grayIm(grayIm~=0)=255;

outFileName=[fileBase,'/mri/',hemi,'_grayMask'];
grayIm=permute(grayIm,[1 3 2]);

save_avw((grayIm),outFileName,'b',scalesmbpp);

% Resulting analyze files can be imported to EMSE and a region defined on
% them using the thresholding / growing routines.
% The dimensions are ordered correctly but must be flipped front/back,
% top/bottom AND left/right!

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function softmaxA = softmax_dim(A,dim)
% apply the softmax function to a matrxi in certain dimension
% -----------------------------------------------------------

if nargin < 2, error('The dimension along which to do the softmax must be provided.'); end

s = ones(1, ndims(A));
s(dim) = size(A, dim);

% First get the maximum of A.
maxA = max(A, [], dim);
expA = exp(A-repmat(maxA, s));
softmaxA = expA ./ repmat(sum(expA,dim), s);

author: cihangxie

repo: DAG

save_path: github-repos/MATLAB/cihangxie-DAG


text:
function f = erfz(zz)
%ERFZ  Error function for complex inputs
%   f = erfz(z) is the error function for the elements of z.
%   Z may be complex and of any size.
%   Accuracy is better than 12 significant digits.
%
%   Usage:  f = erfz(z)
%
%   Ref: Abramowitz & Stegun section 7.1
%   equations 7.1.9, 7.1.23, and 7.1.29
%
%   Tested under version 5.3.1
%
%   See also erf, erfc, erfcx, erfinc, erfcore

%   Main author Paul Godfrey <pgodfrey@intersil.com>
%   Small changes by Peter J. Acklam <jacklam@math.uio.no>
%   09-26-01

   error(nargchk(1, 1, nargin));

   % quick exit for empty input
   if isempty(zz)
      f = zz;
      return;
   end

   twopi = 2*pi;
   sqrtpi=1.772453850905516027298;

   f = zeros(size(zz));
   ff=f;

   az=abs(zz);
   p1=find(az<=8);
   p2=find(az> 8);

if ~isempty(p1)
   z=zz(p1);

   nn = 32;

   x = real(z);
   y = imag(z);
   k1 = 2 / pi * exp(-x.*x);
   k2 = exp(-i*2*x.*y);

   s1 = erf(x);

   s2 = zeros(size(x));
   k = x ~= 0;          % when x is non-zero
   s2(k) = k1(k) ./ (4*x(k)) .* (1 - k2(k));
   k = ~k;              % when x is zero
   s2(k) = i / pi * y(k);

   f = s1 + s2;

   k = y ~= 0;          % when y is non-zero
   xk = x(k);
   yk = y(k);

   s5 = 0;
   for n = 1 : nn
      s3 = exp(-n*n/4) ./ (n*n + 4*xk.*xk);
      s4 = 2*xk - k2(k).*(2*xk.*cosh(n*yk) - i*n*sinh(n*yk));
      s5 = s5 + s3.*s4;
   end
   s6 = k1(k) .* s5;
   f(k) = f(k) + s6;
   ff(p1)=f;
end

if ~isempty(p2)
   z=zz(p2);
   pn=find(real(z)<0);

   if ~isempty(pn)
      z(pn)=-z(pn);
   end

   nmax=193;
   s=1;
   y=2*z.*z;
   for n=nmax:-2:1
       s=1-n.*(s./y);
   end

   f=1.0-s.*exp(-z.*z)./(sqrtpi*z);

   if ~isempty(pn)
      f(pn)=-f(pn);
   end

   pa=find(real(z)==0);
%  fix along i axis problem
   if ~isempty(pa)
      f(pa)=f(pa)-1;
   end

   ff(p2)=f;
end

f=ff;

return

   %a demo of this function is
   x = -4:0.125:4;
   y = x;
   [X, Y] = meshgrid(x,y);
   z = complex(X, Y);
   f = erfz(z);
   af = abs(f);
   %let's truncate for visibility
   p = find(af > 5);
   af(p) = 5;
   mesh(x, y, af);
   view(-70, 40);
   rotate3d on;

   return

author: Sable

repo: mcbench-benchmarks


text:
function [e,C,v] = collect(e,c,v)
%TOUNIVARIATE Transformation to univariate polynomial
%
%On input,
% e   m x 1 array of exponents, possibly with rows occuring several times
% c   m x 1 array of corresponding (polynomial) coefficients (sparse)
% v   string or 1-item cell array of string
%
%On output, polynomial data is transformed to univariate format
%

% written  07/21/02     S.M. Rump
%

n = max(e);           % degree of polynomial
C = zeros(1,n+1);
if isa(c,'intval')
  C = intval(C);
end
C(n+1-e) = c;
e = n;
if iscell(v)
  v = v{1};
end

repo: OpenMAS


text:
function f = p01_f ( n, x )

%*****************************************************************************80
%
%% P01_F returns the integrand for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of variables.
%
%    Input, real X(N), the arguments.
%
%    Output, real F(N), the values of the integrand.
%
  f = 1.1 * ones ( n, 1 );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function cdf = beta_binomial_cdf ( x, a, b, c )

%*****************************************************************************80
%
%% BETA_BINOMIAL_CDF evaluates the Beta Binomial CDF.
%
%  Discussion:
%
%    A simple summing approach is used.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 October 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer X, the argument of the CDF.
%
%    Input, real A, B, parameters of the PDF.
%    0.0D+00 < A,
%    0.0D+00 < B.
%
%    Input, integer C, a parameter of the PDF.
%    0 <= C.
%
%    Output, real CDF, the value of the CDF.
%
  if ( x < 0 )

    cdf = 0.0;

  elseif ( x < c )

    cdf = 0.0;
    for y = 0 : x
      pdf = beta ( a + y, b + c - y ) / ( ( c + 1 ) ...
        * beta ( y + 1,  c - y + 1 ) * beta ( a, b ) );
      cdf = cdf + pdf;
    end

  elseif ( c <= x )

    cdf = 1.0;

  end

  return
end


text:
function Cij = triplet_conditionalgranger(H3,Z3,cmbindx3,H2,Z2,cmbindx2,cmbindx)

% TRIPLET_CONDITIONALGRANGER
%
% Inputs:
%   H3,Z3: transfer matrix, noise covariance for
%     triplets, 3x3(xtriplet)xnfreq
%   H2,Z2: transfer matrix, noise covariance for
%     duplets,  2x2(xnduplet)xnfreq
%   cmbindx: Nx3 indices determining the output, abc = b->a/c

% Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% the ordering for the triplet indices w.r.t. the duplet indices is crucial
% for the interpretation:
%
% abc - ab gives b->a, conditioned on c. If you want a->b, conditioned on
% c, one should also do a bac - ba computation
%
% Here, the cmbindx are taken, and the appropriately ordered corresponding
% cmbindx2 are generated, if necessary, by swapping the order

if nargin<7 || isempty(cmbindx)
    cmbindx = cmbindx3;
end

% FIXME ensure that the number of frequency bins matches

nfreq = size(H3,4);
Cij = zeros(size(cmbindx,1), nfreq);
for k = 1:size(cmbindx,1)
  % triplet
  sel3     = find(all(ismember(cmbindx3, cmbindx(k,:)),2));
  tmp      = cmbindx3(sel3,:);
  reorder3 = [find(tmp==cmbindx(k,1)) find(tmp==cmbindx(k,2)) find(tmp==cmbindx(k,3))];

  h123 = reshape(H3(reorder3, reorder3, sel3, :), [3 3 nfreq]);
  z123 = Z3(reorder3, reorder3, sel3);

  % normalization matrix 2->1/3
  tmp1 = -z123(2,1)/z123(1,1);
  tmp2 = -z123(3,1)/z123(1,1);
  tmp3 = -(z123(3,2)+tmp2*z123(1,2))/(z123(2,2)+tmp1*z123(1,2));

  p1  = [1    0 0;
         tmp1 1 0;
         tmp2 0 1];
  p2  = [1 0    0;
         0 1    0;
         0 tmp3 1];

  P    = p2*p1;
  invP = inv(P);

  %bivariate system
  sel2     = find(all(ismember(cmbindx2, cmbindx(k,[1 3])),2));
  tmp      = cmbindx2(sel2,:);
  reorder2 = [find(tmp==cmbindx(k,1)) find(tmp==cmbindx(k,3))];

  h2 = reshape(H2(reorder2, reorder2, sel2, :), [2 2 nfreq]);
  z2 = Z2(reorder2, reorder2, sel2);

  Q  = [1                 0;
        -z2(1,2)/z2(1,1) 1];
  numer = z2(1,1);

  invh2   = inv2x2(h2);

  HH   = mtimes3x3(h123, invP(:,:,ones(size(h123,3),1)));
  B    = mtimes2x2(Q(:,:,ones(size(invh2,3),1)), invh2);
  FF   = shiftdim(B(1,1,:).*HH(1,1,:)+B(1,2,:).*HH(3,1,:),1);
  denom = abs(FF.*conj(FF)).*z123(1,1);
  Cij(k,:) = log(numer./denom);

%   % it seems only FF(1,1) is needed (as per the commented for-loop
%   for kk = 1:size(h2,3)
%     HH = h123(:,:,kk)/P;
%     B  = Q/h2(:,:,kk);
%     FF = B(1,:)*HH([1 3],1);
%     denom = abs(FF(1,1)*z123(1,1)*conj(FF(1,1)));
%
%     Cij(k,kk) = log(numer./denom);
%
%   end
%

%   for kk = 1:size(h2,3)
%     HH = h123(:,:,kk)/P;
%     Q  = [1                 0;
%           -z2(1,2)/z2(1,1) 1];
%     B  = Q/h2(:,:,kk);
%     BB = [B(1,1) 0 B(1,2);
%           0      1 0;
%           B(2,1) 0 B(2,2)];
%     FF = BB*HH;
%     numer = z2(1,1);
%     denom = abs(FF(1,1)*z123(1,1)*conj(FF(1,1)));
%
%     Cij(k,kk) = log(numer./denom);
%   end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [ drecksMDH, iLCPositions ] = fMeas_mainLUTDrecks( sFilename )
%FMEAS_MAIN main function for extracting Data, Loop counters, evalInfoMask
% and drecksMDH
%
% (c) Christian Wuerslin, Thomas Kuestner
% ---------------------------------------------------------------------

% input read parameter
% Set, Seg, Smp
% measReadPara = {[0 inf], [0 inf], [21 inf]}; % for CS_Trufi and CS_Flash, CS_Flash_Retro, CS_EPI

[sPath, sName, sExt] = fileparts(sFilename);

if(~exist(fullfile(sPath,[sName,'.mat']),'file'))
    fprintf('Creating look-up table for measdata file\n');
    fMeasCreateLUT_main(sFilename);
end

% load data
matfile = whos('-file', fullfile(sPath,[sName,'.mat']));
if(ismember('iLCDrecks', {matfile.name}) && ismember('iLCPositions', {matfile.name}))
    % drecksMDH 1.0
%     [dData, iLC, iEvalInfoMask] = fMeasRead(fullfile(sPath,[sName,sExt]), 'Set', measReadPara{1}, 'Seg', measReadPara{2}, 'Smp', measReadPara{3});
    [drecksMDH, iLCPositions] = fMeasReadDrecksMDH(fullfile(sPath,[sName,sExt]));

elseif(ismember('SDrecksMDH', {matfile.name}))
    % drecksMDH 2.0
%     [dData, iLC, iEvalInfoMask] = fMeasRead(fullfile(sPath,[sName,sExt]), 'Set', measReadPara{1}, 'Seg', measReadPara{2}, 'Smp', measReadPara{3});
    load(fullfile(sPath,[sName,'.mat']), 'SDrecksMDH');
    drecksMDH = SDrecksMDH;
    iLCPositions = [];
else
    % no drecksMDH at all
%     [dData, iLC, iEvalInfoMask] = fMeasRead(fullfile(sPath,[sName,sExt]), 'Set', measReadPara{1}, 'Seg', measReadPara{2}, 'Smp', measReadPara{3});
    drecksMDH = [];
    iLCPositions = [];
end

end

author: thomaskuestner


text:
function A = metric_04 ( p )

%*****************************************************************************80
%
%% METRIC_04 evaluates metric #4 at any point.
%
%  Discussion:
%
%    This routine evaluates the matrix that determines the metric
%    at a point.
%
%    This particular matrix reduces distances when evaluated far from the origin.
%
%    It is diagonal, and it is spatially varying.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 May 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real P(2), the point at which the metric matrix is to
%    be evaluated.
%
%    Output, real A[2,2], the metric matrix.
%
  A = [ 1.0, 0.0; 0.0, 1.0 ] * ...
      ( 0.20 + ( sin ( 2 * pi * p(1) ) )^2 * ( sin ( 2 * pi * p(2) ) )^2 );

  return
end


text:
function varargout = ProgramPerhitunganSel(varargin)
% PROGRAMPERHITUNGANSEL M-file for ProgramPerhitunganSel.fig
%      PROGRAMPERHITUNGANSEL, by itself, creates a new PROGRAMPERHITUNGANSEL or raises the existing
%      singleton*.
%
%      H = PROGRAMPERHITUNGANSEL returns the handle to a new PROGRAMPERHITUNGANSEL or the handle to
%      the existing singleton*.
%
%      PROGRAMPERHITUNGANSEL('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PROGRAMPERHITUNGANSEL.M with the given input arguments.
%
%      PROGRAMPERHITUNGANSEL('Property','Value',...) creates a new PROGRAMPERHITUNGANSEL or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ProgramPerhitunganSel_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ProgramPerhitunganSel_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help ProgramPerhitunganSel

% Last Modified by GUIDE v2.5 06-Jul-2012 06:01:29

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @ProgramPerhitunganSel_OpeningFcn, ...
    'gui_OutputFcn',  @ProgramPerhitunganSel_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before ProgramPerhitunganSel is made visible.
function ProgramPerhitunganSel_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to ProgramPerhitunganSel (see VARARGIN)

% Choose default command line output for ProgramPerhitunganSel
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes ProgramPerhitunganSel wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = ProgramPerhitunganSel_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --------------------------------------------------------------------
function Program_Menu_Callback(hObject, eventdata, handles)
% hObject    handle to Program_Menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function Info_Menu_Callback(hObject, eventdata, handles)
% hObject    handle to Info_Menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function Program_Menu_Item_Callback(hObject, eventdata, handles)
% hObject    handle to Program_Menu_Item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guidata(infogram);

% --------------------------------------------------------------------
function Perancang_Menu_Item_Callback(hObject, eventdata, handles)
% hObject    handle to Perancang_Menu_Item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guidata(Biodata);

% --------------------------------------------------------------------
function Automatic_Menu_Item_Callback(hObject, eventdata, handles)
% hObject    handle to Automatic_Menu_Item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guidata(Otomatis);
close(ProgramPerhitunganSel);

% --------------------------------------------------------------------
function Step_by_step_Menu_Item_Callback(hObject, eventdata, handles)
% hObject    handle to Step_by_step_Menu_Item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guidata(HitungSeltotal);
close(ProgramPerhitunganSel);

% --------------------------------------------------------------------
function Exit_Menu_Item_Callback(hObject, eventdata, handles)
% hObject    handle to Exit_Menu_Item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close;

% --------------------------------------------------------------------
function Parasit_Menu_Item_Callback(hObject, eventdata, handles)
% hObject    handle to Parasit_Menu_Item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guidata(Parasit);

% --- Executes during object creation, after setting all properties.
function axes6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to axes6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes6
axes(hObject);
imshow('halutama.jpg');

% --------------------------------------------------------------------
function Malaria_Menu_Item_Callback(hObject, eventdata, handles)
% hObject    handle to Malaria_Menu_Item (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
guidata(Malaria);


text:
function wfa = nan2wfa(nan)
%
%EVENT_NAN2WFA: Convert events from NAN form to WFA form.
%      WFA - WaveForm Array form, events separated in nx1 waveform array
%          - (or) into 1xl cell array, each cell containing a nx1 waveform
%          - array of events from a separate station/channel.
%      NAN - NaN form, (1xl waveform) for l station/channels with events in
%            one time series w/ non-events = NaN.
%      SST - Start/Stop Times form, nx2 array of matlab start/stop times
%            (or) 1xl cell array, each cell containing nx2 start/stop
%            times from a separate station/channel.
%
%USAGE: events = nan2wfa(nan)
%
%INPUTS: nan - Waveform object of events (1x1) in NAN form
%
%OUTPUTS: wfa - Waveform object array of events (WFA form)
%
% See also NAN2SST, SSD2SST, SST2NAN, SST2SSD, SST2VAL, SST2WFA,
%          WFA2NAN, WFA2SST
%
% Author: Dane Ketner, Alaska Volcano Observatory
% $Date$
% $Revision$

for l = 1:numel(nan)
   dat = get(nan(l),'data');
   l_d = length(dat);
   wfa{l} = [];

   if isnan(dat(1))
      inevent = 0;
   elseif ~isnan(dat(1))
      indx1 = 1;
      inevent = 1;
   end

   for n = 2:l_d-1
      if (inevent == 0) && ~(isnan(dat(n)))
         indx1 = n;
         inevent = 1;
      elseif (inevent == 1) && (isnan(dat(n)))
         indx2 = n-1;
         wfa{l}=[wfa{l}; extract(nan(l),'INDEX',indx1,indx2)];
         inevent = 0;
      end
   end

   if ~isnan(dat(l_d)) && (inevent == 1)
      indx2 = l_d;
      wfa{l}=[wfa{l}; extract(nan(1),'INDEX',indx1,indx2)];
   end
end

if numel(wfa) == 1
   wfa = wfa{1};
end

author: geoscience-community-codes

repo: GISMO


text:
classdef BCEIBEA < ALGORITHM
% <multi/many> <real/integer/label/binary/permutation>
% Bi-criterion evolution based IBEA
% kappa --- 0.05 --- Fitness scaling factor

%------------------------------- Reference --------------------------------
% M. Li, S. Yang, and X. Liu, Pareto or non-Pareto: Bi-criterion evolution
% in multiobjective optimization, IEEE Transactions on Evolutionary
% Computation, 2016, 20(5): 645-665.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            kappa = Algorithm.ParameterSet(0.05);

            %% Generate random population
            NPC      = Problem.Initialization();
            [PC,nND] = PCSelection(NPC,Problem.N);

            %% Optimization
            while Algorithm.NotTerminated(PC)
                % PC evolving
                NewPC = Exploration(Problem,PC,NPC,nND,Problem.N);
                % NPC selection
                NPC = EnvironmentalSelection([NPC,NewPC],Problem.N,kappa);
                % NPC evolving
                MatingPool = TournamentSelection(2,Problem.N,-CalFitness(NPC.objs,kappa));
                NewNPC     = OperatorGA(Problem,NPC(MatingPool));
                NPC        = EnvironmentalSelection([NPC,NewNPC],Problem.N,kappa);
                % PC selection
                [PC,nND] = PCSelection([PC,NewNPC,NewPC],Problem.N);
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function lmcKernDisplay(kern, spacing)

% LMCKERNDISPLAY Display parameters of the LMC kernel.
% FORMAT
% DESC displays the parameters of the LMC kernel to the console.
% ARG kern : the kernel to display.
%
% FORMAT does the same as above, but indents the display according
% to the amount specified.
% ARG kern : the kernel to display.
% ARG spacing : how many spaces to indent the display of the kernel by.
%
% SEEALSO : modelDisplay, kernDisplay
%
% COPYRIGHT : Mauricio A. Alvarez , 2010

% KERN

fhandle = str2func([kern.basicKernelType 'KernDisplay']);
fhandle(kern, spacing);
if nargin > 1
  spacing = repmat(32, 1, spacing);
else
  spacing = [];
end
spacing = char(spacing);
if kern.nout>5
    fprintf(spacing)
    fprintf('For more than 5 outputs, the corregionalization matrix is not printed.\n');
else
    for i = 1:kern.nout
        for j = 1:kern.nout
            fprintf(spacing)
            fprintf('Corregionalization matrix entry (%d,%d) : %f\n', ...
                i,j, kern.B(i,j));
        end
    end
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function [ points_lat, points_long ] = gen_hyperbola( doa_meters, rx1_lat, rx1_long, rx2_lat, rx2_long, geo_ref_lat, geo_ref_long)
%gen_hyperbola: calculates the points of a hyperbola from receiver positions
%               and the doa in meters

    % convert to xy coordinates
    [rx1_x, rx1_y] = latlong2xy(rx1_lat, rx1_long, geo_ref_lat, geo_ref_long);
    [rx2_x, rx2_y] = latlong2xy(rx2_lat, rx2_long, geo_ref_lat, geo_ref_long);

    % mit Kosinussatz Dreieck berechnen
    rx_x_dist = rx2_x - rx1_x;
    rx_y_dist = rx2_y - rx1_y;

    dist_12 = abs (rx_x_dist+i*rx_y_dist);  % positions in complex plane
    angle_12 = angle (rx_x_dist+i*rx_y_dist); % -pi to +pi

    hyp_x = zeros(1,1);
    hyp_y = zeros(1,1);

    hyp_x_leg1 = zeros(1,1);
    hyp_y_leg1 = zeros(1,1);
    hyp_x_leg2 = zeros(1,1);
    hyp_y_leg2 = zeros(1,1);
    hyp_point_counter = 0;

    if abs(doa_meters/1000) > dist_12
        disp(['TODA delay (' num2str(doa_meters) ' meters) larger than RX distance (' num2str(1000*  dist_12) ' meters) -> no solution possible ']);
        doa_meters = sign(doa_meters) * 0.995 * dist_12 * 1000;
        disp(['ATTENTION: Correcting TODA delay to 0.995 * RX distance (maximum possible value) = ' num2str(0.995*doa_meters) '']);
    end

    if abs(doa_meters/1000) <= dist_12

        %for r_1 = (exp(0:0.05:4)-1) / 5
        for r_1 = 0:0.05:10
            r_2 = r_1 - doa_meters/1000;
            %disp(['r_1 = ' num2str(r_1) ', r_2 = ' num2str(r_2)]);

            if ((r_2 + r_1) > dist_12)  % checks if triangle can be created

				acos_argument = (r_2^2 - r_1^2 - dist_12^2) / (-2*r_1*dist_12);

				if (acos_argument >= -1) && (acos_argument <= +1) % checks if triangle can be created

					hyp_point_counter = hyp_point_counter + 1;

					hyp_angle = acos(acos_argument); % inner angle of triangle at RX1

					abs_angle1 = wrap2pi(angle_12 + hyp_angle);  % 1st solution: hyperbola leg 1
					hyp_x_leg1(hyp_point_counter) = rx1_x + r_1 * cos(abs_angle1);
					hyp_y_leg1(hyp_point_counter) = rx1_y + r_1 * sin(abs_angle1);

					abs_angle2 = wrap2pi(angle_12 - hyp_angle);  % 2nd solution: hyperbola leg 2
					hyp_x_leg2(hyp_point_counter) = rx1_x + r_1 * cos(abs_angle2);
					hyp_y_leg2(hyp_point_counter) = rx1_y + r_1 * sin(abs_angle2);
                else
                    %disp(['acos argument ' num2str(acos_argument)]);
				end
            end

        end
    else
        disp('TODA delay larger than RX distance -> no solution possible');
    end

    if (hyp_point_counter == 0)
        disp('Hyperbola could not be constructed');
    end

    hyp_x = [fliplr(hyp_x_leg1) hyp_x_leg2];
    hyp_y = [fliplr(hyp_y_leg1) hyp_y_leg2];
    hyp_points = 2* hyp_point_counter;

    points_lat = zeros(hyp_points,1);
    points_long = zeros(hyp_points,1);

    for ii=1:1:hyp_points
        [points_lat(ii), points_long(ii)] = xy2latlong(hyp_x(ii), hyp_y(ii), geo_ref_lat, geo_ref_long);
    end

    disp(['Hyperbola with totally ' num2str(hyp_points) ' points generated.']);
end

repo: tdoa-evaluation-rtlsdr


text:
%CALCHIST  Calculates a histogram of a set of arrays
%
%     H = cv.calcHist(images, ranges)
%     H = cv.calcHist(..., 'OptionName',optionValue, ...)
%
% ## Input
% * __images__ Source arrays. A numeric array, or cell array of numeric arrays
%   are accepted. They all should have the same class (`uint8`, `uint16`, or
%   `single`) and the same row/column size. Each of them can have an arbitrary
%   number of channels. Note that passing `{img1, img2, ...}` as input is
%   similar to using `cat(3, img1, img2, ...)`, i.e the function computes the
%   histogram from channels of input arrays.
% * __ranges__ Cell-array of length `N` (histogram dimensionality) of the
%   histogram bin boundaries in each dimension.
%   * When the histogram is uniform (`Uniform=true`), then for each dimension
%     `i` it is enough to specify the lower (inclusive) boundary
%     `L(1) = ranges{i}(1)` of the first histogram bin and the upper
%     (exclusive) boundary `U(n) = ranges{i}(end)` for the last histogram bin
%     `HistSize(i)`. That is, in case of a uniform histogram each of
%     `ranges{i}` is an array of 2 elements forming an interval `[L,U)` which
%     is automatically divided according to `HistSize(i)`.
%   * When the histogram is not uniform (`Uniform=false`), then each of
%     `ranges{i}` contains `HistSize(i)+1` elements, specifying the bin edges
%     of dimension `i`: `L(1), L(2), ..., L(n), U(n)` forming the half-open
%     intervals: `[L(1), U(1)), [L(2), U(2)), ..., [L(n-1), U(n-1)), [L(n), U(n))`
%     where `U(1)==L(2), U(2)==L(3), ..., U(n-1)==L(n)`, and `n` is the
%     histogram size of the current dimension (`n = HistSize(i)`). The array
%     elements, that are not between `L(1)` and `U(n)`, are not counted in the
%     histogram.
%
% ## Output
% * __H__ Output histogram, which is a dense or sparse N-dimensional array of
%   type `single` (`N` is the histogram dimensionality that must be positive
%   and not greater than 32 in the current OpenCV version). The size of the
%   output N-D array is `HistSize(1)-by-HistSize(2)-by-...-by-HistSize(N)`.
%
% ## Options
% * __Channels__ List of channels used to compute the histogram (as 0-based
%   indices). The number of channels must match the histogram dimensionality
%   `N`. The first array channels are numerated from `0` to
%   `size(images{1},3)-1`, the second array channels are counted from
%   `size(images{1},3)` to `size(images{1},3) + size(images{2},3)-1`, and so
%   on. By default, all channels from all images are used to compute the
%   histogram, i.e default is `0:sum(cellfun(@(im)size(im,3), images))-1` when
%   input `images` is a cell array, and `0:(size(images,3)-1)` when input
%   `images` is a numeric array.
% * __Mask__ Optional mask. If the matrix is not empty, it must be an 8-bit or
%   logical array of the same row/column size as `images{i}`. The non-zero
%   mask elements mark the array elements (pixels) counted in the histogram.
%   Not set by default.
% * __HistSize__ Array of histogram sizes in each dimension. Use together
%   with the `Uniform` flag. Default is `cellfun(@numel,ranges)-1`.
%   * When the histogram is uniform, the range specified in `ranges{i}` is
%     divided into `HistSize(i)` uniform bins. The interval is divided into
%     bins using equally-spaced boundaries defined as:
%     `ranges{i} = linspace(ranges{i}(1), ranges{i}(end), HistSize(i)+1)`.
%   * When the histogram is not uniform, `ranges{i}` is used as is for the
%     bin boundaries without considering `HistSize`.
% * __Uniform__ Logical flag indicating whether the histogram is uniform or
%   not (see above). default false.
% * __Hist__ Input histogram, used in accumulation mode. Either a dense or
%   sparse array, see `H`. If it is set, the output histogram is initialized
%   with it instead of being cleared in the beginning when it is allocated.
%   This feature enables you to compute a single histogram from several sets
%   of arrays, or to update the histogram in time. Not set by default.
% * __Sparse__ Logical flag indicating whether the output should be sparse.
%   default false (i.e output histogram is a dense array). Keep in mind that
%   MATLAB only supports 2D sparse matrices, so use you must use dense arrays
%   if the histogram has more than two dimensions.
%
% The function cv.calcHist calculates the histogram of one or more arrays. The
% elements of a tuple used to increment a histogram bin are taken from the
% corresponding input arrays at the same location.
%
% ## Example
% The sample below shows how to compute a 2D Hue-Saturation histogram for a
% color image:
%
%     hsv = cv.cvtColor(img, 'RGB2HSV');
%     edges = {linspace(0,180,30+1), linspace(0,256,32+1)};
%     H = cv.calcHist(hsv(:,:,1:2), edges);
%
% Here is another example showing the different options:
%
%     % read some image, and convert to HSV colorspace
%     imgRGB = imread(fullfile(mexopencv.root(),'test','img001.jpg'));
%     imgHSV = cv.cvtColor(imgRGB, 'RGB2HSV');
%
%     % quantize the hue to 30 levels, and the saturation to 32 levels
%     histSize = [30, 32];
%     hranges = linspace(0, 180, histSize(1)+1);  % hue varies from 0 to 179
%     sranges = linspace(0, 256, histSize(2)+1);  % sat varies from 0 to 255
%     ranges = {hranges, sranges};
%
%     % one way
%     H = cv.calcHist(imgHSV(:,:,[1 2]), ranges);
%
%     % another way
%     H = cv.calcHist(imgHSV, ranges, 'Channels',[1 2]-1, 'HistSize',histSize);
%
%     % or similarly
%     H = cv.calcHist({imgHSV(:,:,1), imgHSV(:,:,2)}, {[0,180], [0,256]}, ...
%         'HistSize',histSize, 'Uniform',true);
%
%     % show H-S histogram
%     imagesc(H, 'YData',[0 180], 'XData',[0 256])
%     axis image; colormap gray; colorbar
%     ylabel('Hue'); xlabel('Saturation'); title('Histogram')
%
% See also: cv.calcBackProject, cv.compareHist, cv.EMD, hist, histc,
%  histogram, histcounts, histcounts2, discretize, imhist, hist3
%

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function M = morans_I(grid,W,s)
% PURPOSE: calculate global Moran's I for an input grid (matrix) by calculating all
%          local Moran's I for a given moving windows size using a weight matrix.
% -------------------------------------------------------------------
% USAGE: M = moransI(grid, W, s);
% where: [grid] is the matrix to analyse
%        [W] is the normalized weight matrix of the size the local Moran's
%            I will be calculated for (uneven sized!)
%        [s] is an optional flag to use zscores of input values for
%        calculation. Set to 'true' if zscores of local grid should be
%        calculated. Leave blank if not desired or input values are already
%        standardized.
% -------------------------------------------------------------------------
% OUTPUTS:
%        [M] matrix of all local Moran's I
% -------------------------------------------------------------------
% NOTES: Weight matrix needs to be 'moving window' style, not contiguity
%        matrix: Moran's I is calculated and weighted for neighbours to center cell.
%        Matrix needs to be normalized (weights sum to 1) and center cell weight
%        will be set to 0 if not already. Uses localmoran.m
%        -> Use nanmean(M(:)) to get the average global Moran's I.
%
% See Anselin (1995, 'LISA.', Geogr. Analysis 27(2),p.93f) for details on
% standardized variables in calculation of local Moran's I.
%
% EXAMPLE:  M = moransI(rand(20,20),ones(5,5),'true')
%
% Felix Hebeler, Geography Dept.,de University Zurich, March 2006.

%% Check if standardising should be done
if exist('s','var')
    if strcmp(s,'true');
        grid=zscore(grid);
    elseif strcmp(s,'false')
        %do nothing
    else
        error('Invalid option for s: set [true] to calculated zscores to determine local Moran or leave blank if values are already standardized.');
    end
end
if (mod(size(W,1),2)| mod(size(W,2),2))~=1
   error('Weight matrix W needs to have uneven size (eg. 5x5)')
end
%% Do local Morans I calc of the grid.
M = NaN(size(grid,1),size(grid,2));
wsx=floor(size(W,1)/2);
wsy=floor(size(W,2)/2);
% Do local morans I calc for moving window ws
for row=1+wsy:1:size(grid,1)-wsy;
    for col=1+wsx:1:size(grid,2)-wsx;
        M(row,col) = get_moran(grid(row-wsx:row+wsx,col-wsy:col+wsy),W);
    end
end

%% calculate local Moran's I
function m=get_moran(raster,W)
ncols= size(raster,2);
nrows= size(raster,1);
zi = raster(ceil(nrows/2),ceil(ncols/2));%  value of center cell (note: no weight applied!)
if (isnan(zi));
    m=NaN;
    return;
end;
raster=raster.* W; % Weight values in window
raster(ceil(nrows/2),ceil(ncols/2))=0; %set center cell to zero to exclude zi from sum
zj = nansum(raster(:)); % sum of weighted values excluding zi
m = zi * zj; % calculate local Moran's I and return


text:
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni

%problem 9- autocorrelation of exp(-3t)u(t)

syms t r
x=exp(-3*t)*heaviside(t);
x1=x;
x_2=subs(x1,t,t-r);
x2=conj(x_2);
R=int(x1*x2,t,-inf,inf);
ezplot(R, [-8 8]);
legend('R_x(\tau)');
ylim([0  0.17]);


text:
classdef TestBOWKMeansTrainer
    %TestBOWKMeansTrainer

    methods (Static)
        function test_1
            K = 5;
            trainer = cv.BOWKMeansTrainer(K);
            desc = randn(50,4);
            centers = trainer.cluster(desc);
            validateattributes(centers, {'numeric'}, {'size',[K 4]});
        end

        function test_2
            K = 2;           % number of clusters
            trainer = cv.BOWKMeansTrainer(K);

            dim = 3;         % dimensionality
            N = zeros(1,5);  % number of samples added
            for i=1:numel(N)
                desc = [randn(50,dim)-1; randn(50,dim)+1];
                trainer.add(desc);
                N(i) = size(desc,1);
            end

            assert(trainer.descriptorsCount() == sum(N));

            descs = trainer.getDescriptors();
            validateattributes(descs, {'cell'}, {'vector', 'numel',numel(N)});
            cellfun(@(x,n) validateattributes(x, {'numeric'}, ...
                {'size',[n dim]}), descs, num2cell(N));

            centers = trainer.cluster();
            validateattributes(centers, {'numeric'}, {'size',[K dim]});

            trainer.clear();
            assert(trainer.descriptorsCount() == 0);
            assert(isempty(trainer.getDescriptors()));
        end
    end

end


text:
function [s] = gsp_jtv_filter_inverse(G, filter, filtertype,c, param)
%GSP_JTV_FILTER_INVERSE Inverse operator of a joint timve_vertex filterbank
%   Usage:  s = gsp_jtv_filter_inverse(G, filter, c);
%           s = gsp_jtv_filter_inverse(G, filter, c, param);
%
%   Input parameters:
%         G          : Time-vertex Graph structure.
%         filter     : Cell array of time-vertex filters.
%         filtertype : Filter domain (ts,js,ts-array,js-array)
%         c          : Transform coefficients
%         param      : Optional parameter
%   Output parameters:
%         signal     : sythesis signal
%

% Author: Francesco Grassi
% Testing: test_jtv_filter
% Date: September 2016

if nargin<5
    param = struct;
end

[dual_filter,filtertype] = gsp_jtv_design_can_dual(filter,filtertype);

s = gsp_jtv_filter_synthesis(G,dual_filter,filtertype,c,param);

end

repo: gspbox


text:
function [ax1 ax2] = popout(h, xmin, xmax, extraprops)
% POPOUT create popout plot
%   [ax1 ax2] = popout(h, xmin, xmax)
%      creates a popout plot (e.g. outset plot) from axis contained in the
%      figure specfied by handle h, from limits specified by xmin and xmax.
%
%   [ax1 ax2] = popout(h, xmin, xmax, props)
%      creates a popout plot (e.g. outset plot) from axis contained in the
%      figure specfied by handle h, from limits specified by xmin and xmax
%      with axes properties specified by the structure props (see example below).
%
%      popout plot inherits all graphics properties of the axis in figure h
%      (e.g. linewidth, labels).
%
%      However, extra axes properties (for each axis) may be specfied to override inherited
%      properties, such as:
%
%      props.axes1.position = [0.1 0.15 0.7 0.8];
%      props.axes2.position = [0.5 0.1 0.4 0.6];
%      props.axes2.fontsize = 20;
%
%      Any valid axis property (fontsize, xtick, yticklabel, etc...) may be
%      provided for each axis.
%
%
%   example:
%
%       x=0:0.1:100;
%       y = bessel(1,x);
%       plot(x,y);
%       popout(gcf, 10, 20);
%
%   more complex popout plot example (with axes properties):
%
%       x=0:0.1:100;
%       y1 = bessel(1,x);
%       y2 = bessel(1,x)*2;
%
%       plot(x,y1, x, y2, 'linewidth', 2); grid on;
%       xlabel('time'); ylabel('amplitude');
%       title('Bessel functions');
%       set(gca, 'fontsize', 12, 'linewidth', 2);
%       ylim([-10 2]);
%
%       props.axes1.position = [0.1 0.15 0.7 0.8];
%       props.axes2.position = [0.5 0.1 0.4 0.6];
%       props.axes1.fontsize = 10;
%       props.axes2.fontsize = 18;
%       props.axes2.linewidth = 2;
%       props.xlabel = 'poput x-label';
%       props.ylabel = 'poput y-label';
%
%       [ax1 ax2] = popout(gcf, 10, 20, props);
%
%
%       Copyright 2011, Simon Henin <shenin@gc.cuny.edu>

if nargin < 4,
   extraprops.axes1.position = [0.1 0.55 0.65 0.35];
   extraprops.axes2.position = [0.3 0.1 0.6 0.55];
end

type = get(h, 'Type');
if strcmp(type, 'figure'),
    ax1 = get(h, 'children');
else
    ax1 = h;
end
padding = 10;

ax2 = copyobj(ax1, h);
set(ax2, 'position', extraprops.axes2.position);

children = get(ax1, 'children');
ylimit = get(ax1, 'Ylim');
set(ax1, 'position',extraprops.axes1.position);
ylim([ylimit(1)+ylimit(1)*(padding/100) ylimit(2)+ylimit(2)*(padding/100)]);

ymax = 0;
ymin = 0;
for i=1:length(children),
    xd = get(children(i), 'xdata');
    index = find(xd >= xmin & xd <= xmax);
    yd =  get(children(i), 'ydata');
    ymax = max(ymax, max(yd(index)));
    ymin = min(ymin, min(yd(index)));
end

axes(ax1);
rectangle('Position',[xmin,ymin,xmax-xmin,ymax-ymin], 'linewidth', 2);

axes(ax2);
title('');
xlim([xmin xmax]);
ylim([ymin ymax]);

% add special pop-out properties
if isfield(extraprops, 'xlabel'),
   xlabel(extraprops.xlabel);
end
if isfield(extraprops, 'ylabel'),
   ylabel(extraprops.ylabel);
end

% add axes properties
fields = fieldnames(extraprops.axes1);
for i=1:length(fields),
   set(ax1, fields{i}, getfield(extraprops.axes1, fields{i}));
end
fields = fieldnames(extraprops.axes2);
for i=1:length(fields),
   set(ax2, fields{i}, getfield(extraprops.axes2, fields{i}));
end

% add pop-out lines
[xf1 yf1] = popout_getcoords(ax1, xmin, ymin);
[xf2 yf2] = popout_getcoords(ax2, xmin, ymin);
annotation('line',[xf1 xf2],[yf1 yf2]);

[xf1 yf1] = popout_getcoords(ax1, xmin, ymax);
[xf2 yf2] = popout_getcoords(ax2, xmin, ymax);
annotation('line',[xf1 xf2],[yf1 yf2]);

[xf1 yf1] = popout_getcoords(ax1, xmax, ymin);
[xf2 yf2] = popout_getcoords(ax2, xmax, ymin);
annotation('line',[xf1 xf2],[yf1 yf2]);

[xf1 yf1] = popout_getcoords(ax1, xmax, ymax);
[xf2 yf2] = popout_getcoords(ax2, xmax, ymax);
annotation('line',[xf1 xf2],[yf1 yf2]);

axes(ax2);

function [x y] = popout_getcoords(ax, x, y)

%% Get limits
axun = get(ax,'Units');
set(ax,'Units','normalized');
axpos = get(ax,'Position');
axlim = axis(ax);
axwidth = diff(axlim(1:2));
axheight = diff(axlim(3:4));

x = (x-axlim(1))*axpos(3)/axwidth + axpos(1);
y = (y-axlim(3))*axpos(4)/axheight + axpos(2);

%% Restore axes units
set(ax,'Units',axun)


text:
%GETVALUEOFASSIGNMENT Gets the value of a variable assignment in a factor.
%
%   v = GETVALUEOFASSIGNMENT(F, A) returns the value of a variable assignment,
%   A, in factor F. The order of the variables in A are assumed to be the
%   same as the order in F.var.
%
%   v = GETVALUEOFASSIGNMENT(F, A, VO) gets the value of a variable assignment,
%   A, in factor F. The order of the variables in A are given by the vector VO.
%
%   See also SETVALUEOFASSIGNMENT

% Copyright (C) Daphne Koller, Stanford Univerity, 2012

function v = GetValueOfAssignment(F, A, VO)

if (nargin == 2),
    indx = AssignmentToIndex(A, F.card);
else
    map = zeros(length(F.var), 1);
    for i = 1:length(F.var),
        map(i) = find(VO == F.var(i));
    end;
    indx = AssignmentToIndex(A(map), F.card);
end;

v = F.val(indx);

author: anhncs

repo: Probabilistic-Graphical-Models


text:
function [ t_start, y_start ] = p27_start ( neqn )

%*****************************************************************************80
%
%% P27_START returns the starting point for problem p27.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real T_START, Y_START(NEQN,1), the initial data.
%
  y_start = zeros ( neqn, 1 );

  t_start = 0.0;
  y_start = 110.0;

  return
end


text:
% Set Program Path
function	set_dir

%root_dir = getenv('MFILE');
%prog_dir = [root_dir '/VBtool/prediction'];
prog_dir = pwd;

addpath([prog_dir]);
addpath([prog_dir '/test']);
addpath([prog_dir '/basic_func']);
addpath([prog_dir '/../mex_prog']);

author: KamitaniLab

repo: GenericObjectDecoding


text:
function [channel] = ft_channelselection(desired, datachannel, senstype)

% FT_CHANNELSELECTION makes a selection of EEG and/or MEG channel labels. This
% function translates the user-specified list of channels into channel labels as they
% occur in the data. This channel selection procedure can be used throughout
% FieldTrip.
%
% You can specify a mixture of real channel labels and of special strings, or index
% numbers that will be replaced by the corresponding channel labels. Channels that
% are not present in the raw datafile are automatically removed from the channel
% list.
%
% The order of the channels in the list that is returned corresponds to the order in
% the data.
%
% E.g. the desired input specification can be:
%   'all'        is replaced by all channels in the datafile
%   'gui'        this will pop up a graphical user interface to select the channels
%   'C*'         is replaced by all channels that match the wildcard, e.g. C1, C2, C3, ...
%   '*1'         is replaced by all channels that match the wildcard, e.g. C1, P1, F1, ...
%   'M*1'        is replaced by all channels that match the wildcard, e.g. MEG0111, MEG0131, MEG0131, ...
%   'meg'        is replaced by all MEG channels (works for CTF, 4D, Neuromag and Yokogawa)
%   'megref'     is replaced by all MEG reference channels (works for CTF and 4D)
%   'meggrad'    is replaced by all MEG gradiometer channels (works for Yokogawa and Neuromag306)
%   'megplanar'  is replaced by all MEG planar gradiometer channels (works for Neuromag306)
%   'megmag'     is replaced by all MEG magnetometer channels (works for Yokogawa and Neuromag306)
%   'eeg'        is replaced by all recognized EEG channels (this is system dependent)
%   'eeg1020'    is replaced by 'Fp1', 'Fpz', 'Fp2', 'F7', 'F3', ...
%   'eog'        is replaced by all recognized EOG channels
%   'ecg'        is replaced by all recognized ECG channels
%   'nirs'       is replaced by all channels recognized as NIRS channels
%   'emg'        is replaced by all channels in the datafile starting with 'EMG'
%   'lfp'        is replaced by all channels in the datafile starting with 'lfp'
%   'mua'        is replaced by all channels in the datafile starting with 'mua'
%   'spike'      is replaced by all channels in the datafile starting with 'spike'
%   10           is replaced by the 10th channel in the datafile
%
% Other channel groups are
%   'EEG1010'    with approximately 90 electrodes
%   'EEG1005'    with approximately 350 electrodes
%   'EEGREF'     for mastoid and ear electrodes (M1, M2, LM, RM, A1, A2)
%   'MZ'         for MEG zenith
%   'ML'         for MEG left
%   'MR'         for MEG right
%   'MLx', 'MRx' and 'MZx' with x=C,F,O,P,T for left/right central, frontal, occipital, parietal and temporal
%
% You can also exclude channels or channel groups using the following syntax
%   {'all', '-POz', '-Fp1', -EOG'}
%
% See also FT_PREPROCESSING, FT_SENSLABEL, FT_MULTIPLOTER, FT_MULTIPLOTTFR,
% FT_SINGLEPLOTER, FT_SINGLEPLOTTFR

% Copyright (C) 2003-2021, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

% this is to avoid a recursion loop
persistent recursion

if isempty(recursion)
  recursion = false;
end

if nargin<3
  % the actual senstype will be determined further down
  % postponing the detection speeds up some common use patterns, such as 'all' and []
  senstype = [];
end

if iscell(datachannel)
  % this is the expected format of the input
  datachantype = {};
elseif ischar(datachannel)
  datachannel = {datachannel};
  datachantype = {};
elseif isstruct(datachannel) && isfield(datachannel, 'label')
  % it looks like a header structure
  hdr = datachannel;
  datachannel = hdr.label;
  datachantype = ft_chantype(hdr);
else
  ft_error('please specify the data channels as a cell-array');
end

if length(datachannel)~=length(unique(datachannel))
  ft_warning('discarding non-unique channel names');
  sel = false(size(datachannel));
  for i=1:length(datachannel)
    sel(i) = sum(strcmp(datachannel, datachannel{i}))==1;
  end
  datachannel = datachannel(sel);
  if ~isempty(datachantype)
    datachantype = datachantype(sel);
  end
end

if isempty(desired)
  % return an empty selection
  channel = {};
  return
elseif isequal(desired, 'all') || isequal(desired, {'all'})
  % this is a very common use pattern that can be dealt with quickly
  % ensure that the output is a column vector
  channel = datachannel(:);
  return
elseif isnumeric(desired)
  % remove channels that fall outside the range
  desired = desired(desired>=1 & desired<=numel(datachannel));
  % change the numeric index into the channel name
  channel = datachannel(desired);
  return
elseif ischar(desired)
  % ensure that a single input argument like 'all' also works
  desired = {desired};
elseif ~iscell(desired)
  ft_error('please specify the desired channels as a cell-array or a string');
end

% start with the list of desired channels, this will be pruned/expanded further down
channel = desired;

% ensure that both inputs are column vectors
channel     = channel(:);
datachannel = datachannel(:);

% remove channels that occur more than once, this sorts the channels alphabetically
[channel, indx] = unique(channel);
% undo the sorting, make the order identical to that of the data channels
[dum, indx] = sort(indx);
channel = channel(indx);

[dataindx, chanindx] = match_str(datachannel, channel);
if length(chanindx)==length(channel)
  % there is a perfect match between the channels and the datachannels, only some reordering is needed
  channel = channel(chanindx);
  % no need to look at channel groups
  return
end

% initialize all the system-specific variables to empty
labelall       = {};
labelreg       = {};
labelmeg       = {};
labelecg       = {};
labelemg       = {};
labeleeg       = {};
label102       = {};
label101       = {};
label100       = {};
labelchwilla   = {};
labelbha       = {};
labelref       = {};
labelmegref    = {};
labelmeggrad   = {};
labelmegplanar = {};
labelmegmag    = {};
labelmegrefa   = {};
labelmegrefc   = {};
labelmegrefg   = {};
labelmegrefl   = {};
labelmegrefr   = {};
labelmegrefm   = {};
labeleog       = {};
labelmz        = {};
labelml        = {};
labelmr        = {};
labelmlc       = {};
labelmlf       = {};
labelmlo       = {};
labelmlp       = {};
labelmlt       = {};
labelmrc       = {};
labelmrf       = {};
labelmro       = {};
labelmrp       = {};
labelmrt       = {};
labelmzc       = {};
labelmzf       = {};
labelmzo       = {};
labelmzp       = {};
labellfp       = {};
labelmua       = {};
labelspike     = {};
labelnirs      = {};

% define the known groups with channel labels
labelall    = datachannel;
label1020   = ft_senslabel('eeg1020'); % use external helper function
label1010   = ft_senslabel('eeg1010'); % use external helper function
label1005   = ft_senslabel('eeg1005'); % use external helper function
labelchwilla = {'Fz', 'Cz', 'Pz', 'F7', 'F8', 'LAT', 'RAT', 'LT', 'RT', 'LTP', 'RTP', 'OL', 'OR', 'FzA', 'Oz', 'F7A', 'F8A', 'F3A', 'F4A', 'F3', 'F4', 'P3', 'P4', 'T5', 'T6', 'P3P', 'P4P'}';
labelbham   = {'P9', 'PPO9h', 'PO7', 'PPO5h', 'PPO3h', 'PO5h', 'POO9h', 'PO9', 'I1', 'OI1h', 'O1', 'POO1', 'PO3h', 'PPO1h', 'PPO2h', 'POz', 'Oz', 'Iz', 'I2', 'OI2h', 'O2', 'POO2', 'PO4h', 'PPO4h', 'PO6h', 'POO10h', 'PO10', 'PO8', 'PPO6h', 'PPO10h', 'P10', 'P8', 'TPP9h', 'TP7', 'TTP7h', 'CP5', 'TPP7h', 'P7', 'P5', 'CPP5h', 'CCP5h', 'CP3', 'P3', 'CPP3h', 'CCP3h', 'CP1', 'P1', 'Pz', 'CPP1h', 'CPz', 'CPP2h', 'P2', 'CPP4h', 'CP2', 'CCP4h', 'CP4', 'P4', 'P6', 'CPP6h', 'CCP6h', 'CP6', 'TPP8h', 'TP8', 'TPP10h', 'T7', 'FTT7h', 'FT7', 'FC5', 'FCC5h', 'C5', 'C3', 'FCC3h', 'FC3', 'FC1', 'C1', 'CCP1h', 'Cz', 'FCC1h', 'FCz', 'FFC1h', 'Fz', 'FFC2h', 'FC2', 'FCC2h', 'CCP2h', 'C2', 'C4', 'FCC4h', 'FC4', 'FC6', 'FCC6h', 'C6', 'TTP8h', 'T8', 'FTT8h', 'FT8', 'FT9', 'FFT9h', 'F7', 'FFT7h', 'FFC5h', 'F5', 'AFF7h', 'AF7', 'AF5h', 'AFF5h', 'F3', 'FFC3h', 'F1', 'AF3h', 'Fp1', 'Fpz', 'Fp2', 'AFz', 'AF4h', 'F2', 'FFC4h', 'F4', 'AFF6h', 'AF6h', 'AF8', 'AFF8h', 'F6', 'FFC6h', 'FFT8h', 'F8', 'FFT10h', 'FT10'};
labelref    = {'M1', 'M2', 'LM', 'RM', 'A1', 'A2'}';
labeleeg    = datachannel(startsWith(datachannel, 'EEG'));               % anything that starts with EEG
labeleog    = datachannel(startsWith(datachannel, 'EOG'));               % anything that starts with EOG
labeleog    = [labeleog(:); {'HEOG', 'VEOG', 'VEOG-L', 'VEOG-R', 'hEOG', 'vEOG', 'Eye_Ver', 'Eye_Hor'}'];     % or any of these
labelecg    = datachannel(strncmp('ECG', datachannel, length('ECG')));
labelemg    = datachannel(strncmp('EMG', datachannel, length('EMG')));
labellfp    = datachannel(strncmp('lfp', datachannel, length('lfp')));
labelmua    = datachannel(strncmp('mua', datachannel, length('mua')));
labelspike  = datachannel(strncmp('spike', datachannel, length('spike')));
% for NIRS there are multiple options, either using the terminology transmitter/receiver versus source/detector, and then with either order of the two
option1 = ~cellfun(@isempty, regexp(datachannel, sprintf('%s%s', regexptranslate('wildcard','Rx*-Tx*[*]'), '$')));
option2 = ~cellfun(@isempty, regexp(datachannel, sprintf('%s%s', regexptranslate('wildcard','Tx*-Rx*[*]'), '$')));
option3 = ~cellfun(@isempty, regexp(datachannel, sprintf('%s%s', regexptranslate('wildcard','D*-S*[*]'), '$')));
option4 = ~cellfun(@isempty, regexp(datachannel, sprintf('%s%s', regexptranslate('wildcard','S*-D*[*]'), '$')));
labelnirs = datachannel(option1 | option2 | option3 | option4);

% use regular expressions to deal with the wildcards
labelreg = false(size(datachannel));
findreg  = [];
for i=1:length(channel)
  if length(channel{i}) < 1
    continue;
  end

  if strcmp((channel{i}(1)), '-')
    % skip channels to be excluded
    continue;
  end

  rexp = sprintf('%s%s%s', '^', regexptranslate('wildcard',channel{i}), '$');
  lreg = ~cellfun(@isempty, regexp(datachannel, rexp));
  if any(lreg)
    labelreg = labelreg | lreg;
    findreg  = [findreg; i];
  end
end

if ~isempty(findreg)
  findreg  = unique(findreg); % remove multiple occurances due to multiple wildcards
  labelreg = datachannel(labelreg);
end

if isempty(senstype)
  senstype = ft_senstype(datachannel);
end

switch senstype

  case {'yokogawa', 'yokogawa160', 'yokogawa160_planar', 'yokogawa64', 'yokogawa64_planar', 'yokogawa440', 'yokogawa440_planar'}
    % Yokogawa axial gradiometers channels start with AG, hardware planar gradiometer
    % channels start with PG, magnetometers start with M
    megax    = strncmp('AG', datachannel, length('AG'));
    megpl    = strncmp('PG', datachannel, length('PG'));
    megmag   = strncmp('M',  datachannel, length('M' ));
    megind   = logical( megax + megpl + megmag);
    labelmeg      = datachannel(megind);
    labelmegmag   = datachannel(megmag);
    labelmeggrad  = datachannel(megax | megpl);
    %%
    %    labeleeg  = datachannel(strncmp('EEG', datachannel, length('EEG')));
    eeg_A = myregexp('^A[^G]*[0-9hzZ]$', datachannel);
    eeg_P = myregexp('^P[^G]*[0-9hzZ]$', datachannel);
    eeg_T = myregexp('^T[^R]*[0-9hzZ]$', datachannel);
    eeg_E = myregexp('^E$', datachannel);
    eeg_Z = myregexp('^[zZ]$', datachannel);
    eeg_M = myregexp('^M[0-9]$', datachannel);
    eeg_O = myregexp('^[BCFION]\w*[0-9hzZ]$', datachannel);
    eeg_EEG = myregexp('^EEG[0-9][0-9][0-9]$', datachannel);
    eegind = logical( eeg_A + eeg_P + eeg_T + eeg_E + eeg_Z + eeg_M + eeg_O + eeg_EEG );
    clear eeg_A eeg_P eeg_T eeg_E eeg_Z eeg_M eeg_O eeg_EEG
    labeleeg      = datachannel(eegind);
    labeleog    = [ labeleog(:); datachannel(myregexp('^EO[0-9]$', datachannel)) ];  % add 'EO'
    labelecg    = [ labelecg(:); datachannel(myregexp('^X[0-9]$', datachannel)) ];   % add 'X'

  case {'ctf64'}
    labelml     = datachannel(~cellfun(@isempty, regexp(datachannel, '^SL')));    % left    MEG channels
    labelmr     = datachannel(~cellfun(@isempty, regexp(datachannel, '^SR')));    % right   MEG channels
    labelmeg    = cat(1, labelml, labelmr);
    labelmegref = [datachannel(strncmp('B'  , datachannel, 1));
      datachannel(strncmp('G'  , datachannel, 1));
      datachannel(strncmp('P'  , datachannel, 1));
      datachannel(strncmp('Q'  , datachannel, 1));
      datachannel(strncmp('R'  , datachannel, length('G'  )))];

  case {'ctf', 'ctf275', 'ctf151', 'ctf275_planar', 'ctf151_planar'}
    % all CTF MEG channels start with "M"
    % all CTF reference channels start with B, G, P, Q or R
    % all CTF EEG channels start with "EEG"
    labelmeg    = datachannel(strncmp('M'  , datachannel, length('M'  )));
    labelmegref = [datachannel(strncmp('B'  , datachannel, 1));
      datachannel(strncmp('G'  , datachannel, 1));
      datachannel(strncmp('P'  , datachannel, 1));
      datachannel(strncmp('Q'  , datachannel, 1));
      datachannel(strncmp('R'  , datachannel, length('G'  )))];
    labeleeg  = datachannel(strncmp('EEG', datachannel, length('EEG')));

    % Not sure whether this should be here or outside the switch or
    % whether these specifications should be supported for systems
    % other than CTF.
    labelmz   = datachannel(strncmp('MZ' , datachannel, length('MZ' )));    % central MEG channels
    labelml   = datachannel(strncmp('ML' , datachannel, length('ML' )));    % left    MEG channels
    labelmr   = datachannel(strncmp('MR' , datachannel, length('MR' )));    % right   MEG channels
    labelmlc  = datachannel(strncmp('MLC', datachannel, length('MLC')));
    labelmlf  = datachannel(strncmp('MLF', datachannel, length('MLF')));
    labelmlo  = datachannel(strncmp('MLO', datachannel, length('MLO')));
    labelmlp  = datachannel(strncmp('MLP', datachannel, length('MLP')));
    labelmlt  = datachannel(strncmp('MLT', datachannel, length('MLT')));
    labelmrc  = datachannel(strncmp('MRC', datachannel, length('MRC')));
    labelmrf  = datachannel(strncmp('MRF', datachannel, length('MRF')));
    labelmro  = datachannel(strncmp('MRO', datachannel, length('MRO')));
    labelmrp  = datachannel(strncmp('MRP', datachannel, length('MRP')));
    labelmrt  = datachannel(strncmp('MRT', datachannel, length('MRT')));
    labelmzc  = datachannel(strncmp('MZC', datachannel, length('MZC')));
    labelmzf  = datachannel(strncmp('MZF', datachannel, length('MZF')));
    labelmzo  = datachannel(strncmp('MZO', datachannel, length('MZO')));
    labelmzp  = datachannel(strncmp('MZP', datachannel, length('MZP')));

  case {'bti', 'bti248', 'bti248grad', 'bti148', 'bti248_planar', 'bti148_planar'}
    % all 4D-BTi MEG channels start with "A"
    % all 4D-BTi reference channels start with M or G

    labelmeg     = datachannel(myregexp('^A[0-9]+$', datachannel));
    labelmegref  = [datachannel(myregexp('^M[CLR][xyz][aA]*$', datachannel)); datachannel(myregexp('^G[xyz][xyz]A$', datachannel)); datachannel(myregexp('^M[xyz][aA]*$', datachannel))];
    labelmegrefa = datachannel(~cellfun(@isempty,strfind(datachannel, 'a')));
    labelmegrefc = datachannel(strncmp('MC', datachannel, 2));
    labelmegrefg = datachannel(myregexp('^G[xyz][xyz]A$', datachannel));
    labelmegrefl = datachannel(strncmp('ML', datachannel, 2));
    labelmegrefr = datachannel(strncmp('MR', datachannel, 2));
    labelmegrefm = datachannel(myregexp('^M[xyz][aA]*$', datachannel));

  case {'neuromag122' 'neuromag122alt', 'neuromag122_combined'}
    % all neuromag MEG channels start with MEG
    % all neuromag EEG channels start with EEG
    labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG')));
    labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG')));

  case {'neuromag306' 'neuromag306alt', 'neuromag306_combined'}
    % all neuromag MEG channels start with MEG
    % all neuromag EEG channels start with EEG
    % all neuromag306 gradiometers follow pattern MEG*2,MEG*3
    % all neuromag306 magnetometers follow pattern MEG*1
    labelmeg = datachannel(strncmp('MEG', datachannel, length('MEG')));
    labeleeg = datachannel(strncmp('EEG', datachannel, length('EEG')));

    labelmeggrad   = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*[23]$')));
    labelmegmag    = labelmeg(~cellfun(@isempty, regexp(labelmeg, '^MEG.*1$')));
    labelmegplanar = labelmeggrad;

  case {'ant128', 'biosemi64', 'biosemi128', 'biosemi256', 'egi32', 'egi64', 'egi128', 'egi256', 'eeg1020', 'eeg1010', 'eeg1005', 'ext1020'}
    if ~ft_senstype(datachannel, 'unknown')
      % use an external helper function to define the list with EEG channel names
      labeleeg = ft_senslabel(ft_senstype(datachannel));
    end

  case {'itab153' 'itab28' 'itab28_old'}
    % all itab MEG channels start with MAG
    labelmeg = datachannel(strncmp('MAG', datachannel, length('MAG')));

  case{'qzfm_gen2'}
    % This is for use with QZFM_Gen2 Optically Pumped Magnetometers manufactured by QuSpin Inc.
    % SPECS: https://quspin.com/qzfm-gen-2-update/

    labelmeg    = datachannel(strncmp('meg', datachantype, 3));
    labelmegref = datachannel(strncmp('refmag', datachantype, 3));

    % All channels measuring tangential fields are end with TAN
    % All channels measuring radial fields are end with RAD

    % This is specific to data collected from UCL. Also see:
    % https://www.fieldtriptoolbox.org/getting_started/opm_fil/
    labelmegtan = labelmeg(~cellfun(@isempty, regexp(labelmeg, '.*TAN$')));
    labelmegrad = labelmeg(~cellfun(@isempty, regexp(labelmeg, '.*RAD$')));

  otherwise
    if ~isempty(datachantype)
      labelmeg = datachannel(strncmp('meg', datachantype, 3));
      labeleeg = datachannel(strncmp('eeg', datachantype, 3));
    end

end % switch ft_senstype

% figure out if there are bad channels or channel groups that should be excluded
findbadchannel = strncmp('-', channel, length('-'));      % bad channels start with '-'
badchannel = channel(findbadchannel);
if ~isempty(badchannel)
  for i=1:length(badchannel)
    badchannel{i} = badchannel{i}(2:end);                 % remove the '-' from the channel label
  end
  badchannel = ft_channelselection(badchannel, datachannel); % support exclusion of channel groups
end

% determine if any of the known groups is mentioned in the channel list
findall        = find(strcmp(channel, 'all'));
% findreg (for the wildcards) is dealt with in the channel group specification above
findmeg        = find(strcmpi(channel, 'MEG'));
findemg        = find(strcmpi(channel, 'EMG'));
findecg        = find(strcmpi(channel, 'ECG'));
findeeg        = find(strcmpi(channel, 'EEG'));
findeeg1020    = find(strcmpi(channel, 'EEG1020'));
findeeg1010    = find(strcmpi(channel, 'EEG1010'));
findeeg1005    = find(strcmpi(channel, 'EEG1005'));
findeegchwilla = find(strcmpi(channel, 'EEGCHWILLA'));
findeegbham    = find(strcmpi(channel, 'EEGBHAM'));
findeegref     = find(strcmpi(channel, 'EEGREF'));
findmegref     = find(strcmpi(channel, 'MEGREF'));
findmeggrad    = find(strcmpi(channel, 'MEGGRAD'));
findmegplanar  = find(strcmpi(channel, 'MEGPLANAR'));
findmegmag     = find(strcmpi(channel, 'MEGMAG'));
findmegrefa    = find(strcmpi(channel, 'MEGREFA'));
findmegrefc    = find(strcmpi(channel, 'MEGREFC'));
findmegrefg    = find(strcmpi(channel, 'MEGREFG'));
findmegrefl    = find(strcmpi(channel, 'MEGREFL'));
findmegrefr    = find(strcmpi(channel, 'MEGREFR'));
findmegrefm    = find(strcmpi(channel, 'MEGREFM'));
findmegtan     = find(strcmpi(channel, 'MEGTAN'));
findmegrad     = find(strcmpi(channel, 'MEGRAD'));
findeog        = find(strcmpi(channel, 'EOG'));
findmz         = find(strcmp(channel, 'MZ' ));
findml         = find(strcmp(channel, 'ML' ));
findmr         = find(strcmp(channel, 'MR' ));
findmlc        = find(strcmp(channel, 'MLC'));
findmlf        = find(strcmp(channel, 'MLF'));
findmlo        = find(strcmp(channel, 'MLO'));
findmlp        = find(strcmp(channel, 'MLP'));
findmlt        = find(strcmp(channel, 'MLT'));
findmrc        = find(strcmp(channel, 'MRC'));
findmrf        = find(strcmp(channel, 'MRF'));
findmro        = find(strcmp(channel, 'MRO'));
findmrp        = find(strcmp(channel, 'MRP'));
findmrt        = find(strcmp(channel, 'MRT'));
findmzc        = find(strcmp(channel, 'MZC'));
findmzf        = find(strcmp(channel, 'MZF'));
findmzo        = find(strcmp(channel, 'MZO'));
findmzp        = find(strcmp(channel, 'MZP'));
findnirs       = find(strcmpi(channel, 'NIRS'));
findlfp        = find(strcmpi(channel, 'lfp'));
findmua        = find(strcmpi(channel, 'mua'));
findspike      = find(strcmpi(channel, 'spike'));
findgui        = find(strcmpi(channel, 'gui'));

% remove any occurences of groups in the channel list
channel([
  findall
  findreg
  findmeg
  findemg
  findecg
  findeeg
  findeeg1020
  findeeg1010
  findeeg1005
  findeegchwilla
  findeegbham
  findeegref
  findmegref
  findmeggrad
  findmegplanar
  findmegmag
  findeog
  findmz
  findml
  findmr
  findmlc
  findmlf
  findmlo
  findmlp
  findmlt
  findmrc
  findmrf
  findmro
  findmrp
  findmrt
  findmzc
  findmzf
  findmzo
  findmzp
  findlfp
  findmua
  findspike
  findnirs
  findgui
  ]) = [];

% add the full channel labels to the channel list
if findall,        channel = [channel; labelall]; end
if findreg,        channel = [channel; labelreg]; end
if findmeg,        channel = [channel; labelmeg]; end
if findecg,        channel = [channel; labelecg]; end
if findemg,        channel = [channel; labelemg]; end
if findeeg,        channel = [channel; labeleeg]; end
if findeeg1020,    channel = [channel; label1020]; end
if findeeg1010,    channel = [channel; label1010]; end
if findeeg1005,    channel = [channel; label1005]; end
if findeegchwilla, channel = [channel; labelchwilla]; end
if findeegbham,    channel = [channel; labelbham]; end
if findeegref,     channel = [channel; labelref]; end
if findmegref,     channel = [channel; labelmegref]; end
if findmeggrad,    channel = [channel; labelmeggrad]; end
if findmegplanar,  channel = [channel; labelmegplanar]; end
if findmegmag,     channel = [channel; labelmegmag]; end
if findmegrefa,    channel = [channel; labelmegrefa]; end
if findmegrefc,    channel = [channel; labelmegrefc]; end
if findmegrefg,    channel = [channel; labelmegrefg]; end
if findmegrefl,    channel = [channel; labelmegrefl]; end
if findmegrefr,    channel = [channel; labelmegrefr]; end
if findmegrefm,    channel = [channel; labelmegrefm]; end
if findmegtan,     channel = [channel; labelmegtan]; end
if findmegrad,     channel = [channel; labelmegrad]; end
if findeog,        channel = [channel; labeleog]; end
if findmz ,        channel = [channel; labelmz ]; end
if findml ,        channel = [channel; labelml ]; end
if findmr ,        channel = [channel; labelmr ]; end
if findmlc,        channel = [channel; labelmlc]; end
if findmlf,        channel = [channel; labelmlf]; end
if findmlo,        channel = [channel; labelmlo]; end
if findmlp,        channel = [channel; labelmlp]; end
if findmlt,        channel = [channel; labelmlt]; end
if findmrc,        channel = [channel; labelmrc]; end
if findmrf,        channel = [channel; labelmrf]; end
if findmro,        channel = [channel; labelmro]; end
if findmrp,        channel = [channel; labelmrp]; end
if findmrt,        channel = [channel; labelmrt]; end
if findmzc,        channel = [channel; labelmzc]; end
if findmzf,        channel = [channel; labelmzf]; end
if findmzo,        channel = [channel; labelmzo]; end
if findmzp,        channel = [channel; labelmzp]; end
if findlfp,        channel = [channel; labellfp]; end
if findmua,        channel = [channel; labelmua]; end
if findspike,      channel = [channel; labelspike]; end
if findnirs,       channel = [channel; labelnirs]; end

% remove channel labels that have been excluded by the user
badindx = match_str(channel, badchannel);
channel(badindx) = [];

% remove channel labels that are not present in the data
chanindx = match_str(channel, datachannel);
channel  = channel(chanindx);

if findgui
  indx = select_channel_list(datachannel, match_str(datachannel, channel), 'Select channels');
  channel = datachannel(indx);
end

% remove channels that occur more than once, this sorts the channels alphabetically
channel = unique(channel);

if isempty(channel) && ~recursion
  % try whether only lowercase channel labels makes a difference
  recursion = true;
  channel   = ft_channelselection(desired, lower(datachannel));
  recursion = false;
  % undo the conversion to lowercase, this sorts the channels alphabetically
  [c, ia, ib] = intersect(channel, lower(datachannel));
  channel = datachannel(ib);
end

if isempty(channel) && ~recursion
  % try whether only uppercase channel labels makes a difference
  recursion = true;
  channel = ft_channelselection(desired, upper(datachannel));
  recursion = false;
  % undo the conversion to uppercase, this sorts the channels alphabetically
  [c, ia, ib] = intersect(channel, lower(datachannel));
  channel = datachannel(ib);
end

% undo the sorting, make the order identical to that of the data channels
[tmp, indx] = match_str(datachannel, channel);
channel = channel(indx);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function match = myregexp(pat, list)
match = false(size(list));
for i=1:numel(list)
  match(i) = ~isempty(regexp(list{i}, pat, 'once'));
end


text:
function jed = ymdf_to_jed_hindu_solar ( y, m, d, f )

%*****************************************************************************80
%
%% YMDF_TO_JED_HINDU_SOLAR converts a Hindu solar YMDF date to a JED.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Edward Reingold, Nachum Dershowitz, Stewart Clamen,
%    Calendrical Calculations, II: Three Historical Calendars,
%    Software - Practice and Experience,
%    Volume 23, Number 4, pages 383-404, April 1993.
%
%  Parameters:
%
%    Input, integer Y, M, D, real F, the YMDF date.
%
%    Output, real JED, the Julian Ephemeris Date.
%
  jed_epoch = epoch_to_jed_hindu_solar ( );

  jed = jed_epoch + ...
      ( d - 1 ) ...
    + ( m - 1 ) * month_length_hindu_solar ( ) ...
    + y * year_length_hindu_solar ( ) ...
    + f;

  return
end


text:
function [myfft, freq, handle] = fft_plot_scnlab(dat, TR, varargin)
% :Usage:
% ::
%
%     [myfft, freq, handle] = fft_plot_scnlab(dat, TR, varargin)
%
% :Inputs:
%
%   **dat:**
%        is a data vector (column)
%
%   **TR:**
%        is the sampling rate of the data you put in
%        in seconds / sample, or 1/Hz
%
% :Optional inputs:
%   - 'samefig'
%   - 'color, ['b'] or other color
%   - 'bar'
%   - 'linebar': both line and bar
%
% :Examples:
% ::
%
%    % plot effects of filtering on a difference
%    % between two regressors
%    spm_hplength = SPM.xX.K.HParam;
%    d = SPM.xX.X * SPM.xCon(mycon).c(:, 1);
%    create_figure('Contrast'); plot(d) % contrast we care about
%    px = pinv(SPM.xX.K.X0);           % pinv of the filtering matrix
%    y = d;
%    y = y - SPM.xX.K.X0 * px * y;     % residuals after filtering
%
%    [myfft, freq, handle] = fft_plot_scnlab(d, 2);
%    hold on;
%    [myfft2, freq2, handle] = fft_plot_scnlab(y, 2); set(handle,'Color','r')
%    plot_vertical_line(1/spm_hplength)
%    set(ans, 'Color', 'b', 'LineWidth', 3)
%

fftfig = 1;
ptype = 'line';
color = 'k';

for i = 1:length(varargin)
    if ischar(varargin{i})
        switch varargin{i}
            % reserved keywords
            case 'samefig', fftfig = 0;

            case 'bar', ptype = 'bar';
            case 'color', color = varargin{i+1}; varargin{i+1} = [];

            case 'linebar', ptype = 'both';

            otherwise, warning(['Unknown input string option:' varargin{i}]);
        end
    end
end

n = length(dat);

% from matlab example
% power = abs(Y(1:floor(n/2))).^2;
% nyquist = 1/2;
% freq = (1:n/2)/(n/2)*nyquist

nyq = 1 ./ (2 * TR);

timepts = floor(n ./ 2);

freq = (0:timepts-1)/timepts * nyq;
%freq = linspace(0, nyq, timepts)';

myfft = fft(dat); %real(abs(fft(dat)));
myfft = abs(myfft(1:timepts)) .^ 2;  % power

myfft = myfft ./ sum(myfft);

if fftfig
    create_figure('fftplot',1, 1, 1);
else
    hold on
end

%myfft = myfft(1:timepts);
switch ptype
    case 'line'
        handle = plot(freq, myfft, '-', 'Color', color, 'LineWidth', 2);

    case 'bar'
        handle = bar(freq, myfft);
        set(handle, 'FaceColor', color);

    case 'both'
        handle = bar(freq, myfft);
        set(handle, 'FaceColor', color, 'EdgeColor', 'none');
        handle = plot(freq, myfft, '-', 'Color', color, 'LineWidth', 2);

    otherwise
        error('unknown plot type');
end

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function h = min(f, g, dim)
%MIN   Minimum value of a CHEBFUN3 in one direction.
%   MIN(F) returns a CHEBFUN2 representing the minimum of the CHEBFUN3
%   object F along the x direction, i.e, MIN(F) = @(y,z) min(F(:, y, z)).
%
%   MIN(F, [], DIM) returns a CHEBFUN2 representing the minimum of F along
%   the dimension DIM. DIM should be 1, 2 or 3 to minimize over X, Y or Z,
%   respectively.
%
%   WARNING: This function is not always accurate to the expected precision.
%
% See also CHEBFUN3/MIN2 and CHEBFUN3/MIN3.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Empty check:
if ( isempty(f) )
    error('CHEBFUN:CHEBFUN3:min:input', 'CHEBFUN3 is empty');
end

% Default to min of one chebfun3:
if ( nargin < 2 )
    g = [];
end

% Default to minimum along the x direction:
if ( nargin < 3 )
    dim = 1;
end

% Do not allow min(F, G):
if ( nargin > 1 && ~isempty(g) )
    error('CHEBFUN:CHEBFUN3:min:twoCHEBFUN3Inputs', ...
        'Unable to minimize two CHEBFUN3 objects.');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% We have no idea how to achieve this in an efficient way. This
% is an attempt to return a result, but typically it won't be accurate to
% more than 4-5 digits.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

dom = f.domain;
n = 129;
if ( dim == 1 )
    vals = sample(f, n, n, n);
    h = chebfun2(squeeze(min(vals, [], 1)), dom(3:6));
    h = simplify(h);

elseif ( dim == 2 )
    vals = sample(f, n, n, n);
    h = chebfun2(squeeze(min(vals, [], 2)), [dom(1:2), dom(5:6)]);
    h = simplify(h);

elseif ( dim == 3 )
    vals = sample(f, n, n, n);
    h = chebfun2(min(vals, [], 3), dom(1:4));
    h = simplify(h);

elseif ( dim == 0 )
    error('CHEBFUN:CHEBFUN3:min:dim', 'dim must be 1, 2, or 3.')
else
   % Return the CHEBFUN3 object. This is analogous to that MIN() command in
   % MATLAB.
   h = f;
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function r8mat_fss_test ( )

%*****************************************************************************80
%
%% R8MAT_FSS_TEST tests R8MAT_FSS.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 November 2011
%
%  Author:
%
%    John Burkardt
%
  n = 10;
  nb = 3;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8MAT_FSS_TEST\n' );
  fprintf ( 1, '  For a matrix in general storage,\n' );
  fprintf ( 1, '  R8MAT_FSS factors and solves multiple linear systems.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Matrix order N = %d\n', n );
%
%  Set the matrix.
%
  [ a, seed ] = r8mat_uniform_01 ( n, n, seed );
%
%  Set the desired solutions.
%
  x(1:n,1) = 1.0;
  x(1:n,2) = 1:n;
  x(1:n,3) = mod ( 0 : n - 1, 3 ) + 1;

  b(1:n,1:nb) = a(1:n,1:n) * x(1:n,1:nb);
%
%  Factor and solve the system.
%
  x = r8mat_fss ( n, a, nb, b );

  r8mat_print ( n, nb, x, '  Solution:' );

  return
end


text:
% Generate weight matrix for the task of quadratic matching
function  [W, acceptedPairs] = generateWeightMatrix(M, B, config)

    N = size(M, 2);
    W = -10000*ones(N*N, N*N);
    acceptedPairs = 0;

    % Loop through all possible pairs
    for p=1:N
        for q=1:N
            for s=1:N
                for t=1:N
                    if (p~=s && q~=t)
                        i = p + (q-1)*N;
                        j = s + (t-1)*N;
                        dDiff = abs( distance(M,p,s) - distance(B,q,t));
                        psDist = distance(M, p,s);
                        qtDist = distance(B, q,t);

                        if dDiff <= config.dDiffThresh && psDist >= config.pairDistThresh && qtDist >= config.pairDistThresh
                            W (i,j) = exp(-dDiff);  % can also use 1./dDiff; %
                            acceptedPairs = acceptedPairs + 1;
                        end
                    end
                end
            end
        end
    end

end

author: intellhave

repo: SDRSAC

save_path: github-repos/MATLAB/intellhave-SDRSAC