text:
classdef BOWKMeansTrainer < handle
    %BOWKMEANSTRAINER  KMeans-based class to train visual vocabulary using the bag of visual words approach
    %
    % kmeans-based class for training the *bag of visual words* vocabulary
    % from a set of descriptors.
    %
    % ## Example
    %
    %     % create bag of visual words
    %     trainer = cv.BOWKMeansTrainer(K);
    %     dictionary = trainer.cluster(train_descs);
    %
    %     % Compute histogram of visual word occurrences of an image
    %     extractor = cv.BOWImgDescriptorExtractor('SIFT','BruteForce');
    %     extractor.Vocabulary = dictionary;
    %     descs = extractor.compute(im, keypoints);
    %
    % ## References
    % > "Visual Categorization with Bags of Keypoints" by
    % > Gabriella Csurka, Christopher R. Dance, Lixin Fan, Jutta Willamowski,
    % > Cedric Bray, 2004.
    %
    % See also: cv.BOWKMeansTrainer.BOWKMeansTrainer,
    %  cv.BOWImgDescriptorExtractor, bagOfFeatures
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    methods
        function this = BOWKMeansTrainer(dictionarySize, varargin)
            %BOWKMEANSTRAINER  The constructor
            %
            %     trainer = cv.BOWKMeansTrainer(dictionarySize)
            %     [...] = cv.BOWKMeansTrainer(...,'OptionName', optionValue, ...)
            %
            % ## Input
            % * __dictionarySize__ Number of clusters.
            %
            % ## Options
            % * __Criteria__ The algorithm termination criteria, that is, the
            %   maximum number of iterations and/or the desired accuracy. The
            %   accuracy is specified as `Criteria.epsilon`. As soon as each
            %   of the cluster centers moves by less than `Criteria.epsilon`
            %   on some iteration, the algorithm stops. default
            %   `struct('type','Count+EPS', 'maxCount',100, 'epsilon',eps('float'))`
            % * __Attempts__ The number of times the algorithm is executed
            %   using different initial labelings. The algorithm returns the
            %   labels that yield the best compactness. default 3.
            % * __Initialization__ Method to initialize seeds, default 'PP'.
            %   One of the followings:
            %   * __Random__ Select random initial centers in each attempt.
            %   * __PP__ Use kmeans++ center initialization by
            %     Arthur and Vassilvitskii [Arthur2007].
            %
            % See also: cv.BOWKMeansTrainer, cv.kmeans
            %
            this.id = BOWKMeansTrainer_(0, 'new', dictionarySize, varargin{:});
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     trainer.delete()
            %
            % See also: cv.BOWKMeansTrainer
            %
            if isempty(this.id), return; end
            BOWKMeansTrainer_(this.id, 'delete');
        end

        function descs = getDescriptors(this)
            %GETDESCRIPTORS  Returns a training set of descriptors
            %
            %     descs = trainer.getDescriptors()
            %
            % ## Output
            % * __descs__ a cell array of descriptors
            %
            % See also: cv.BOWKMeansTrainer.descriptorsCount
            %
            descs = BOWKMeansTrainer_(this.id, 'getDescriptors');
        end

        function count = descriptorsCount(this)
            %DESCRIPTORSCOUNT  Returns the count of all descriptors stored in the training set
            %
            %     count = trainer.descriptorsCount()
            %
            % ## Output
            % * __count__ is a numeric value
            %
            % See also: cv.BOWKMeansTrainer.add
            %
            count = BOWKMeansTrainer_(this.id, 'descriptorsCount');
        end

        function add(this, descs)
            %ADD  Adds descriptors to a training set
            %
            %     trainer.add(descs)
            %
            % ## Input
            % * __descs__ Descriptors to add to a training set. Each row of
            %   the descriptors matrix is a descriptor.
            %
            % The training set is clustered using cluster method to construct
            % the vocabulary.
            %
            % See also: cv.BOWKMeansTrainer.cluster
            %
            BOWKMeansTrainer_(this.id, 'add', descs);
        end

        function clear(this)
            %CLEAR  Clear training descriptors
            %
            %     trainer.clear()
            %
            % See also: cv.BOWKMeansTrainer.add
            %
            BOWKMeansTrainer_(this.id, 'clear');
        end

        function centers = cluster(this, descs)
            %CLUSTER  Clusters train descriptors
            %
            %     centers = trainer.cluster()
            %     centers = trainer.cluster(descs)
            %
            % ## Input
            % * __descs__ Descriptors to cluster. Each row of the
            %   descriptors matrix is a descriptor. Descriptors are not added
            %   to the inner train descriptor set.
            %
            % ## Output
            % * __centers__ Row vectors of vocabulary descriptors.
            %
            % The vocabulary consists of cluster centers. So, this method
            % returns the vocabulary. In the first variant of the method,
            % train descriptors stored in the object are clustered. In the
            % second variant, input descriptors are clustered.
            %
            % See also: cv.BOWKMeansTrainer.add, cv.kmeans
            %
            if (nargin > 1)
                centers = BOWKMeansTrainer_(this.id, 'cluster', descs);
            else
                centers = BOWKMeansTrainer_(this.id, 'cluster');
            end
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function k = rbfwhiteKernDiagCompute(kern, t)

% RBFWHITEKERNDIAGCOMPUTE Compute diagonal of RBF-WHITE kernel.
% FORMAT
% DESC computes the diagonal of the kernel matrix for the RBF-WHITE kernel
% given a column vector of inputs.
% ARG kern : the kernel structure for which the kernel matrix is computed.
% ARG t : input data in the form of a column vector.
% RETURN k : a vector of the same size as t containing the diagonal of the
% kernel matrix computed at the given points.
%
% SEEALSO : rbfwhiteKernParamInit, kernDiagCompute, kernCreate,
% rbfwhiteKernCompute
%
% COPYRIGHT : David Luengo, 2009

% KERN

if size(t, 2) > 1
  error('Input can only have one column');
end

if (kern.isStationary == false)
    k = kern.variance/sqrt(8*pi) * erf(kern.inverseWidth*t/sqrt(2));
else
    k = zeros(size(t));
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function PosMove=findpossmoveRec(graph,curr,ts)
%% Written by Muhammet Balcilar, France
% all rights reverved
cf=size(graph,1)/ts;
PosMove=[];
I1=find(graph(curr(1),:)==1);
for i1=1:length(I1)
    nx1=I1(i1);
    g1=graph;
    g1(:,nx1)=0;
    g1(nx1-cf,curr(1)+cf)=0;
    if length(curr)==1
        PosMove=[PosMove;nx1];
    else
        pm=findpossmoveRec(g1,curr(2:end),ts);
        if ~isempty(pm)
            PosMove=[PosMove;nx1*ones(size(pm,1),1) pm];
        end
    end

end

author: balcilar

repo: Multi-Robot-Path-Planning-on-Graphs


text:
function pdf = benford_pdf ( x )

%*****************************************************************************80
%
%% BENFORD_PDF returns the Benford probability of one or more significant digits.
%
%  Discussion:
%
%    Benford's law is an empirical formula explaining the observed
%    distribution of initial digits in lists culled from newspapers,
%    tax forms, stock market prices, and so on.  It predicts the observed
%    high frequency of the initial digit 1, for instance.
%
%    Note that the probabilities of digits 1 through 9 are guaranteed
%    to add up to 1, since
%      LOG10 ( 2/1 ) + LOG10 ( 3/2) + LOG10 ( 4/3 ) + ... + LOG10 ( 10/9 )
%      = LOG10 ( 2/1 * 3/2 * 4/3 * ... * 10/9 ) = LOG10 ( 10 ) = 1.
%
%    PDF(X) = LOG10 ( ( X + 1 ) / X ).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    F Benford,
%    The Law of Anomalous Numbers,
%    Proceedings of the American Philosophical Society,
%    Volume 78, pages 551-572, 1938.
%
%    T P Hill,
%    The First Digit Phenomenon,
%    American Scientist,
%    Volume 86, July/August 1998, pages 358 - 363.
%
%    R Raimi,
%    The Peculiar Distribution of First Digits,
%    Scientific American,
%    December 1969, pages 109-119.
%
%  Parameters:
%
%    Input, integer X, the string of significant digits to be checked.
%    If X is 1, then we are asking for the Benford probability that
%    a value will have first digit 1.  If X is 123, we are asking for
%    the probability that the first three digits will be 123, and so on.
%
%    Output, real PDF, the Benford probability that an item taken
%    from a real world distribution will have the initial digits X.
%
  if ( x <= 0 )
    pdf = 0.0;
  else
    pdf = log10 ( ( x + 1 ) / x );
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function hpdi = hpdi(x, p)
% HPDI - Estimates the Bayesian HPD intervals
%
%   Y = HPDI(X,P) returns a Highest Posterior Density (HPD) interval
%   for each column of X. P must be a scalar. Y is a 2 row matrix
%   where ith column is HPDI for ith column of X.

%   References:
%      [1] Chen, M.-H., Shao, Q.-M., and Ibrahim, J. Q., (2000).
%          Monte Carlo Methods in Bayesian Computation. Springer-Verlag.

% Copyright (C) 2001 Aki Vehtari
%
% This software is distributed under the GNU General Public
% Licence (version 3 or later); please refer to the file
% Licence.txt, included with the software, for details.

if nargin < 2
  error('Not enough arguments')
end

m=size(x,2);
pts=linspace(0.1,99.9-p,20);
pt1=prctile(x,pts);
pt2=prctile(x,p+pts);
cis=abs(pt2-pt1);
[foo,hpdpi]=min(cis);
if m==1
  hpdi=[pt1(hpdpi); pt2(hpdpi)];
else
  hpdpi=sub2ind(size(pt1),hpdpi,1:m);
  hpdi=[pt1(hpdpi); pt2(hpdpi)];
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [] = test_elasticnet()

    clc;
    clear;
    close all;

    %% Set algorithms
    if 0
        algorithms = gd_solver_list('ALL');
    else
        algorithms = {'PG-BKT', 'PG-TFOCS-BKT', 'APG-BKT', 'CD-EasticNet', 'FISTA'};
    end

    %% prepare dataset
    if 1
        % generate synthtic data
        n = 500;
        d = 100;
        A = randn(d,n);
        b = randn(d,1);
        lambda1 = 5;
        lambda2 = 1;
    else
    end

    %% define problem definitions
    problem = elastic_net(A, b, lambda1, lambda2);

    %% initialize
    w_init = rand(n,1);
    w_list = cell(length(algorithms),1);
    info_list = cell(length(algorithms),1);

    %% perform algorithms
    for alg_idx=1:length(algorithms)
        fprintf('\n\n### [%02d] %s ###\n\n', alg_idx, algorithms{alg_idx});

        clear options;
        % general options for optimization algorithms
        options.w_init = w_init;
        options.tol_gnorm = 1e-10;
        options.max_iter = 300;
        options.verbose = true;
        options.f_opt = 0;
        options.store_w = false;

        switch algorithms{alg_idx}
            case {'PG-BKT'}

                options.step_alg = 'backtracking';
                options.step_init_alg = 'bb_init';
                [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options);

            case {'PG-TFOCS-BKT'}

                options.step_alg = 'tfocs_backtracking';
                options.step_init_alg = 'bb_init';
                [w_list{alg_idx}, info_list{alg_idx}] = sd(problem, options);

            case {'APG-BKT'}

                options.step_alg = 'backtracking';
                options.step_init_alg = 'bb_init';
                [w_list{alg_idx}, info_list{alg_idx}] = ag(problem, options);

            case {'APG-TFOCS-BKT'}

                options.step_alg = 'tfocs_backtracking';
                options.step_init_alg = 'bb_init';
                [w_list{alg_idx}, info_list{alg_idx}] = ag(problem, options);

            case {'FISTA'}

                options.sub_mode  = 'FISTA';
                [w_list{alg_idx}, info_list{alg_idx}] = ista(problem, options);

            case {'ADMM-LASSO'}

                options.rho = 0.1;
                [w_list{alg_idx}, info_list{alg_idx}] = admm_lasso(problem, options);

            case {'CD-EasticNet'}

                options.sub_mode = 'elasticnet';
                [w_list{alg_idx}, info_list{alg_idx}] = cd_lasso_elasticnet(problem, options);

            case {'L-BFGS-BKT'}

                options.step_alg = 'backtracking';
                [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options);

            case {'L-BFGS-WOLFE'}

                options.step_alg = 'strong_wolfe';
                [w_list{alg_idx}, info_list{alg_idx}] = lbfgs(problem, options);

            case {'P-Newton-CHOLESKY'}

                options.sub_mode = 'CHOLESKY';
                options.step_init_alg = 'bb_init';
                options.step_alg = 'tfocs_backtracking';
                %options.step_alg = 'backtracking';
                [w_list{alg_idx}, info_list{alg_idx}] = newton(problem, options);

            otherwise
                warn_str = [algorithms{alg_idx}, ' is not supported.'];
                warning(warn_str);
                w_list{alg_idx} = '';
                info_list{alg_idx} = '';
        end

    end

    fprintf('\n\n');

    %% plot all
    close all;

    % display iter vs cost/gnorm
    display_graph('iter','cost', algorithms, w_list, info_list);
    % display iter vs. l1 norm, i.e. the toral number of non-zero elements
    display_graph('iter','reg', algorithms, w_list, info_list);

end

author: hiroyuki-kasai

repo: SGDLibrary


text:
%% RRT*FN Toolbox
% *RRT*FN Toolbox* for solving path/motion planning problems.
% Toolbox provides *RRT*, *RRT** and *RRT*FN* for solving various problems
% (e.g. 2D mobile robot, planar redundant manipulator)
%
% Sampling-based motion planning algorithms got a lot of research attention
% in past decade or so. The main reason of the popularity is an ability
% to solve relatively easy motion planning problems of 2D mobile robot
% as well as hard high dimensional problems both.
%
% *Rapidly-Exporing Random Tree (RRT)* is sampling-based algorithm, solves
% the problem of motion and path planning providing feasible solutions
% however it does not take into account optimality of the solution.
%
% *RRT** is probabilistically optimal variant of RRT which converges to the
% optimal solution asymtotically. Due to the fact that RRT* takes cost of
% the path into consideration, the computational diffuculty increases with
% each node added to tree, a good example of this problem is finding
% neighbors.
%
% *RRT*FN (Fixed Nodes)* is a memory efficient variant of RRT*. It
% inherents all the optimization features of RRT*, but in contrast using
% limited number of nodes i.e. memory is limited.
%
%%
%

% Please do not change anything in rrt.m,
% rrt_star.m and rrt_star_fn.m files unless it is a bug.
Everything
% you want to add (e.g. new function or modifications of a model)
% please do it creating/editing classes for models.
% e.g. FNSimple2D.m or
% FNRedundantManipulator.m
%

%

author: olzhas


text:
function value = problem5 ( x, h, epsilon, o )

%*****************************************************************************80
%
%% PROBLEM5 evaluates problem data for problem 5.
%
%  Discussion:
%
%    case # 5: u_anl  = 1+x, w_anl  =   0
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 February 2012
%
%  Parameters:
%
%    Input, real X(:), the evaluation points.
%
%    Input, real H, the discretization parameter.
%
%    Input, real EPSILON, the nonlocalization parameter.
%
%    Input, string O, the option:
%    'U', evaluate the exact solution.
%    'D', evaluate the derivative of the exact solution.
%    'F', evaluate the right hand side.
%    'L', evaluate the lifting function.
%
  if ( o == 'u' )
    value = 1 + x;
  elseif ( o == 'd' )
    value = ones ( size ( x ) );
  elseif ( o == 'f' )
    value = zeros ( size ( x ) );
  elseif ( o == 'l' )
    value = (x<=0).*(1+x) + ...
            (x>0 & x<=h).* (1-x./h) + ...
            (x>h & x< 1-h).* 0 * epsilon + ...
            (x>=1-h & x<=1).*2.*(1. + (x-1)./h)  + ...
            (x>1).*(1+x);
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'PROBLEM5 - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized option O = "%s"\n', o );
    error ( 'PROBLEM5 - Fatal error!\n' );
  end

  return
end


text:
clc, clear, close all;

%% create data and query
p = rand( 1000, 2 );
tree = kdtree_build(p);
range = [ min( p(1:5,:) ); max( p(1:5,:) ) ]';
idxs = kdtree_range_query( tree, range );

%% visualize
hold on; xlim( [0 1] ); ylim( [0 1] ); axis equal;
plot(p(:,1),p(:,2), '.b');
plot(p(idxs,1), p(idxs,2), 'or');
legend('database', 'range query result');
line( range(1,[1,2]), range(2,[1,1]) ); % lower
line( range(1,[1,2]), range(2,[2,2]) ); % upper
line( range(1,[1,1]), range(2,[1,2]) ); % left
line( range(1,[2,2]), range(2,[1,2]) ); % right

author: intellhave

repo: SDRSAC

save_path: github-repos/MATLAB/intellhave-SDRSAC


text:
% The royal roads function. The chromosome length (i.e. len)
% should be a multiple of 8
function fitness=R1(pop)
[popSize len]=size(pop);
fitness=zeros(popSize,1);
for i=1:8:len
    temp=sum(pop(:,i:i+7),2);
    temp=double(temp==8);
    fitness=fitness+temp*8;
end
fitness=fitness';

author: Sable

repo: mcbench-benchmarks


text:
function [Spos,Sneg,vpos,vneg] = strengths_und_sign(W)
%STRENGTHS_UND_SIGN        Strength and weight
%
%   [Spos Sneg] = strengths_und_sign(W);
%   [Spos Sneg vpos vneg] = strengths_und_sign(W);
%
%   Node strength is the sum of weights of links connected to the node.
%
%   Inputs:     W,              undirected connection matrix with positive
%                               and negative weights
%
%   Output:     Spos/Sneg,      nodal strength of positive/negative weights
%               vpos/vneg,      total positive/negative weight
%
%
%   2011, Mika Rubinov, UNSW

%   Modification History:
%   Mar 2011: Original

n = length(W);              %number of nodes
W(1:n+1:end) = 0;           %clear diagonal
Spos = sum( W.*(W>0));      %positive strengths
Sneg = sum(-W.*(W<0));      %negative strengths

if nargout>2
    vpos = sum(Spos);       %positive weight
    vneg = sum(Sneg);       %negative weight
end


text:
function id = get_official_id(joint_id)
    % Convert the joint id to MPII joint order to official id.
    % my joint: 1-14
    % official: 0-15
    order_to_MPI_official = [9 8 12 11 10 13 14 15 2 1 0 3 4 5];
    id = order_to_MPI_official(joint_id);
end

author: Guanghan

repo: GNet-pose

save_path: github-repos/MATLAB/Guanghan-GNet-pose


text:
function [nlp] = updateDesiredGait(nlp, sys, target_gait)
    domains = sys.Gamma.Nodes.Domain;

    idx = [7:9, 12:14];
    for j=1:numel(domains) %% HECK!!!!!!
        domain = domains{j};
        phase_idx = getPhaseIndex(nlp,sys.Gamma.Nodes.Name{j});
        for i = 1:nlp.Phase(phase_idx).NumNode
            x_star_val = target_gait(j).states.x(idx, i);
            dx_star_val = target_gait(j).states.dx(idx, i);
%             u_star_val = target_gait(j).inputs.u(:,i);
            updateCostProp(nlp.Phase(phase_idx), ['stateDeviation_', domain.Name], i, 'AuxData',...
                {{x_star_val, dx_star_val}});
        end
    end
    nlp.update();
end

author: ayonga

repo: frost-dev

save_path: github-repos/MATLAB/ayonga-frost-dev


text:
function tex_responses = compute_texton_response(im, tim)

if isempty(tim)
    tex_responses = [];
    return;
end

tex_responses = zeros(size(im, 1), size(im, 2), numel(tim));

fims = fbRun(tim, im);

for i = 1:length(fims)
    tex_responses(:, :, i) = abs(fims{i});
end

author: zouchuhang

repo: LayoutNet


text:
function gsp_plot_jft(G,Xhat,param)
%GSP_PLOT_JFT  Plot the magnitude squared of the joint Fourier transform matrix Xhat
%   Usage:  gsp_plot_jft(G,X);
%           gsp_plot_jft(G,X,param);
%
%   Input parameters:
%       G       : Time-Vertex graph structure
%       Xhat    : Joint Time-Vertex Fourier Coefficients Matrix
%       param   : Structure of optional parameters
%   Output parameters:
%       none
%
%   Additional parameters
%   ---------------------
%
%   * *param.dim*       : '2d' for imagesc and '3d' for surf (default 3d)
%   * *param.logscale*  : Use log-scale to visualize the JFT (default 0)
%   * *param.dB*        : Range of plotting in dB for the logscale
%   * *param.fftshift*  : Put zero frequency at center (default 1)
%

% Author: Francesco Grassi, Nathanael

if nargin<3
    param=struct;
end

if ~isfield(param,'dim');      param.dim='3d';end
if ~isfield(param,'logscale'); param.logscale=0; end
if ~isfield(param,'dB');       param.dB = Inf; end
if ~isfield(param,'fftshift'); param.fftshift = 1; end

if isfield(G,'e')
    lambda = G.e;
else
    if isfield(G,'lmax')
        lambda = linspace(0,G.lmax,G.N);
    else
        lambda = linspace(0,G.N,G.N);
    end
end

if param.logscale
    Xhat = 20*log(abs(Xhat)+1);
    maxXhat = max(Xhat(:));
    Xhat(Xhat < (maxXhat-param.dB)) = maxXhat-param.dB;
else
    Xhat=abs(Xhat.^2);
end

if param.fftshift
    omega = gsp_jtv_fa( G,1 );
    Xhat  = fftshift(Xhat,2);
else
    omega = gsp_jtv_fa( G,0 );
end

switch param.dim
    case {2,'2','2d'}
        imagesc(omega,lambda,Xhat);
        set(gca,'YTickLabel','')
        axis xy
        colorbar

    case {3,'3','3d'}
        surf(omega,lambda,Xhat,'linestyle','none');
        view([0 90])
        xlim([min(omega) max(omega)])
        ylim([min(lambda) max(lambda)])

    otherwise
        error('unkown plot method');
end

repo: gspbox


text:
function A = minimum_spanning_tree(C1, C2)
%
% Find the minimum spanning tree using Prim's algorithm.
% C1(i,j) is the primary cost of connecting i to j.
% C2(i,j) is the (optional) secondary cost of connecting i to j, used to break ties.
% We assume that absent edges have 0 cost.
% To find the maximum spanning tree, used -1*C.
% See Aho, Hopcroft & Ullman 1983, "Data structures and algorithms", p 237.

% Prim's is O(V^2). Kruskal's algorithm is O(E log E) and hence is more efficient
% for sparse graphs, but is implemented in terms of a priority queue.

% We partition the nodes into those in U and those not in U.
% closest(i) is the vertex in U that is closest to i in V-U.
% lowcost(i) is the cost of the edge (i, closest(i)), or infinity is i has been used.
% In Aho, they say C(i,j) should be "some appropriate large value" if the edge is missing.
% We set it to infinity.
% However, since lowcost is initialized from C, we must distinguish absent edges from used nodes.

n = length(C1);
if nargin==1, C2 = zeros(n); end
A = zeros(n);

closest = ones(1,n);
used = zeros(1,n); % contains the members of U
used(1) = 1; % start with node 1
C1(find(C1==0))=inf;
C2(find(C2==0))=inf;
lowcost1 = C1(1,:);
lowcost2 = C2(1,:);

for i=2:n
  ks = find(lowcost1==min(lowcost1));
  k = ks(argmin(lowcost2(ks)));
  A(k, closest(k)) = 1;
  A(closest(k), k) = 1;
  lowcost1(k) = inf;
  lowcost2(k) = inf;
  used(k) = 1;
  NU = find(used==0);
  for ji=1:length(NU)
    for j=NU(ji)
      if C1(k,j) < lowcost1(j)
	lowcost1(j) = C1(k,j);
	lowcost2(j) = C2(k,j);
	closest(j) = k;
      end
    end
  end
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
classdef slaveRef < int32

methods

function H = slaveRef(data, hidx)
  global state;

  if (~isfield(state, 'refs'))
    state.refs=cell(1,10);
  end
  if (~isfield(state, 'refs_occupancy'))
    state.refs_occupancy=zeros(1,10);
  end

  if (nargin < 2)
    I=find(state.refs_occupancy == 0);
    if (length(I) == 0)
      hidx = int32(length(state.refs)+1);
    else
      hidx = int32(I(1));
    end
  end

  % generate ref
  H = H@int32(hidx);

  if (nargin < 2)
    % store to global repo
    state.refs{hidx} = data;
    state.refs_occupancy(hidx) = 1;
  end
end

function v = getValue(H)
  global state;
  if (state.refs_occupancy(int32(H)) == 0)
    error('Dereferencing invalid slaveRef.');
  end
  v = state.refs{int32(H)};
end

end % end methods

methods (Static)

function outvar = dereferenceVar(var)

  type=class(var);
  switch (type)
   case 'struct'
    if (length(var) > 1)
      % struct array
      for i=1:length(var)
        outvar(i) = slaveRef.dereferenceVar(var(i));
      end
    else
      % single struct
      fields=fieldnames(var);
      for i=1:length(fields)
        outvar.(fields{i}) = slaveRef.dereferenceVar(var.(fields{i}));
      end
    end

   case 'cell'
    % cell array
    for i=1:length(var)
      outvar{i} = slaveRef.dereferenceVar(var{i});
    end

   case 'slaveRef'
    outvar = var.getValue();

   otherwise
    outvar=var;
  end
end

end % end methods (Static)

end

author: huashiyiqike

repo: LSTM-MATLAB


text:
function test_num = p00_test_num ( )

%*****************************************************************************80
%
%% P00_TEST_NUM returns the number of test problems.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer TEST_NUM, the number of test problems.
%
  test_num = 40;

  return
end


text:
function buffername = onl_writeLslToFile(varargin)
% Open a named LSL stream and write it to disk.
% If no arguments are supplied, a GUI is generated.
% This function requires the BCILAB toolbox (http://sccn.ucsd.edu/wiki/BCILAB)
%
% --------------------------------------------------------------------------------------------------
% Input                  Information
% --------------------------------------------------------------------------------------------------
% StreamName:            LSL stream that should be written to disk
%                        This is the name of the stream.
%                        Possible values: ''
%                        Default value  : 'n/a'
%                        Input Data Type: string
%
% OutputOptions:         Output options
%
%     | FileName:        The file to write to. This may also contain a system or platform-independent path
%                        Input Range  : Unrestricted
%                        Default value: 'data:/lastdata.set'
%                        Input Data Type: string
%
%     | UpdateFrequency: Update frequency
%                        This is the rate at which data is written.
%                        Input Range  : Unrestricted
%                        Default value: 1
%                        Input Data Type: real number (double)
%
%     | StartDelay:      Start-up delay
%                        Delay before real-time processing begins; grace period until file is written.
%                        Input Range  : Unrestricted
%                        Default value: 3
%                        Input Data Type: real number (double)
%
%
%
% See Also: run_writedataset(), run_readlsl()
%
% Tim Mullen, SCCN/INC/UCSD 2013
% Inspired by BCILAB functions by Christian Kothe

% make sure that everything is on the path and LSL is loaded
if ~exist('arg_define','file')
    addpath(genpath(fileparts(mfilename('fullpath')))); end
% make sure that the library is also found if the toolbox is compiled
lib = lsl_loadlib(env_translatepath('dependencies:/liblsl-Matlab/bin'));

% handle default arguments
try
streamnames = find_streams;
catch err
    hlp_handleerror(err);
    streamnames = {''};
end
% handle inputs
opts = arg_define(varargin, ...
        arg({'streamname','StreamName'},streamnames{1},streamnames,'LSL stream that should be written to disk. This is the name of the stream.'), ...
        arg_sub({'outopts','OutputOptions'},{'out_filename','data:/lastdata.set'},@run_writedataset,'Output options','suppress',{'in_stream'}) ...
        );

if isempty(opts.streamname)
    return;
end
if isempty(varargin)
    % bring up GUI dialog if no arguments were passed
    arg_guidialog;
else
    % choose variable names to hold the stream's data (in the base workspace)
    taken = evalin('base','whos(''lsl*'')');
    buffername = genvarname(['lsl_' opts.streamname '_stream'],{taken.name});

    % create local stream to read data from LSL
    run_readlsl('MatlabStream',buffername,'SelectionProperty','name','SelectionValue',opts.streamname);

    % write data to file
    fprintf('Will write stream ''%s'' to %s\n',opts.streamname,env_translatepath(opts.outopts.out_filename));
    fprintf('To end recording, type:\n>> clear %s \n',buffername);
    run_writedataset(opts.outopts,'in_stream',buffername)
end

% find names of streams on the lab network...
function names = find_streams
    streams = lsl_resolve_all(lib,1);
    names = cellfun(@(s)s.name(),streams ,'UniformOutput',false);
    if isempty(names)
        error('There is no stream visible on the network.'); end

end

end

repo: REST


text:
function [X,rho,eta,F] = pnu(A,L,W,b,k,nu,sm)
%PNU "Preconditioned" version of Brakhage's nu-method.
%
% [X,rho,eta,F] = pnu(A,L,W,b,k,nu,sm)
%
% Performs k steps of a `preconditioned' version of Brakhage's
% nu-method for the problem
%    min || (A*L_p) x - b || ,
% where L_p is the A-weighted generalized inverse of L.  Notice
% that the matrix W holding a basis for the null space of L must
% also be specified.
%
% The routine returns all k solutions, stored as columns of
% the matrix X.  The solution seminorm and residual norm are returned
% in eta and rho, respectively.
%
% If nu is not specified, nu = .5 is the default value, which gives
% the Chebychev method of Nemirovskii and Polyak.
%
% If the generalized singular values sm of (A,L) are also provided,
% then pnu computes the filter factors associated with each step and
% stores them columnwise in the matrix F.

% Reference: H. Brakhage, "On ill-posed problems and the method of
% conjugate gradients"; in H. W. Engl & G. W. Groetsch, "Inverse and
% Ill-Posed Problems", Academic Press, 1987.

% Martin Hanke, Institut fuer Praktische Mathematik, Universitaet
% Karlsruhe and Per Christian Hansen, IMM, 06/25/92.

% Set parameters.
l_steps = 3;      % Number of Lanczos steps for est. of || A*L_p ||.
fudge   = 0.99;   % Scale A and b by fudge/|| A*L_p ||.
fudge_thr = 1e-4; % Used to prevent filter factors from exploding.

% Initialization.
if (k < 1), error('Number of steps k must be positive'), end
if (nargin==5), nu = .5; end
[m,n] = size(A); p = size(L,1); X = zeros(n,k);
if (nargout > 1)
  rho = zeros(k,1); eta = rho;
end;
if (nargin==7)
  F = zeros(n,k); Fd = zeros(n,1); s = (sm(:,1)./sm(:,2)).^2;
end
V = zeros(p,l_steps); B = zeros(l_steps+1,l_steps);
v = zeros(p,1);

% Prepare for computations with L_p.
[NAA,x_0] = pinit(W,A,b); x1 = x_0;

% Compute a rough estimate of || A*L_p || by means of a few steps of
% Lanczos bidiagonalization, and scale A and b such that || A*L_p || is
% slightly less than one.
b_0 = b - A*x_0; beta = norm(b_0); u = b_0/beta;
for i=1:l_steps
  r = ltsolve(L,A'*u,W,NAA) - beta*v;
  alpha = norm(r); v = r/alpha;
  B(i,i) = alpha; V(:,i) = v;
  p = A*lsolve(L,v,W,NAA) - alpha*u;
  beta = norm(p); u = p/beta;
  B(i+1,i) = beta;
end
scale = fudge/norm(B); A = scale*A;
if (nargin==7), s = scale^2*s; end

% Prepare for iteration.
x  = x_0;
z  = -scale*b_0;
r  = A'*z;
d1 = ltsolve(L,r);
d  = lsolve(L,d1,W,NAA);
if (nargout>2), x1 = L*x_0; end

% Iterate.
for j=0:k-1

  % Updates.
  alpha = 4*(j+nu)*(j+nu+0.5)/(j+2*nu)/(j+2*nu+0.5);
  beta  = -(j+nu)*(j+1)*(j+0.5)/(j+2*nu)/(j+2*nu+0.5)/(j+nu+1);
  Ad  = A*d; AAd = A'*Ad;
  x   = x - alpha*d;
  r   = r - alpha*AAd;
  rr1 = ltsolve(L,r);
  rr  = lsolve(L,rr1,W,NAA);
  d   = rr - beta*d;
  X(:,j+1) = x;
  if (nargout>1 )
    z = z - alpha*Ad; rho(j+1) = norm(z)/scale;
  end
  if (nargout>2)
    x1 = x1 - alpha*d1; d1 = rr1 - beta*d1;
    eta(j+1) = norm(x1);
  end

  % Filter factors.
  if (nargin==7)
    if (j==0)
      F(:,1) = alpha*s;
      Fd = s - s.*F(:,1) + beta*s;
    else
      F(:,j+1) = F(:,j) + alpha*Fd;
      Fd = s - s.*F(:,j+1) + beta*Fd;
    end
    if (j > 1)
      f = find(abs(F(:,j)-1) < fudge_thr & abs(F(:,j-1)-1) < fudge_thr);
      if ~isempty(f), F(f,j+1) = ones(length(f),1); end
    end
  end

end


text:
rows = 240;
cols = 360;
%fps = 1;
fps = 1/88800;
blk = 5;


text:
classdef MivDefaultStyleSheet
    % MivDefaultStyleSheet. Defines the default styles for GUI components.
    %
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Constant)
        SelectedBackgroundColour = [1.0 0.694 0.392]
        TextPrimaryColour = [1.0 1.0 1.0]
        BackgroundColour = [0, 0, 0]
        TextSecondaryColour = [1.0 0.694 0.392]
        TextContrastColour = [0, 0.129, 0.278]
        IconHighlightColour = [0.7 0.7 0.7]
        IconSelectedColour = [0.6 0.6 0]
        IconHighlightSelectedColour = [1 1 0]
        Font = 'Helvetica'
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function ChannelMat = in_channel_cartool_els(ChannelFile)
% IN_CHANNEL_ELS: Reads a .els file : cartesian coordinates of a set of electrodes, divided in various clusters
%
% USAGE:  ChannelMat = in_channel_els(ChannelFile)
%
% INPUT:
%    - ChannelFile : name of file to open, WITH .ELS EXTENSION
% OUTPUT:
%    - ChannelMat  : Brainstorm channel structure
%
% FORMAT: (.ELS)
%     ASCII file :
%     Format : "ES01<RETURN>"
%              "<nb_electrodes> <RETURN>"
%              "<nb_clusters> <RETURN>"
%              Repeat for each cluster :
%                  "<Cluster_name> <RETURN>"
%                  "<Cluster_number_of_electrodes> <RETURN>"
%                  "<Cluster_type> <RETURN>"
%              End of repeat
%              Repeat for each electrode :
%                  "<X1> <Y1> <Z1> ?<electrode_label>? ?<optional_flag>?<RETURN>"
%              End.
%     Notes :
%     - Cluster_type : could be seen as the dimensionality of the cluster :
%           - 0 for separated electrodes (like auxiliaries), or "points"
%           - 1 for a strip of electrodes, or "line"
%           - 2 for a grid of electrodes, or "array"
%           - 3 for a 3D set of electrodes, usually on the scalp
%     - optional_flag : ignored in this program

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2006-2015

% Initialize output variable
ChannelMat = [];

%% ===== READ ELS FILE =====
% Open file
[fid, message] = fopen(ChannelFile, 'r');
if (fid == -1)
    disp(['BST> Error: Could not open file: ' message]);
    return;
end
% Read magic number
readData = fgetl(fid);
if ~strcmp(readData, 'ES01')
    error('Invalid ELS file.');
end
% Read number of electrodes
Ne = str2num(fgetl(fid));
% Read number of clusters
Nclust = str2num(fgetl(fid));
% Read all clusters
clusterNames  = cell(1,Nclust);
allLoc      = zeros(0,3);
allLabels   = {};
allClusters = {};
allTypes    = {};
for iClust = 1:Nclust
    clusterNames{iClust} = fgetl(fid);
    clusterNchan = str2num(fgetl(fid));
    clusterType  = str2num(fgetl(fid));
    % Skip electrode positions and move to next cluster
    for iChan = 1:clusterNchan
        chanLine = fgetl(fid);
        readData = textscan(chanLine, '%n %n %n %s', 1);
        allLoc(end+1,:) = [readData{1:3}];
        allClusters{end+1} = clusterNames{iClust};
        if isempty(readData{4}) || isempty(readData{4}{1})
            allLabels{end+1} = sprintf('%s%02d', clusterNames{iClust}, iChan);
        else
            allLabels{end+1} = readData{4}{1};
        end
        % Channel type
        switch clusterType
            case 0,    allTypes{end+1} = 'Misc';
            case 1,    allTypes{end+1} = 'SEEG';
            case 2,    allTypes{end+1} = 'ECOG';
            case 3,    allTypes{end+1} = 'EEG';
            otherwise, allTypes{end+1} = 'EEG';
        end
    end
end
% Close file
fclose(fid);

% Verify the expected number of electrodes
% If too many electrodes were read, only keep the first 'Ne' electrodes
readNe = size(allLoc,1);
if (readNe < Ne)
    disp('BST> Warning: Incorrect number of electrodes in file.');
elseif (readNe > Ne)
    allLoc(Ne+1:readNe, :) = [];
    allLabels(Ne+1:readNe, :) = [];
    allClusters(Ne+1:readNe, :) = [];
    allTypes(Ne+1:readNe, :) = [];
end

%% ===== SELECT CLUSTERS =====
% If there are multiple clusters
if (Nclust > 1)
    % Ask user to select clusters
    isSelected = java_dialog('checkbox', 'Select the clusters to import:', 'Import ELS file', [], clusterNames, ones(size(clusterNames)));
    if isempty(isSelected) || ~any(isSelected)
        return;
    end
    % Select only the required sensors
    iChannels = find(ismember(allClusters, clusterNames(isSelected==1)));
else
    iChannels = 1:readNe;
end

%% ===== CONVERT IN BRAINSTORM FORMAT =====
ChannelMat = db_template('channelmat');
ChannelMat.Comment = 'Cartool ELS';
ChannelMat.Channel = repmat(db_template('channeldesc'), 1, length(iChannels));
for i = 1:length(iChannels)
    ChannelMat.Channel(i).Name    = allLabels{iChannels(i)};
    ChannelMat.Channel(i).Comment = '';
    ChannelMat.Channel(i).Type    = allTypes{iChannels(i)};
    ChannelMat.Channel(i).Group   = allClusters{iChannels(i)};
    ChannelMat.Channel(i).Loc     = allLoc(iChannels(i),:)';
    ChannelMat.Channel(i).Orient  = [];
    ChannelMat.Channel(i).Weight  = 1;
end

author: brainstorm-tools


text:
function out = spm_dartel_invnorm(job)
% Warp template to match individuals
% FORMAT spm_dartel_invnorm(job)
% job.flowfields - Filenames of flowfields
% job.images     - Filenames of images to warp
% job.interp     - Interpolation method
% job.K          - 2^K timesteps are used
%
% This function may be useful fo warping labels on to images.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_dartel_invnorm.m 5668 2013-10-03 18:34:18Z guillaume $

PU    = job.flowfields;
PI    = job.images;
intrp = job.interp;
K     = job.K;

for i=1:numel(PU),
    [pth1,nam1,ext1,num1] = spm_fileparts(PU{i});
    NU = nifti(fullfile(pth1,[nam1,ext1]));
    fprintf('%s: ',nam1);
    y  = spm_dartel_integrate(NU.dat,[0 1], K);
    y1 = double(y(:,:,:,1));
    y2 = double(y(:,:,:,2));
    y3 = double(y(:,:,:,3));
    clear y

    for m=1:numel(PI),
        [pth2,nam2,ext2,num2] = spm_fileparts(PI{m});
        NI = nifti(fullfile(pth2,[nam2 ext2]));

        NO = NI;
        NO.dat.fname = fullfile(pth1,['w' nam2 '_' nam1 ext2]);
        NO.dat.dim = [NU.dat.dim(1:3) NI.dat.dim(4:end)];
        NO.mat  = NU.mat0;
        NO.mat0 = NU.mat0;
        NO.mat_intent  = NU.mat0_intent;
        NO.mat0_intent = NU.mat0_intent;
        NO.descrip = 'Warped';
        create(NO);
        fprintf('%s',nam2); drawnow;

        for j=1:size(NI.dat,4),
            mat = NI.mat;
            if ~isempty(NI.extras) && isstruct(NI.extras) && isfield(NI.extras,'mat'),
                mat1 = NI.extras.mat;
                if size(mat1,3) >= j && sum(sum(mat1(:,:,j).^2)) ~=0,
                    mat = mat1;
                end;
            end;

            M   = mat\NU.mat;
            ty1 = M(1,1)*y1 + M(1,2)*y2 + M(1,3)*y3 + M(1,4);
            ty2 = M(2,1)*y1 + M(2,2)*y2 + M(2,3)*y3 + M(2,4);
            ty3 = M(3,1)*y1 + M(3,2)*y2 + M(3,3)*y3 + M(3,4);
            for k=1:size(NI.dat,5),
                for l=1:size(NI.dat,6),
                    f             = NI.dat(:,:,:,j,k,l);
                    spl_param     = [intrp,intrp,intrp,0,0,0];
                    if intrp>1, f = spm_bsplinc(f,spl_param); end;
                    f             = spm_bsplins(f,ty1,ty2,ty3,spl_param);
                    NO.dat(:,:,:,j,k,l) = f;
                    fprintf('\t%d,%d,%d', j,k,l); drawnow;
                    clear f
                end;
            end;
            clear ty1 ty2 ty3
        end;
        fprintf('\n'); drawnow;
    end;
end;

PU    = job.flowfields;
PI    = job.images;
out.files = cell(numel(PU),numel(PI));
for i=1:numel(PU),
    [pth1,nam1,ext1,num1] = spm_fileparts(PU{i});
    for m=1:numel(PI),
        [pth2,nam2,ext2,num2] = spm_fileparts(PI{m});
        fname = fullfile(pth1,['w' nam2 '_' nam1 ext2]);
        out.files{i,j} = fname;
    end
end


text:
function A = uplus(A)
%UPLUS        Long unary plus  +A
%
%

% written  12/30/98     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
%

repo: OpenMAS


text:
% Ini_Manager(fileName, raw_data)
%
% =========================================================================
%   OBJECT Ini_Manager
% =========================================================================
%
% DESCRIPTION:
%   Object to create / read / modify an ini file
%
% EXTENDS: Ini_Reader
%
% INI EXAMPLE:
%   [Section 1]
%       array = [1 2 3]
%       string = "I'm a string"
%       stringCellArray = ["I" "am" "a string cell" "array"]
%   ; I'm a comment
%   # I'm also a comment
%   [Section 2]
%       number = 10
%   [Section n]     # comment
%       double = 10.4
%
% REQUIRES:
%   log:     Logger Class
%   cprintf:    http://www.mathworks.com/matlabcentral/fileexchange/24093-cprintf-display-formatted-colored-text-in-the-command-window
%

%--------------------------------------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:        Andrea Gatti
%  Contributors:      Andrea Gatti, ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%    This program 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.
%
%    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

classdef Ini_Manager < handle

    properties (Constant, GetAccess = 'private')
        STD_COMMENT  = '#';       % Character Identifying the start of a comments
    end

    properties (GetAccess = 'private', SetAccess = 'private')
        log = Logger.getInstance();        % Handler to the log object
        raw_data = {};                 % Cell array containing the file, each cell is a line
    end

    properties (GetAccess = 'public', SetAccess = 'protected')
        c_comment  = [';', Ini_Manager.STD_COMMENT];  % Character Identifying the start of a comments
        file_name = 'config.ini';         % Name (and full path) of the ini
        fid = 0;                          % Handle of the ini file
        rw = 'r';                         % File access mode (r/w)
        read_status = false;              % Flag of reading status

        % Structure containing the data: section -> name / ( key -> (name / data )
        section = {};
        %section{1}.name = 'Section Name';
        %section{1}.key = {};
        %section{1}.key{1}.name = 'Key name';
        %section{1}.key{1}.data = 100;
    end

    % =========================================================================
    %    STANDARD METHODS
    % =========================================================================
    methods

        % Creator ---------------------------------------------------------
        function this = Ini_Manager(file_name, raw_data)
        % Creator of the class
        % SYNTAX:  Ini_Manager(<file_name>, <raw_data>) creator
            if (nargin == 0)
                file_name = '';
            end
            if isempty(file_name)
                file_name = '';
            end

            if (nargin == 1) && iscell(file_name) % ---------------- Parse RAW but do not save it
                this.setFileName('');
                this.raw_data = file_name;
                this.setRW('w');
                this.cleanRaw();
                this.parseData();
                this.setReadStatus(true)
                this.raw_data = {};
            elseif (nargin == 2) % --------------------------------- Parse and save RAW
                this.setFileName(file_name);
                this.raw_data = raw_data;
                this.setRW('w');
                this.writeFile();
                this.cleanRaw();
                this.parseData();
                this.setReadStatus(true)
                this.raw_data = {};
            else
                this.setFileName(file_name);
            end
        end

        % Destructor ------------------------------------------------------
        function delete(this) %#ok<INUSD>
            % Empty Destructor
        end

        % Cleaner ---------------------------------------------------------
        function clearAll(this)
            % Reset the object
            this.fid = 0;
            this.rw = 'r';
            this.file_name = 'config.ini';
            this.raw_data = {};
            this.section = {};
        end

    end

    % =========================================================================
    %  FILE
    % =========================================================================
    methods

        % Set file name ---------------------------------------------------
        function setFileName(this, file_name)
            % Set the complete path of the ini file
            this.file_name = file_name;
        end

        % Get file name ---------------------------------------------------
        function file_name = getFileName(this)
            % Get the complete path of the ini file
            file_name = this.file_name;
        end

    end

    % =========================================================================
    %  INI SYNTAX
    % =========================================================================
    methods

        % Set Comment Character -------------------------------------------
        function setCommentChar(this, character)
            % define the characters that define comment lines
            this.c_comment = unique([character this.STD_COMMENT]);
        end

        % Get Comment Character -------------------------------------------
        function characters = getCommentChar(this)
            % Get the characters that define comment lines
            characters = this.c_comment;
        end

    end

    % =========================================================================
    %  R/W MODES OF THE FILE
    % =========================================================================
    methods

        % Set RW mode -----------------------------------------------------
        function setRW(this,rwMode)
            % Set mode for open the ini file
            if ( ~this.readMode() && ~writeMode())
                this.rw = 'r';
            else
                this.rw = rwMode;
            end
        end

        % Get RW mode -----------------------------------------------------
        function rwMode = getRW(this)
            % Get the current mode of the file
            rwMode = this.rw;
        end

        % Read mode? ------------------------------------------------------
        function bool = readMode(this)
            % Is it in read mode?
            if ((this.rw(1)=='r'))
                bool = true;
            else
                bool = false;
            end
        end

        % Write mode? -----------------------------------------------------
        function bool = writeMode(this)
            % Is it in write mode?
            if ((this.rw(1)=='w'))
                bool = true;
            else
                bool = false;
            end
        end

        % Get read status mode --------------------------------------------
        function bool = getReadStatus(this)
            % Return if the file has been already parsed
            bool = this.read_status;
        end

        % Read File -------------------------------------------------------
        function status = readFile(this)
            % Force reading of the File
            status = true;
            % If the object already contains data - clean it
            if (this.getReadStatus())
                this.raw_data = {};
            end
            if ~exist(this.getFileName(),'file')
                this.log.addError(sprintf('INI reading of file "%s" failed', this.getFileName()))
                status = false;
            else
                this.fid = fopen(this.getFileName(), this.getRW());

                if (this.fid ~= -1)   % If reading is ok
                    this.raw_data = textscan(this.fid, '%s', 'delimiter', '\n', 'endOfLine', '\r\n');
                    fclose(this.fid);

                    this.read_status = true;
                    this.raw_data = this.raw_data{1};

                    this.log.addStatusOk('The INI file has been parsed correctly.', 15);

                    this.cleanRaw();      % Strip comments and spaces
                    this.parseData();     % Parse file
                    this.raw_data = {};   % clean RAW temp data
                else
                    this.log.addError(['INI file read failed:' ferror(this.fid)]);
                    this.setReadStatus(false);
                    this.raw_data = {};
                end
            end
        end

        % Write File ------------------------------------------------------
        function errStatus = writeFile(this)
            % Force reading of the File
            errStatus = false;
            if isempty(this.getFileName())
                this.log.addError(sprintf('INI writing  of file "%s" failed', this.getFileName()));
                errStatus = true;
            else
                if (this.fid ~= -1)   % If file access is ok
                    try
                        this.fid = fopen(this.getFileName(), this.getRW());
                        % Convert raw data to string
                        tmp_str = '';
                        for i = 1 : numel(this.raw_data)
                            tmp_str = [tmp_str this.raw_data{i} 10]; %#ok<AGROW>
                        end
                        fwrite(this.fid, tmp_str);
                        fclose(this.fid);
                    catch ex
                        errStatus = true;
                        this.log.addError(['INI file cannot be written (' this.file_name '): ' ex.message]);
                    end

                    this.log.addStatusOk('The INI file has been writted correctly', 10);
                else
                    this.log.addError(['INI file write failed:' ferror(this.fid)]);
                end
            end
        end

        % Update File (when needed) ---------------------------------------
        function reloaded = update(this, file_name, force_read)
            % Update the object when needed:
            %  - file_name changed
            %  - force flag == 1
            %  - INI not yet read
            if nargin == 2
                force_read = 0;
            end
            reloaded = 0;
            if (~strcmp(file_name,this.getFileName) || (force_read == 1) || ~this.getReadStatus())
                this.setFileName(file_name);
                this.readFile();
                reloaded = 1;
            end
        end

    end

    % =========================================================================
    %  SEARCH FUNCTIONS
    % =========================================================================
    methods

        % Search a section in the object Ini_Manager ----------------------
        function isPresent = containsSection(this, section)
            % Search a section in the object Ini_Manager
            s = 1;
            while ((s<=length(this.section)) && (s ~= 0))
                if (strcmp(this.section{s}.name,section))
                    s = 0;
                else
                    s = s + 1;    % go on with the search of the section
                end
            end
            if (s == 0)
                isPresent = true;
            else
                isPresent = false;
            end
        end

        % Search a key in the object Ini_Manager --------------------------
        function isPresent = containsKey(this, section, key)
            % Search a key in the object Ini_Manager
            s = 1;
            while ((s<=length(this.section)) && (s ~= 0))
                if (strcmp(this.section{s}.name,section))
                    while ((k<=length(this.section{s}.key)) && (k ~= 0))
                        if (strcmp(this.section{s}.key{k}.name,key))
                            k = 0;
                        else
                            k = k + 1;
                        end
                    end
                    s = 0;
                else
                    s = s + 1;    % go on with the search of the section
                end
            end
            if (k == 0)
                isPresent = true;
            else
                isPresent = false;
            end
        end

    end

    % =========================================================================
    %  GETTER OF THE PARAMETERS
    % =========================================================================
    methods

        % Get the list of sections present in the file --------------------
        function section_list = getSections(this)
            % Get the list of available sections
            if (~this.getReadStatus())
                %this.printWarning('File not yet read!\n');
                this.readFile();
            end

            section_list = cell(length(this.section),1);
            for s=1:length(this.section)
                section_list{s} = this.section{s}.name;
            end
        end

        % Return the presence of a section --------------------------------
        function isS = isSection(this, section)
            % Get the presence of a section
            s = 1;
            while ((s<=length(this.section)) && (s ~= 0))
                if (strcmp(this.section{s}.name,section))
                    s = 0;      % Stop searching
                else
                    s = s+1;    % go on with the search of the section
                end
            end
           isS = s == 0;
        end

        % Return the presence of a key ------------------------------------
        function isK = isKey(this, section, key)
            % Get the presence of a key
            s = 1;
            k = 1;
            while ((s<=length(this.section)) && (s ~= 0))
                if (strcmp(this.section{s}.name,section))
                    k = 1;
                    while ((k<=length(this.section{s}.key)) && (k ~= 0))
                        if (strcmp(this.section{s}.key{k}.name,key))
                            k = 0;
                        else
                            k = k + 1;
                        end
                    end
                    s = 0;
                else
                    s = s + 1;    % go on with the search of the section
                end
            end
            isK = k == 0;
        end

        % Get the list of keys present in the file ------------------------
        function key_list = getKeys(this, section)
            % Get the list of the keys available
            if (nargin == 1)
                section = 0;
            end

            if (~this.getReadStatus())
                %this.printWarning('File not yet read!\n');
                this.readFile();
            end

            key_list = {};
            l = 1;
            if (section == 0)
                for s = 1:length(this.section)
                    for p = 1 : length(this.section{s}.key)
                        key_list{l} = this.section{s}.key{p}.name; %#ok<AGROW>
                        l = l+1;
                    end
                end
            else
                s = 1;
                while ((s<=length(this.section)) && (s ~= 0))
                    if (strcmp(this.section{s}.name,section))
                        for p = 1:length(this.section{s}.key)
                            key_list{l} = this.section{s}.key{p}.name; %#ok<AGROW>
                            l = l+1;
                        end
                        s = 0;      % Stop searching
                    else
                        s = s+1;    % go on with the search of the section
                    end
                end
            end
        end

        % Get data --------------------------------------------------------
        function data = getData(this, section, key)
            % Get the value of a specified key
            if (~this.getReadStatus() && isempty(this.section))
               %this.printWarning('File not yet read!\n');
               this.readFile();
            end
            found = false;
            data = [];
            if (nargin == 2)
                key = section;
                % Search the key among all the sections
                s = 1;
                while ((s<=length(this.section)) && (s > 0))
                    p = 1;
                    while ((p <= length(this.section{s}.key)) && (p ~= 0))
                        if (strcmp(this.section{s}.key{p}.name,key))
                            data = this.section{s}.key{p}.data;
                            found = true;
                            p = 0;      % Stop searching key
                        else
                            p = p+1;    % go on with the search of the key
                        end
                    end
                    if (p == 0)
                        s = 0;     % Stop searching section
                    else
                        s = s+1;   % go on with the search of the section
                    end
                end
                if ~found
                    this.log.addWarning(['Key "' key '" not found while reading: "' this.file_name '"'], 10);
                    data = [];
                end
            else
                % Search the key of a specific section
                s = 1;
                while ((s<=length(this.section)) && (s > 0))
                    if (strcmp(this.section{s}.name,section))
                        p = 1;
                        while ((p <= length(this.section{s}.key)) && (p ~= 0))
                            if (strcmp(this.section{s}.key{p}.name,key))
                                data = this.section{s}.key{p}.data;
                                found = true;
                                p = 0; % Stop searching key
                            else
                                p = p+1;    % go on with the search of the key
                            end
                        end
                        s = 0;      % Stop searching section
                    else
                        s = s+1;    % go on with the search of the section
                    end
                end
                if ~found
                    this.log.addWarning(['Key "' key '" not found in section "' section '" while reading: "' this.file_name '"'], 100);
                    data = [];
                end
            end

        end

    end

    % =========================================================================
    %  MODIFIER FUNCTIONS
    % =========================================================================
    methods

        % Add a new section to the object ---------------------------------
        function addSection(this, new_section)
            % Add a new section to the object
            if ~this.isSection(new_section)
                newId = length(this.section)+1;
                this.section{newId}.name = new_section;
                this.section{newId}.key = {};
            end
        end

        % Add a new keys to the object ------------------------------------
        function addKey(this, section, key, data)
            % Add a new key to the object if the section exist
            if this.isKey(section, key)
                this.editKey(section, key, data);
            else
                s = 1;
                while ((s<=length(this.section)) && (s ~= 0))
                    if (strcmp(this.section{s}.name,section))
                        newId = length(this.section{s}.key)+1;
                        this.section{s}.key{newId}.name = key;
                        this.section{s}.key{newId}.data = data;
                        s = 0;
                    else
                        s = s+1;    % go on with the search of the section
                    end
                end
                if (s ~= 0)
                    this.printError(['Section "' section '" not found!\n']);
                end
            end
        end

        % Add a data to the object giving key and section -----------------
        function addData(this, section, key, data)
            % Add a data to the object an eventually create the section and key to store it
            this.addSection(section)
            this.addKey(section, key, data)
        end

        % Remove a section from the object Ini_Manager --------------------
        function rmSection(this, section)
            % Remove a section from the object Ini_Manager
            s = 1;
            while ((s<=length(this.section)) && (s ~= 0))
                if (strcmp(this.section{s}.name,section))
                    this.section(s) = [];
                    s = 0;
                else
                    s = s+1;    % go on with the search of the section
                end
            end
            if (s ~= 0)
                this.printError(['Section "' section '" not found!\n']);
            end
        end

        % Remove a key from the object Ini_Manager ------------------------
        function rmKey(this, section, key)
            % Remove a key from the object Ini_Manager
            s = 1;
            k = 1;
            while ((s<=length(this.section)) && (s ~= 0))
                if (strcmp(this.section{s}.name,section))
                    k = 1;
                    while ((k<=length(this.section{s}.key)) && (k ~= 0))
                        if (strcmp(this.section{s}.key{k}.name,key))
                            this.section{s}.key(k) = [];
                            k = 0;
                        else
                            k = k + 1;
                        end
                    end
                    s = 0;
                else
                    s = s + 1;    % go on with the search of the section
                end
            end
            if (k ~= 0)
                this.printError(['Key "' key '" not found!\n']);
            end
        end

        % Edit a key in the object Ini_Manager ----------------------------
        function editKey(this, section, key, data)
            this.setData(section, key, data)
        end

        function setData(this, section, key, data)
            % Edit a key in the object Ini_Manager
            s = 1;
            k = 1;
            if (nargin == 3)
                data  = key;
                key = section;
                % Search the key among all the sections
                while ((s<=length(this.section)) && (s > 0))
                    p = 1;
                    while ((p <= length(this.section{s}.key)) && (p ~= 0))
                        if (strcmp(this.section{s}.key{p}.name,key))
                            this.section{s}.key{p}.data = data;
                            p = 0;      % Stop searching key
                        else
                            p = p+1;    % go on with the search of the key
                        end
                    end
                    if (p == 0)
                        s = 0;     % Stop searching section
                    else
                        s = s+1;   % go on with the search of the section
                    end
                end
                if (isempty(data))
                    this.log.addWarning(['Key "' key '" not found while reading: "' this.file_name '"'], 10);
                end
            else
                while ((s<=length(this.section)) && (s ~= 0))
                    if (strcmp(this.section{s}.name,section))
                        k = 1;
                        while ((k<=length(this.section{s}.key)) && (k ~= 0))
                            if (strcmp(this.section{s}.key{k}.name,key))
                                this.section{s}.key{k}.data = data;
                                k = 0;
                            else
                                k = k + 1;
                            end
                        end
                        s = 0;
                    else
                        s = s + 1;    % go on with the search of the section
                    end
                end
                if (k ~= 0)
                    this.log.addWarning(['Key "' key '" not found while reading: "' this.file_name '"'], 10);
                end
            end
        end

    end

    % =========================================================================
    %  VISUALIZATION FUNCTIONS (not using LOGGER) - for DEBUG
    % =========================================================================
    methods

        % List Sections ---------------------------------------------------
        function listSections(this, color_mode)
            % List the list of available sections
            if (nargin == 1)
                color_mode = this.log.getColorMode();
            end

            if (~this.getReadStatus())
                %this.printWarning('File not yet read!\n');

                this.readFile();
            end

            fprintf('        List of sections:\n')
            for s=1:length(this.section)
                this.printSection(this.section{s}.name, color_mode);
            end
        end

        % List Key --------------------------------------------------------
        function listKeys(this, section, color_mode)
            % List the list of the keys available
            if (nargin == 1)
                section = 0;
                color_mode = this.log.getColorMode();
            end
            if (nargin == 2)
                if (ischar(section))
                    color_mode = this.log.getColorMode();
                else
                    color_mode = section;
                    section = 0;
                end
            end

            if (~this.getReadStatus() && isempty(this.section))
                %this.printWarning('File not yet read!\n');
                this.readFile();
            end

            if (section == 0)
                fprintf('        List of all the keys:\n')
                for s = 1:length(this.section)
                    this.printSection(this.section{s}.name, color_mode);
                    for p = 1:length(this.section{s}.key)
                        this.printData(this.section{s}.key{p}.name, this.section{s}.key{p}.data, color_mode)
                    end
                end
            else
                fprintf('        List of all the keys in section "%s":\n', section)
                s = 1;
                while ((s<=length(this.section)) && (s ~= 0))
                    if (strcmp(this.section{s}.name,section))
                        this.printSection(this.section{s}.name, color_mode);
                        for p = 1:length(this.section{s}.key)
                            this.printData(this.section{s}.key{p}.name, this.section{s}.key{p}.data, color_mode)
                        end
                        s = 0;      % Stop searching
                    else
                        s = s+1;    % go on with the search of the section
                    end
                end
            end
        end

        % Show data -------------------------------------------------------
        function showData(this, section, color_mode)
            % List the data contained in the ini
            if (nargin == 1)
                section = 0;
                color_mode = this.log.getColorMode();
            end
            if (nargin == 2)
                if (ischar(section))
                    color_mode = this.log.getColorMode();
                else
                    color_mode = section;
                    section = 0;
                end
            end

            if (~this.getReadStatus())
                %this.printWarning('File not yet read')
                this.readFile();
            end

            if (section == 0)
                fprintf('        List of all the key values:\n')
                for s = 1:length(this.section)
                    this.printSection(this.section{s}.name, color_mode);
                    for p = 1:length(this.section{s}.key)
                        this.printData(this.section{s}.key{p}.name, this.section{s}.key{p}.data, color_mode)
                    end
                end
            else
                fprintf('        List of all the key values in section "%s":\n', section)
                s = 1;
                while ((s <= length(this.section)) && (s ~= 0))
                    if (strcmp(this.section{s}.name,section))
                        this.printSection(this.section{s}.name, color_mode);
                        for p = 1:length(this.section{s}.key)
                            this.printData(this.section{s}.key{p}.name, this.section{s}.key{p}.data, color_mode)
                        end
                        s = 0;      % Stop searching
                    else
                        s = s+1;    % go on with the search of the section
                    end
                end
            end
        end

    end

    % =========================================================================
    %   CUSTOM DISPLAY UTILITIES (not using LOGGER) - for DEBUG
    % =========================================================================

    methods (Access = 'protected')

        % Display a Section -----------------------------------------------
        function printSection(this, section, color_mode)
            % Display a sections on a tree
            if (nargin == 2)
                color_mode = this.color_mode;
            end
            if (color_mode)
                cprintf('blue','         - ');
                cprintf('text', '"%s"\n', section);
            else
                fprintf('         - "%s"\n', section);
            end
        end

        % Display a Key ---------------------------------------------------
        function printKey(this, key, color_mode)
            % Display a key on a tree
            if (nargin == 2)
                color_mode = this.color_mode;
            end
            if (color_mode)
                cprintf('blue','             |- ');
                cprintf('text', '"%s"\n', key);
            else
                fprintf('             |- "%s"\n', key);
            end
        end

        % Display a Key ---------------------------------------------------
        function printData(this, key, data, color_mode)
            % Display the data of a key
            if (nargin == 3)
                color_mode = this.color_mode;
            end
            if (color_mode)
                cprintf('blue','             |- ');
                tmpData = data;
                if (iscell(tmpData))    % The only dataset that can be a cell array is an array of strings
                    cprintf('text','"%s" = [', key);
                    for l = 1:size(tmpData,2)
                        cprintf('text', ' "%s"', tmpData{l});
                    end
                    cprintf('text', ' ]\n');
                else
                    % if it is not an array of string...
                    if (ischar(tmpData))
                        cprintf('text','"%s" = "%s"\n',key, tmpData);
                    else
                        cprintf('text','"%s" = %s\n',key, num2str(tmpData));
                    end
                end
            else
                tmpData = data;
                if (iscell(tmpData))    % The only dataset that can be a cell array is an array of strings
                    fprintf('             |- "%s" = [', key);
                    for l = 1:size(tmpData,2)
                        fprintf(' "%s"', tmpData{l});
                    end
                    fprintf(' ]\n');
                else
                    % if it iks not an array of string...
                    if (ischar(tmpData))
                        fprintf('             |- "%s" = "%s"\n',key, num2str(tmpData));
                    else
                        fprintf('             |- "%s" = %s\n',key, num2str(tmpData));
                    end
                end
            end
        end

    end

    % =========================================================================
    %    PRIVATE UTILITIES
    % =========================================================================
    methods (Access = 'private')

        % Strip empty/comment lines ---------------------------------------
        function cleanRaw(this)
            % Strip empty lines
            this.raw_data((cellfun(@length, this.raw_data)==0)) = [];
            % Strip commented lines
            r = 1;
            while (r <= length(this.raw_data))
                if ismember(this.raw_data{r}(1), this.c_comment)
                    this.raw_data(r) = [];
                else
                    r = r + 1;
                end
            end

            for r=1:length(this.raw_data)
                % Strip inline comments

                start = regexp(this.raw_data{r}, ['([' this.c_comment ']).*'], 'start');
                if (~isempty(start))
                    this.raw_data{r}(start:end) = [];
                end

                start = regexp(this.raw_data{r}, ' *$', 'start');
                if (~isempty(start))
                    this.raw_data{r}(start:end) = [];
                end
            end
        end

        % Parse the file (cleaned) ----------------------------------------
        function parseData(this)
            p = 0;
            s = 0;
            this.section = {};
            for r=1:length(this.raw_data)
                section_name = regexp(this.raw_data{r}, '(?<=^\[).*(?=\])', 'match');
                if (~isempty(section_name))
                    % we have a new SECTION!
                    s = s+1;
                    p = 0;
                    this.section{s}.name = section_name{1};
                    this.section{s}.key = [];
                else
                    % maybe this line contains a key, let's check
                    par_name = regexp(this.raw_data{r}, '^(.*(?=\s\=))', 'match');
                    if (isempty(par_name))
                        par_name = regexp(this.raw_data{r}, '^(.*(?=\=))', 'match');
                    end
                    if (~isempty(par_name))
                        % we have a PARAMETER!
                        p = p+1;
                        if (s == 0)
                            s = s + 1;
                            this.section{s}.name = 'Section';
                            this.section{s}.key = [];
                        end
                        this.section{s}.key{p}.name = par_name{1};
                        this.section{s}.key{p}.data = Ini_Manager.str2value(this.raw_data{r});
                    end
                end
            end
        end

        % Set read status -------------------------------------------------
        function setReadStatus(this, bool)
            this.read_status = bool;
        end
    end

    % =========================================================================
    %  STATIC STRING GENERATION FROM INI TO STR
    % =========================================================================

    methods (Static)

        % str2value -------------------------------------------------------
        function value = str2value(raw_data)
            % Get the DATA!
            str_data = regexp(raw_data, '(?<=\=).*', 'match');
            if (isempty(str_data))
                value = [];
            else
                tmpData = str2num(str_data{1}); %#ok<ST2NM>
                if (~isempty(tmpData) && isnumeric(tmpData))   % It's a number!
                    value = tmpData;
                else
                    % It's a string!
                    % If it is a string properly formatted "string data"
                    tmpData = regexp(str_data{1}, '(?<=\")[^"]*(?=\")', 'match');
                    if (~isempty(tmpData))
                        if (size(tmpData,2) == 1)
                            value = tmpData{1};
                        else
                            % Strip empty cells
                            tmpData((cellfun(@length, tmpData)==0)) = [];
                            % Strip space only cells
                            for c=size(tmpData,2):-1:1
                                if isempty(regexp(tmpData{c}, '[^ ]*', 'match'))
                                    tmpData(c) = [];
                                end
                            end
                            value = tmpData;
                        end
                    else
                        % If it appears to be an empty string
                        value = '';
                    end
                end
            end
        end

        % cellStringtoString ----------------------------------------------
        function str = strCell2Str(value)
            % Converta cell of string to string
            % SYNTAX:
            %   str = strCell2Str(value)
            if ~isempty(value)
                if ~iscell(value)
                    value = {value};
                end
                str = strcat('"', value{1}, '"');
                for i = 2 : numel(value)
                    str = strcat(str, ' "', value{i}, '"');
                end
            else
                str = '[]';
            end
        end

        % toIniString -----------------------------------------------------
        function cell_str = toIniString(variable_name, value, format, cell_str)
            % Convert any variable to ini string format
            % SYNTAX:
            %   cell_str = toIniString(variable_name, value)
            %   cell_str = toIniString(variable_name, value, format)
            %   cell_str = toIniString(variable_name, value, cell_str)
            %   cell_str = toIniString(variable_name, value, format, cell_str)
            switch nargin
                case 1
                    error('Error in Ini_Manager.toIniString, too few parameters');
                case 2

                    format = '';
                    cell_str = {};
                case 3
                    if iscellstr(format)
                        cell_str = format;
                        format = '%g';
                    else
                        cell_str = {};
                    end
                case 4
                    % ok
            end

            if ischar(value) % is string
                cell_str{numel(cell_str) + 1} = [variable_name ' = "' value(:)' '"'];
            elseif isnumeric(value)
                if isempty(format)
                    format = '%g';
                else
                    format = strtrim(format);
                end
                if numel(value) > 1 % it's an array of values
                    format = [format ' '];
                    tmp = sprintf(format,value);
                    cell_str{numel(cell_str) + 1} = [variable_name ' = [' tmp(1:end-1) ']'];
                    clear tmp;
                else
                    cell_str{numel(cell_str) + 1} = [variable_name ' = ' sprintf(format,value)];
                end
            else % generic converter (may not work properly)
                toString = @(var) strtrim(regexprep(evalc('disp(var)'), '\n', ''));
                if iscell(value)
                    if ~isempty(value) && ischar(value{1})
                        cell_str{numel(cell_str) + 1} = [variable_name ' = [' Ini_Manager.strCell2Str(value) ']'];
                    else
                        cell_str{numel(cell_str) + 1} = [variable_name ' = [' toString(value) ']'];
                    end
                else
                    cell_str{numel(cell_str) + 1} = [variable_name ' = ' toString(value)];
                end
            end

            % I want a column array
            if size(cell_str,1) < size(cell_str,2)
                cell_str = cell_str';
            end
        end

        % toIniString Section ---------------------------------------------
        function cell_str = toIniStringSection(section_name, cell_str)
            % Add a section in ini string format
            % SYNTAX:
            %   cell_str = toIniStringSection(section_name, cell_str)
            if (nargin == 1)
                cell_str = {};
            end

            cell_str{numel(cell_str) + 1} = [Ini_Manager.STD_COMMENT '----------------------------------------------------------------------------------'];
            cell_str{numel(cell_str) + 1} = ['[' section_name ']'];
            cell_str{numel(cell_str) + 1} = [Ini_Manager.STD_COMMENT '----------------------------------------------------------------------------------'];

            % I want a column array
            if size(cell_str,1) < size(cell_str,2)
                cell_str = cell_str';
            end
        end

        % toIniString Comment ---------------------------------------------
        function cell_str = toIniStringComment(comment, cell_str)
            % Add a comment in ini string format
            % SYNTAX:
            %   cell_str = toIniStringComment(comment, cell_str)
            if (nargin == 1)
                cell_str = {};
            end
            line_lim = strfind(comment, 10);
            line_lim = [[1; line_lim'] [line_lim'; numel(comment)]];
            for i = 1 : size(line_lim, 1)
                cell_str{numel(cell_str) + 1} = [ Ini_Manager.STD_COMMENT ' ' strrep(comment(line_lim(i, 1) : line_lim(i, 2)), char(10), '')];
            end

            % I want a column array
            if size(cell_str,1) < size(cell_str,2)
                cell_str = cell_str';
            end
        end

        % toIniString New Line --------------------------------------------
        function cell_str = toIniStringNewLine(cell_str)
            % Add a new line in ini string format
            % SYNTAX:
            %   cell_str = toIniStringSection(section_name, cell_str)
            if (nargin == 0)
                cell_str = {};
            end
            cell_str{numel(cell_str) + 1} = '';

            % I want a column array
            if size(cell_str,1) < size(cell_str,2)
                cell_str = cell_str';
            end
        end
    end
end

author: goGPS-Project


text:
function i4mat_u1_inverse_test ( )

%*****************************************************************************80
%
%% I4MAT_U1_INVERSE_TEST tests I4MAT_U1_INVERSE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 April 2009
%
%  Author:
%
%    John Burkardt
%
  n = 6;
%
%  Each row of this definition is a COLUMN of the matrix.
%
  a = [ ...
    1,  0,  0,  0,  0,  0; ...
    2,  1,  0,  0,  0,  0; ...
    0,  0,  1,  0,  0,  0; ...
    5,  0,  3,  1,  0,  0; ...
    0,  0,  0,  0,  1,  0; ...
   75,  0,  0,  6,  4,  1 ]';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'I4MAT_U1_INVERSE_TEST\n' );
  fprintf ( 1, '  I4MAT_U1_INVERSE inverts a unit upper triangular matrix.\n' );

  i4mat_print ( n, n, a, '  The original matrix:' );

  b = i4mat_u1_inverse ( n, a );

  i4mat_print ( n, n, b, '  The inverse matrix:' );

  c(1:n,1:n) = a(1:n,1:n) * b(1:n,1:n);

  i4mat_print ( n, n, c, '  The product:' );

  return
end


text:
function [P]=tesSmooth(TES,V,IND_V,cPar)

% function [P]=tesSmooth(TES,V,IND_V,cPar)
% ------------------------------------------------------------------------
%
%
% Kevin Mattheus Moerman
% kevinmoerman@hotmail.com
% 2014/06/02
%------------------------------------------------------------------------

%%

%Get/set method
if isfield(cPar,'Method')
    smoothMethod=cPar.Method;
else
    smoothMethod='LAP'; %DEFAULT
end

%Smooth
switch smoothMethod
    case 'LAP'
        [P]=tesSmooth_LAP(TES,V,IND_V,cPar);
    case 'HC'
        [P]=tesSmooth_HC(TES,V,IND_V,cPar);
    otherwise
        error('Invalid smooth method specified');
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program 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.
%
% This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function [dim, index, attr_name, dim_name, values]=cosmo_dim_find(ds, dim_label, raise)
% find dimension attribute in dataset
%
% [dim, index, attr_name, dim_name]=cosmo_dim_find(ds, dim_label[, raise])
%
% Inputs:
%   ds              dataset struct
%   dim_label       dimension label
%   raise           if true, raise an error if the dimension is not found.
%                   Default: false
%
% Outputs:
%   dim             dimension where dim_label was found, 1=sample
%                   dimension, 2=feature dimension
%   index           position where dim_label was found, so that:
%                     ds.a.(dim_name).values{index}==dim_label
%   attr_name       'sa' if dim==1, 'fa' if dim==2
%   dim_name        'sdim' if dim==1, 'fdim' if dim==2
%   values          the values associated with the dimension
%
% Examples:
%     % fMRI dataset, find first voxel dimension
%     ds=cosmo_synthetic_dataset('type','fmri');
%     [dim, index, attr_name, dim_name, values]=cosmo_dim_find(ds,'i');
%     disp(dim)
%     %|| 2
%     disp(index)
%     %|| 1
%     disp(attr_name)
%     %|| fa
%     disp(dim_name)
%     %|| fdim
%     cosmo_disp(values)
%     %|| [ 1 2 3 ]
%
%     % MEEG time-frequency dataset, find 'time' dimension
%     ds=cosmo_synthetic_dataset('type','timefreq','size','big');
%     [dim, index, attr_name, dim_name, values]=cosmo_dim_find(ds,'time');
%     disp(dim)
%     %|| 2
%     disp(index)
%     %|| 3
%     disp(attr_name)
%     %|| fa
%     disp(dim_name)
%     %|| fdim
%     cosmo_disp(values)
%     %|| [ -0.2000 -0.1500 -0.1000 -0.0500 0 ]
%     %
%     % move 'time' from feature to sample dimension
%     dst=cosmo_dim_transpose(ds,'time',1);
%     [dim, index, attr_name, dim_name, values]=cosmo_dim_find(dst,'time');
%     disp(dim)
%     %|| 1
%     disp(index)
%     %|| 1
%     disp(attr_name)
%     %|| sa
%     disp(dim_name)
%     %|| sdim
%     cosmo_disp(values)
%     %|| [ -0.2000 ; -0.1500 ; -0.1000 ; -0.0500 ; 0 ]
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #

    if nargin<3, raise=true; end

    is_singleton=ischar(dim_label);
    if is_singleton
        dim_label={dim_label};
    elseif ~iscellstr(dim_label)
        error('Second input must be string or cell with strings');
    end

    nlabel=numel(dim_label);

    dim=[];
    index=zeros(nlabel,1);
    values=cell(nlabel,1);
    for k=1:nlabel
        [d,i,an,dn,vs]=find_singleton(ds,dim_label{k},raise);

        if k==1
            dim=d;
            attr_name=an;
            dim_name=dn;
        end

        if isempty(d) || dim~=d || ~isequal(attr_name,an) || ...
                                    ~isequal(dim_name,dn)
            dim=[];
            break;
        end

        index(k)=i;
        values{k}=vs;
    end

    if isempty(dim)
        index=[];
        attr_name=[];
        dim_name=[];
        values=[];

        if raise
            error('Unable to find all labels in the same dimension: %s',...
                        cosmo_strjoin(dim_label,', '));
        end
    else
        if dim==1
            index=index';
            values=values';
        end
        if is_singleton
            values=values{1};
        end
    end

function [dim, index, attr_name, dim_name, values]=find_singleton(ds,...
                                                        dim_label,raise)
    infixes='sf';
    for dim=1:numel(infixes)
        infix=infixes(dim);

        attr_name=[infix 'a'];
        dim_name=[infix 'dim'];

        if cosmo_isfield(ds, ['a.' dim_name '.labels'])
            labels=ds.a.(dim_name).labels;
            m=cosmo_match(labels, dim_label);
            if any(m)
                index=find(m);
                if numel(index)>1 && raise
                    error('Duplicate label %s in .a.%s.labels', ...
                                    dim_label, dim_name);
                elseif ~cosmo_isfield(ds, ['a.' dim_name '.values'],...
                                                        raise)
                    % not all fields present

                else
                    values=ds.a.(dim_name).values{index};
                    return
                end
            end
        end
    end

    dim=[];
    index=[];
    attr_name=[];
    dim_name=[];
    values=[];

    if raise
        error('Not found: dimension label %s', dim_label);
    end

author: CoSMoMVPA

repo: CoSMoMVPA

save_path: github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA


text:
function varargout = drawDirectedEdges(p, e, varargin)
%DRAWDIRECTEDEDGES Draw edges with arrow indicating direction
%
%   usage:
%   drawDirectedEdges(NODES, EDGES);
%
%   drawDirectedEdges(NODES, EDGES, STYLE);
%   specifies style of arrrows. Can be one of:
%   'left'
%   'right'
%   'arrow'
%   'triangle'
%   'fill'
%
%   drawDirectedEdges(NODES, EDGES, STYLE, DIRECT) : also specify the base
%   direction of all edges. DIRECT is true by default. If DIRECT is false
%   all edges are inverted.
%
%   H = drawDirectedEdges(NODES, EDGES) : return handles to each of the
%   lines created.
%
%   TODO: now only style 'arrow' is implemented ...
%
%   -----
%
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 12/03/2003.
%

%   HISTORY

b=1;

if ~isempty(varargin)
    b = varargin{1};
end

h = zeros(length(e),1);
hold on;
for l=1:length(e)
    p1 = e(l, 1);
    p2 = e(l, 2);
    h(l*4) = line([p(p1,1) p(p2,1)], [p(p1,2) p(p2,2)]);

    % position of middles of edge
    xm = (p(p1,1) + p(p2,1))/2;
    ym = (p(p1,2) + p(p2,2))/2;

    % orientation of edge
    theta = atan2(p(p2,2) - p(p1,2), p(p2,1) - p(p1,1)) + (b==0)*pi;

    % pin of the arrow
    xa0 = xm + 10*cos(theta);
    ya0 = ym + 10*sin(theta);

    % right side of the arrow
    xa1 = xm + 3*cos(theta-pi/2);
    ya1 = ym + 3*sin(theta-pi/2);

    % left side of the arrow
    xa2 = xm + 3*cos(theta+pi/2);
    ya2 = ym + 3*sin(theta+pi/2);

    h(l*4+1) = line([xa1 xa0], [ya1 ya0]);
    h(l*4+2) = line([xa2 xa0], [ya2 ya0]);
end

if nargout==1
    varargout(1) = {h};
end

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
function [m,varargout] = min(varargin)

funname = 'min';

narginchk(1, 2)
if nargin == 1;
    nargoutchk(0, 2)
    [m,varargout{1}] = min(varargin{1}.Z(:));

elseif nargin == 2;
    nargoutchk(0, 1)

    % which one of the two input arguments is a GRIDobj
    isGRIDobj = cellfun(@(x) isa(x,'GRIDobj'),varargin);

    % if both
    if all(isGRIDobj)
        validatealignment(varargin{1},varargin{2});
        M = builtin(funname,varargin{1}.Z,varargin{2}.Z);
    else
        varargin = varargin(~isGRIDobj + 1);
        if ~isscalar(varargin{2});
            validatealignment(varargin{1},varargin{2});
        end
        M = builtin(funname,varargin{1}.Z,varargin{2});
    end

    m = varargin{1};
    m.name = funname;
    m.Z = M;
    m.zunit = '';
end

author: GERSL

repo: CCDC

save_path: github-repos/MATLAB/GERSL-CCDC


text:
function  [h, compUpJP] =  lfmComputeH4JP(gamma1_p, gamma1_m, sigma2, t1, ...
    preFactor, preExp, mode)

% LFMCOMPUTEH4JP Helper function for computing part of the LFMJP kernel.
% FORMAT
% DESC computes a portion of the LFMAP kernel.
% ARG gamma1 : Gamma value for first system.
% ARG gamma2 : Gamma value for second system.
% ARG sigma2 : length scale of latent process.
% ARG t1 : first time input (number of time points x 1).
% ARG t2 : second time input (number of time points x 1).
% ARG mode: indicates in which way the vectors t1 and t2 must be transposed
% RETURN h : result of this subcomponent of the kernel for the given values.
%
% COPYRIGHT : Mauricio Alvarez, 2010
%
% SEEALSO : lfmComputeH4.m, lfmComputeH4AP.m

% KERN

if mode==0
    if nargout > 1
        compUpJP{1} = lfmjpComputeUpsilonVector(gamma1_p,sigma2, t1);
        compUpJP{2} = lfmjpComputeUpsilonVector(gamma1_m,sigma2, t1);
        h =  compUpJP{1}*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...
            + compUpJP{2}*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';
    else
        h =  lfmjpComputeUpsilonVector(gamma1_p,sigma2, t1)*( preExp(:,1)/preFactor(1) - preExp(:,2)/preFactor(2)).' ...
            + lfmjpComputeUpsilonVector(gamma1_m,sigma2, t1)*( preExp(:,2)/preFactor(3) - preExp(:,1)/preFactor(4)).';
    end
else
    if nargout > 1
        compUp{1} = lfmComputeUpsilonVector(gamma1_p,sigma2, t1);
        compUp{2} = lfmComputeUpsilonVector(gamma1_m,sigma2, t1);
        h =  compUp{1}*(preExp(:,2)/preFactor(2) - preExp(:,1)/preFactor(1)).' ...
            + compUp{2}*(preExp(:,1)/preFactor(4) - preExp(:,2)/preFactor(3)).';
        compUpJP = compUp;
    else
        h =  lfmComputeUpsilonVector(gamma1_p,sigma2, t1)*(preExp(:,2)/preFactor(2) - preExp(:,1)/preFactor(1) ).' ...
            + lfmComputeUpsilonVector(gamma1_m,sigma2, t1)*(preExp(:,1)/preFactor(4) - preExp(:,2)/preFactor(3)).';
    end
end

author: SheffieldML

repo: GPmat


text:
function MountainCarPlot( x,a,steps )
subplot(2,1,2);

xplot =-1.6:0.05:0.6;
yplot =sin(3*xplot);
%Mountain
h = area(xplot,yplot,-1.1);
set(h,'FaceColor',[.1 .7 .1])
hold on
% Car  [1 .7 .1]
plot(x(1),sin(3*x(1))+0.1,'ok','markersize',12,'MarkerFaceColor',[1 .7 .1]);
%Goal
plot(0.45,sin(3*0.5)+0.1,'-pk','markersize',15,'MarkerFaceColor',[1 .7 .1]);
% direction of the force
if (a<0)
      plot(x(1)-0.08,sin(3*x(1))+0.1,'<k','MarkerFaceColor','g','markersize',10);
elseif (a>0)
      plot(x(1)+0.08,sin(3*x(1))+0.1,'>k','MarkerFaceColor','g','markersize',10);
end

title(strcat ('Step: ',int2str(steps)));
%-----------------------
axis([-1.6 0.6 -1.1 1.5]);
drawnow
hold off

author: epfl-lasa


text:
clear;
clc;
%PESQ_LQ.exe +8000 CH01M001.dat CH01M001-white+10dB.dat > test.txt
addpath('bin');
addpath('bin\obj_evaluation')
path = '.\EnhancedSpeech\';
[enhancedFiles]=find_wav(path);
numEnhancedFile=size(enhancedFiles,1);
fid=fopen('PESQ.txt','wt');

cleanFilePath='.\cleanSpeech\TIMIT_1_TEST.wav';
cleanSig = audioread(cleanFilePath);
for i=1:numEnhancedFile
    enhancedFilePath=enhancedFiles(i,:);

    k=0;
    enhancedSig = audioread(enhancedFilePath);
    short = min(length(enhancedSig),length(cleanSig));

    cleanSig = cleanSig(1:1:short);
    enhancedSig = enhancedSig(1:1:short);

    audiowrite('temp_clean.wav',cleanSig,8000,'BitsPerSample',16);
    audiowrite('temp_enhanced.wav',enhancedSig,8000,'BitsPerSample',16);
    PESQ_O=pesq('temp_clean.wav','temp_enhanced.wav');
    delete('temp_clean.wav');
    delete('temp_enhanced.wav');

    fprintf(fid,'%s\t\t',enhancedFilePath(length(path)+2:end));
    fprintf(fid,'%s\n',num2str(PESQ_O));
end
fclose(fid);

author: vipchengrui

repo: traditional-speech-enhancement


text:
%--------------------------------------------------------------------------
%   [dataout] = d2b(datain,N_bit)
%--------------------------------------------------------------------------
%   功能
%   转换10进制有符号数为二进制格式(常用于FPGA验证)
%--------------------------------------------------------------------------
%   输入:
%           datain                  10进制数
%           N_bit                   转换位数
%   output:
%           dataout                 二进制数
%--------------------------------------------------------------------------
%   例子:
%   d2b(13,5)
%   ans =
%       "1101"
%   d2b(-13,5)
%   ans =
%       "10011"
%--------------------------------------------------------------------------
function dataout = d2b(datain,N_bit)
[X,Y,Z] = size(datain);
datain(datain < 0) = datain(datain < 0)+2^N_bit;
h = dec2bin(datain);
for index = 1:X*Y*Z
    temp(index)= string(h(index,:));
end
dataout = reshape(temp,[X Y Z]);
end

repo: SP