text:
%扩频函数
function [out] = spread(data, code)

% ****************************************************************
%   data   : 输入数据序列
%   code   : 扩频码序列
%   out    : 扩频后的输出数据序列
% ****************************************************************

switch nargin
case { 0 , 1 }                                  %如果输入参数个数不对，提示错误
    error('缺少输入参数');
end

[hn,vn] = size(data);
[hc,vc] = size(code);

if hn > hc                                      %如果扩频码数小于输入的待扩频的数据序列，提示错误
    error('缺少扩频码序列');
end

out = zeros(hn,vn*vc);

for ii=1:hn
    out(ii,:) = reshape(code(ii,:).'*data(ii,:),1,vn*vc);
end

%******************************** end of file ********************************

repo: OFDM


text:
function r = mrdivide(a,b)
%MRDIVIDE     Implements  a / b  for gradient
%

% written  10/16/98     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
%                                    complete redesign
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 09/28/08     S.M. Rump  check for rounding to nearest improved
% modified 08/26/12     S.M. Rump  global variables removed
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  if prod(size(b))~=1
    error('Gradient division only for scalar denominator')
  end

  N = getappdata(0,'INTLAB_GRADIENT_NUMVAR');

  if ~isa(a,'gradient')          % non-gradient / gradient scalar
    r.x = a / b.x;
    n = prod(size(a));
    if n==1                     % non-gradient scalar / gradient scalar
      D = -a / sqr(b.x);
      r.dx = b.dx * D;
    else                        % non-gradient array / gradient scalar
      D = 1 / sqr(b.x);
      if issparse(b.dx)
        ax = sparse(-a(:));
      else
        ax = -a(:);
      end
      r.dx = ax * ( b.dx * D );
    end
  elseif ~isa(b,'gradient')      % gradient / non-gradient scalar
    r.x = a.x / b;
    r.dx = a.dx / b;
  else                          % gradient / gradient scalar
    r.x = a.x / b.x;
    D = 1 / sqr(b.x);
    n = prod(size(a.x));
    if n==1                     % gradient scalar / gradient scalar
      Num = a.dx * b.x - a.x * b.dx;
      r.dx = Num * D;
    else                        % gradient array / gradient scalar
      if issparse(a.dx)
        ax = sparse(a.x(:));
      else
        ax = a.x(:);
      end
      Num = a.dx * b.x - ax * b.dx;
      r.dx = Num * D;
    end
  end

  r = class(r,'gradient');

  if rndold
    setround(rndold)
  end

repo: OpenMAS


text:
function A = frand (n,nel,s)
% A = frand (n,nel,s) creates an n-by-n sparse matrix consisting of nel finite
% elements, each of which are of size s-by-s with random symmetric nonzero
% pattern, plus the identity matrix.
%
% Example:
%   A = frand (100, 100, 4) ; cspy (A)
% See also: cs_demo

%   Copyright 2006-2007, Timothy A. Davis.
%   http://www.cise.ufl.edu/research/sparse
ss = s^2 ;
nz = nel*ss ;
ii = zeros (nz,1) ;
jj = zeros (nz,1) ;
xx = zeros (nz,1) ;
k = 1 ;
for e = 1:nel
    i = 1 + fix (n * rand (s,1)) ;
    i = repmat (i, 1, s) ;
    j = i' ;
    x = rand (s,s) ;
    ii (k:k+ss-1) = i (:) ;
    jj (k:k+ss-1) = j (:) ;
    xx (k:k+ss-1) = x (:) ;
    k = k + ss ;
end
A = sparse (ii,jj,xx,n,n) + speye (n) ;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [w,winit_pix]=init_w(method,peval,image)
% [w,winit_pix]=init_w(method,peval,image)
% method:   'rand' %random initialization
%           'image' %specified initialization for example image=double(array2im(dpixc_ind))
%           'image_repmat' %for example image = mean(image,3);
%           'res' %image is res.w -> initialisation from the nmf results
% addbackgroundcomponent:   1 adds one component flat component as a background (peval.ncomp th)
%                           0 no background component
if ~isfield(peval, 'bgcomp')
    peval.bgcomp = 1;
end

switch method
    case 'rand'
        winit_pix = normalize(rand(peval.nx,peval.ny,peval.ncomp));
        msg='W initialzied as uniform random.';
    case 'image'
        winit_pix = normalize(image);
        msg='W initialized with specified 3D image.';
    case 'image_repmat'
        winit_pix(:,:,1:peval.ncomp) = normalize(repmat(image,[1,1,peval.ncomp]));
        msg='W initialized as repmat(image,[1,1,peval.ncomp].)';
    case 'res'
        s2=size(image,2); %it is only 2D (#pixX#comp)
        winit_pix(:,:,1:s2) = reshape(image, peval.nx, peval.ny, s2);
        msg='W initialized from the results res.w.';
end
winit_pix=max(winit_pix, eps); % To avoid zeros...
sw=size(winit_pix);
w=reshape(winit_pix,sw(1)*sw(2), size(winit_pix,3)); % it must be specifically set to size(winit_pix,3) for the case tehre is only one compoenent (ncomp=1)

if isfield (peval,'fid')
    mfprintf(peval.fid, [msg '\n'])
else
    fprintf([msg '\n']);
end

if peval.bgcomp
    w(:,peval.ncomp)=normalize(ones(sw(1)*sw(2),1));
    mfprintf(peval.fid, 'Last component [%g] of w initialised as a flat background. (background=%g)\n',peval.ncomp,peval.bg);
end

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
%MDL_TWOLINK_MDH Create model of a 2-link mechanism using modified DH convention
%
% MDL_TWOLINK_MDH is a script that the workspace variable tl which
% describes the kinematic and dynamic characteristics of a simple planar
% 2-link mechanism using modified Denavit-Hartenberg conventions.
%
% Also defines the vector:
%   qz   corresponds to the zero joint angle configuration.
%
% Notes::
% - SI units of metres are used.
% - It is a planar mechanism operating in the XY (horizontal) plane and is
%   therefore not affected by gravity.
%
% References::
%  - Based on Fig 3.8 (p71) of Craig (3rd edition).
%
% See also SerialLink, mdl_onelink, mdl_twolink, mdl_planar2.

% MODEL: generic, planar, 2DOF, modified_DH

% Copyright (C) 1993-2015, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

a1 = 1;
a2 = 1;

% for MDH parameters we need to implement the second link as a tool
% transform

twolink = SerialLink([
        RevoluteMDH('d', 0, 'a', 0,  'alpha', 0)
        RevoluteMDH('d', 0, 'a', a1, 'alpha', 0)
    ], ...
    'tool', transl(a2, 0, 0), ...
    'name', 'two link', ...
    'comment', 'from Craig');
qz = [0 0];
qn = [pi/6, -pi/6];

author: Allopart

repo: rbpf-gmapping


text:
% StackOverflow Q2080835
% https://stackoverflow.com/questions/2080835
% Deriving the Inverse Filter of Image Convolution Kernel
% References:
%   1.  A
% Remarks:
%   1.  B
% TODO:
% 	1.  C
% Release Notes
% - 1.0.000     14/01/2019
%   *   First release.

%% General Parameters

subStreamNumberDefault = 0;

run('InitScript.m');

figureIdx           = 0; %<! Continue from Question 1
figureCounterSpec   = '%04d';

generateFigures = OFF;
generateImages  = OFF;

OPERATION_MODE_CONVOLUTION = 1;
OPERATION_MODE_CORRELATION = 2;

CONVOLUTION_SHAPE_FULL         = 1;
CONVOLUTION_SHAPE_SAME         = 2;
CONVOLUTION_SHAPE_VALID        = 3;

%% Simulation Parameters

operationMode = OPERATION_MODE_CONVOLUTION;
convShape = CONVOLUTION_SHAPE_VALID;

% The Input Kernel - F
numRowsF = 11;
numColsF = 7;

% The Inverse Kernel - G
numRowsG = 201;
numColsG = 201;

numIteraions    = 50000;
stepSize        = 5e-5;

%% Generate Data

numRowsH = numRowsF + numRowsG - 1;
numColsH = numColsF + numColsG - 1;

mF = rand(numRowsF, numColsF);
mG = ones(numRowsG, numColsG); %<! Initial condition

%% Verify Gradient
% Using Random h Filter

mH = rand(numRowsH, numColsH);

hObjFun = @(mG) 0.5 * sum((conv2(mF, mG, 'full') - mH) .^ 2, 'all');

mObjFunGrad = conv2(conv2(mF, mG, 'full') - mH, mF(end:-1:1, end:-1:1), 'valid');

mObjFunGradNum = zeros(size(mG));
mTmp = zeros(size(mObjFunGradNum));

derEps = 5e-6;

% Numeric Gradient
for ii = 1:numel(mObjFunGradNum)
    mTmp(ii)            = derEps;
    mObjFunGradNum(ii)  = (hObjFun(mG + mTmp) - hObjFun(mG)) / derEps;
    mTmp(ii)            = 0;
end

mE = mObjFunGradNum - mObjFunGrad;
gradError = max(abs(mE(:)));

%% Derive the Inverse

% The Target Kernel - Discrete Delta
mH = zeros(numRowsH, numColsH);
mH(ceil(numRowsH / 2), ceil(numColsH / 2)) = 1; %<! Delta

% Gradient Descent (Could improved with Accelerated Gradient Descent)
for ii = 1:numIteraions
    mObjFunGrad = conv2(conv2(mF, mG, 'full') - mH, mF(end:-1:1, end:-1:1), 'valid');
    mG          = mG - (stepSize * mObjFunGrad);
end

mA = conv2(mG, mF, 'full');
mE = abs(mA - mH);
inverseError = max(mE(:));

%% Analysis

disp(['Analytic Gradient vs. Numeric Gradient - Maximum Absolute Deviation - ', num2str(gradError)]);
disp(['Inverse Filter - Maximum Deviation - ', num2str(inverseError)]);

%% Display Results

figureIdx = figureIdx + 1;

hFigure = figure('Position', figPosLarge);
hAxes   = axes();
hImgObj = imshow(mA, []);
set(get(hAxes, 'Title'), 'String', {['Convolution Result']}, ...
    'FontSize', fontSizeTitle);

if(generateFigures == ON)
    saveas(hFigure,['Figure', num2str(figureIdx, figureCounterSpec), '.png']);
end

%% Restore Defaults

% set(0, 'DefaultFigureWindowStyle', 'normal');
% set(0, 'DefaultAxesLooseInset', defaultLoosInset);

author: RoyiAvital

repo: StackExchangeCodes


text:
report_this_filefun(mfilename('fullpath'));

dy = 0.15;
tmin1 = 0.05;
newt0 = newt2;
tpre = 365;
dt = 1;

save_aspar2;
do = [ ' ! '  hodi '/aspar/myaspar' ];
eval(do)

try
    load aspar3.out
catch ME
    error_handler(ME,@do_nothing);
end
re = aspar3;

% std of p etc form pauls code.
pvar0 = 0.04, bvar0 = 0.029; avar0 = 0.337, cvar0 = 0.002;
bv = re(2,3);
p =  re(1,3);
c =  re(4,3);
A =  re(3,3);
bv0 = re(2,1);
p0 =  re(1,1);
c0 =  re(4,1);
A0 =  re(3,1);
tpre2 = 100

la = 0;
m0 = maepi(1,6);

m = min(newt2.Magnitude);
dt = 1;

t0 = ( max(newt2.Date) - mati)*365;
pla = 0;plae = 0;

P2 = [];
mp = 6;

for tpre = 0.1:tpre2
    pla = 0; plae = 0;
    for t = t0:dt:t0+tpre
        pla = pla + (10^(A + bv*(7.4-mp)) * (t + c)^(-p))  *dt;
        plae = plae + (10^(A-avar0 + bv+bvar0*(7.3-mp)) * (t + c+cvar0)^(-p+pvar0))  *dt;

    end
    P = 1 - exp(-pla);
    Pe = 1-exp(-plae);
    P2 = [P2 ; P tpre Pe];

end

P0 = [];

for tpre = 0.1:tpre2
    pla = 0;
    for t = t0:dt:t0+tpre
        pla = pla + (10^(A0 + bv0*(7.4-mp)) * (t + c0)^(-p0))  *dt;
    end
    P  =  1 - exp(-pla);
    P0 = [P0 ; P tpre ];
end

figure
axes('position',[0.1 0.25 0.35 0.6])
hold on; box on
plot(P2(:,2),P2(:,1));
hold on
%plot(P2(:,2),P2(:,3),'k');

hold  on
plot(P0(:,2),P0(:,1),'r-.');
set(gca,'TickDir','out','fontweight','bold')

legend('Bayes Estimate','Generic Model', 'Location', 'SouthEast');
xlabel('Time after Mainshock')
ylabel('Probability')
te = text(0.1,0.9,'Mag. 6','units','normalized','fontweight','bold')

P2 = [];
mp = 7;

for tpre = 0.1:tpre2
    pla = 0;
    for t = t0:dt:t0+tpre
        pla = pla + (10^(A + bv*(7.3-mp)) * (t + c)^(-p))  *dt;
    end
    P = 1 - exp(-pla);
    P2 = [P2 ; P tpre ];

end

P0 = [];

for tpre = 0.1:tpre2
    pla = 0;
    for t = t0:dt:t0+tpre
        pla = pla + (10^(A0 + bv0*(7.3-mp)) * (t + c0)^(-p0))  *dt;
    end
    P  =  1 - exp(-pla);
    P0 = [P0 ; P tpre ];
end

axes('position',[0.55 0.25 0.35 0.6])
hold on; box on
plot(P2(:,2),P2(:,1));
hold  on
plot(P0(:,2),P0(:,1),'r-.');
set(gca,'TickDir','out','fontweight','bold')

legend('Bayes Estimate','Generic Model', 'Location', 'SouthEast');
xlabel('Time after Mainshock')
te = text(0.1,0.9,'Mag. 7','units','normalized','fontweight','bold');

author: CelsoReyes


text:
% Test file for trigtech/cell2mat.m

function pass = test_cell2mat(pref)

if ( nargin < 2 )
    pref = trigtech.techPref();
end

testclass = trigtech();

f = testclass.make(@(x) [sin(pi*x) cos(pi*x) exp(2*1i*pi*x)], [], pref);
g = testclass.make(@(x) sin(pi*x), [], pref);
h = testclass.make(@(x) [cos(pi*x) exp(2*1i*pi*x)], [], pref);

F = cell2mat([g h]);
pass(1) = all( sum(F - f) < max(vscale(f)*eps) );

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
% eeg_eventtypes()  - return a list of event or urevent types in a dataset and
%                     the respective number of events of each type. Ouput event
%                     types are sorted in reverse order of their number. If no
%                     outputs, print this list on the commandline instead.
%
% Usage:
%        >> [types,numbers] = eeg_eventtypes(EEG);
% Inputs:
%        EEG        - EEGLAB dataset structure
% Outputs:
%        types      - cell array of event type strings
%        numbers    - vector giving the numbers of each event type in the data
%
% Example:
%           >> eeg_eventtypes(EEG);       % print numner of each event types
%
% Author: Scott Makeig, SCCN/INC/UCSD, April 28, 2004-

%        >> [types,numbers] = eeg_eventtypes(EEG,types);
%        >> [types,numbers] = eeg_eventtypes(EEG,'urevents',types);
% Inputs:
%        EEG        - EEGLAB dataset structure
%        'urevents' - return event information for the EEG.urevent structure
%        types      - {cell array} of event types to return or print.
% Outputs:
%        types      - cell array of event type strings
%        numbers    - vector giving the numbers of each event type in the data
%
% Note:  Numeric (ur)event types are converted to strings, so, for example,
%        types {13} and {'13'} are not distinguished.
%
% Example:
%           >> eeg_eventtypes(EEG);       % print numner of each event types
%
% Curently disabled:
%           >> eeg_eventtypes(EEG,'urevent');  % print hist. of urevent types
%           >> eeg_eventtypes(EEG,{'rt'});% print number of 'rt' events
%           >> eeg_eventtypes(EEG,'urevent',{'rt','break'});
%                                         % print numbers of 'rt' and 'break'
%                                         % type urevents

% Copyright (C) 2004 Scott Makeig, SCCN/INC/UCSD, smakeig@ucsd.edu
%
% 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 2 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, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
%
%
% event types can be numbers, Stefan Debener, 05/12/2006,
% added 2nd and 3rd args, sorted outputs by number, Scott Makeig, 09/12/06

function [types,numbers] = eeg_eventtypes(EEG,arg2,arg3)

if nargin< 1
   help eeg_eventtypes
   return
end
if ~isstruct(EEG)
   error('EEG argument must be a dataset structure')
end

if ~isfield(EEG,'event')
   error('EEG.event field not found');
end
if nargin > 1
    error('Multiple input arguments are currently disabled');
end;

UREVENTS = 0; % flag returning infor for urevents instead of events
typelist = [];
if nargin>1
   if ischar(arg2)
       if strcmp(arg2,'urevent') | strcmp(arg2,'urevents')
            UREVENTS = 1; % change flag
       else
            error('second argument string not understood')
       end
       if nargin>2
            if iscell(arg3)
                  typelist = arg3;
            end
       end
   elseif iscell(arg2)
       typelist = arg2;
   end
end
if ~isempty(typelist)     % cast to cell array of strings
   for k=1:length(typelist)
       if isnumeric(typelist{k})
          typelist{k} = num2str(typelist{k});
       end
   end
end

if ~UREVENTS
   nevents = length(EEG.event);
   alltypes = cell(nevents,1);
   for k=1:nevents
       if isnumeric(EEG.event(k).type)
          alltypes{k} = num2str(EEG.event(k).type);
       else
          alltypes{k} = EEG.event(k).type;
       end
   end
else
   nevents = length(EEG.urevent);
   alltypes = cell(nevents,1);
   for k=1:nevents
       if isnumeric(EEG.urevent(k).type)
          alltypes{k} = num2str(EEG.urevent(k).type);
       else
          alltypes{k} = EEG.urevent(k).type;
       end
   end
end

[types i j] = unique_bc(alltypes);

istypes = 1:length(types);
notistypes = [];
if ~isempty(typelist)
  notistypes = ismember_bc(typelist,types);
  istypes = ismember_bc(types,typelist(find(notistypes==1))); % types in typelist?
  notistypes = typelist(find(notistypes==0));
end

types(~istypes) = []; % restrict types to typelist

ntypes = length(types);
numbers = zeros(ntypes + length(notistypes),1);
for k=1:ntypes
  numbers(k) = length(find(j==k));
end
types = [types(:); notistypes(:)]; % concatenate the types not found
ntypes = length(types);
for j = 1:length(notistypes)
   numbers(k+j) = 0;
end

% sort types in reverse order of event numbers
[numbers nsort] = sort(numbers);
numbers = numbers(end:-1:1);
types = types(nsort(end:-1:1));

%
% print output on commandline %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargout < 1
  fprintf('\n');
  if UREVENTS
    fprintf('EEG urevent types:\n\n')
  else
    fprintf('EEG event types:\n\n')
  end

  maxx = 0;
  for k=1:ntypes
    x = length(types{k});
    if x > maxx
        maxx = x; % find max type name length
    end
  end
  for k=1:ntypes
    fprintf('  %s',types{k});
    for j=length(types{k})+1:maxx+4
       fprintf(' ');
    end
    fprintf('%d\n',numbers(k));
 end
 fprintf('\n');
 clear types % no return variables
end

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function align_filtered= apply_filter( data, data_Nsamples, align_filter_dB)

global Downsample DATAPADDING_MSECS SEARCHBUFFER Fs

align_filtered= data;
n= data_Nsamples- 2* SEARCHBUFFER* Downsample+ DATAPADDING_MSECS* (Fs/ 1000);
% now find the next power of 2 which is greater or equal to n
pow_of_2= 2^ (ceil( log2( n)));

[number_of_points, trivial]= size( align_filter_dB);
overallGainFilter= interp1( align_filter_dB( :, 1), align_filter_dB( :, 2), ...
    1000);

x= zeros( 1, pow_of_2);
x( 1: n)= data( SEARCHBUFFER* Downsample+ 1: SEARCHBUFFER* Downsample+ n);

x_fft= fft( x, pow_of_2);

freq_resolution= Fs/ pow_of_2;

factorDb( 1: pow_of_2/2+ 1)= interp1( align_filter_dB( :, 1), ...
    align_filter_dB( :, 2), (0: pow_of_2/2)* freq_resolution)- ...
    overallGainFilter;
factor= 10.^ (factorDb/ 20);

factor= [factor, fliplr( factor( 2: pow_of_2/2))];
x_fft= x_fft.* factor;

y= ifft( x_fft, pow_of_2);

align_filtered( SEARCHBUFFER* Downsample+ 1: SEARCHBUFFER* Downsample+ n)...
    = y( 1: n);

% fid= fopen( 'log_mat.txt', 'wt');
% fprintf( fid, '%f\n', y( 1: n));
% fclose( fid);

author: vipchengrui

repo: traditional-speech-enhancement


text:
function b = yalmipbandwidth(S)

if isa(S,'sdpvar')
    S = spy(S);
end
[i,j] = find(triu((S)));
b = max(abs(i-j));

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function halton_test0125 ( )

%*****************************************************************************80
%
%% TEST0125 tests I4_TO_HALTON.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 January 2009
%
%  Author:
%
%    John Burkardt
%
  dim_max = 3;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST0125\n' );
  fprintf ( 1, '  I4_TO_HALTON computes a Halton sequence.\n' );
  fprintf ( 1, '  The user specifies all data explicitly.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  In this test, we call I4_TO_HALTON repeatedly.\n' );
  fprintf ( 1, '  We use distinct primes as bases.\n' );

  for dim_num = 1 : dim_max

    n = 11;
    step = 0;
    seed(1:dim_num) = 0;
    leap(1:dim_num) = 1;
    for j = 1 : dim_num
      base(j) = prime(j);
    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  DIM_NUM = %12d\n', dim_num );
    fprintf ( 1, '  N =    %12d\n', n );
    fprintf ( 1, '  STEP = %12d\n', step );
    i4vec_transpose_print ( dim_num, seed, '  SEED = ' );
    i4vec_transpose_print ( dim_num, leap, '  LEAP = ' );
    i4vec_transpose_print ( dim_num, base, '  BASE = ' );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  STEP      Halton\n' );
    fprintf ( 1, '\n' );
    for j = 1 : n
      step = j - 1;
      r = i4_to_halton ( dim_num, step, seed, leap, base );
      fprintf ( 1, '  %6d  ', step );
      for i = 1 : dim_num
        fprintf ( 1, '%8f  ', r(i) );
      end
      fprintf ( 1, '\n' );
    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [D,Ds,hdr,p,coords,X,Y,Z] = tor_3d(varargin)
% :Usage:
% ::
%
%    [D,Ds,hdr,p,coords,X,Y,Z] = tor_3d(varargin)
%
% made to use single_subj_T1.img from SPM99
%
% :Options:
%
%   **'data':**
%        followed by image data, must also use 'hdr'; data is full image volume
%
%   **'hdr':**
%        followed by hdr structure (use read_hdr)
%
%   **'coords':**
%        3 element row vector of x,y,z coordinates at which to cut away
%
%   **'figure':**
%        create a new figure to plot on
%
%   **'whichcuts':**
%        followed by incisions; choices are x y z w (whole)
%
%        example:'whichcuts','xyz' (xyz is default)
%        order of output handles (p(i)) is 'wyzx'
%
%        New: Special methods:
%          - 'coronal slice right'
%          - 'coronal slice left'
%          - 'coronal slice'
%
%   **'filename':**
%        followed by filename of image data to load, in single quotes
%
%        should be analyze img format, without the .img extension
%
%        cluster imaging assumes neurological orientation, but should work anyway.
%
%   **'revx':**
%        reverse x cut direction, so cut in from left instead of right
%
%   **'topmm':**
%        topmm = varargin{i+1};
%
%   **'intensity_threshold':**
%        percentile of data above which is considered in-object
%        higher = more sparse object
%
% :Outputs:
%
%   **D:**
%        img data
%
%   **Ds:**
%        smoothed data
%
%   **hdr:**
%        header
%
%   **p:**
%        image handles
%
%   **coords:**
%        coordinates
%
%   **X, Y, Z:**
%        are the millimeter, origin centered reference frame for the head isosurface
%
% :Examples:
% ::
%
%    [D,Ds,hdr,p,coords] = tor_3d('figure','data',D,'hdr',hdr,'whichcuts','yzx');
%    [D,Ds,hdr,p,coords] = tor_3d('figure');
%    [D,Ds,hdr,headhandle,coords] = tor_3d('whichcuts','z', 'coords', [-Inf
%    -Inf Inf], 'filename', 'T1_face_exemplar', 'intensity_threshold', 80); set(gcf, 'Color', 'w'); axis on
%
%    % Special slice example:
%    [D,Ds,hdr,handle,coords]  = tor_3d('whichcuts', 'coronal slice right', 'coords', [0 12 0], 'topmm', 100);
%    lightRestoreSingle
%    set(handle(1), 'FaceColor', [.5 .5 .5])
%
% ..
%    Made by Tor Wager, 10/3/2001 last modified 10/19/01
% ..

% ..
%    Set up arguments and default values
% ..

[D,Ds,hdr] = deal([]);
p = zeros(1,2);
coords = [0 0 0];
whichcuts = 'xyz';
filename = 'spm2_single_subj_T1_scalped'; 'single_subj_T1';    % default structural image to use
topmm = 60;                     % image only this high in mm to avoid image distortions above head.
bottommm = nan;                 % bottom cutoff in mm
dolight = 1;
revx = 0;
intensity_threshold = [];

for i = 1:nargin
    if isstr(varargin{i})
        switch varargin{i}
        case 'data', D = varargin{i+1};
        case 'hdr', hdr = varargin{i+1};
        case 'coords', coords = varargin{i+1};
        case 'figure', h3dfig = figure; set(h3dfig,'Tag','myFig');
            colormap(gray(100)),set(gcf,'Color','k'),axis off,set(gcf,'Position',[184   115   672   543])
        case 'whichcuts',whichcuts = varargin{i+1};
        case 'filename',filename = varargin{i+1};
        case 'nolight', dolight = 0;
        case 'revx', revx = 1;
        case 'topmm', topmm = varargin{i+1};
        case 'bottommm', bottommm = varargin{i+1};

        case 'intensity_threshold', intensity_threshold = varargin{i + 1};

        end
    end
end

%------------------------------------------------------------------------------
% Load the image file, if necessary
% Get origin and voxel size
%------------------------------------------------------------------------------
if isempty(D)

    if isa(D, 'fmri_data'), D = []; end % empty fmri_data object

    if ~exist(filename, 'file')
        fullpath = which([filename '.img']);
    else
        fullpath = filename;
    end

    if isempty(fullpath), error(['Cannot find file: ' filename '.img']);
    else disp(['Loading structural image: ' fullpath]);drawnow
    end
    [array,hdr] = readim2(filename);
    % rotate 270 degrees so that front of head is positive y
    % (works with canonical SPM images, at least, so this orientation is ok.)
    for i = 1:size(array,3)
        D(:,:,i) = rot90(rot90(rot90((array(:,:,i)))));
    end

    VV = spm_vol(fullpath);
    origin = VV.mat(1:3, 4);
    voxsize = (diag(VV.mat(1:3, 1:3)));

elseif isa(D, 'fmri_data')

    mymat = D.volInfo.mat;
    origin = mymat(1:3, 4);
    voxsize = (diag(mymat(1:3, 1:3)));
    array = reconstruct_image(D);

    % rotate 270 degrees so that front of head is positive y
    % (works with canonical SPM images, at least, so this orientation is ok.)
    D = [];
    for i = 1:size(array,3)
        D(:,:,i) = rot90(rot90(rot90((array(:,:,i)))));
    end

else
    error('Use no ''data'' argument for default surface, or enter ''data'' followed by fmri_data object')
end

if isempty(Ds)
    Ds = smooth3(D);
end

%------------------------------------------------------------------------------
% Define X Y Z coordinates of head data
%------------------------------------------------------------------------------
% Define X, Y, Z relative to the origin, so head will be centered on origin
% Multiply by voxel size in header so that coordinates are in mm from the origin
% Make sure origin is set properly in header for this to work accurately.

% NOTE: spm5 no longer sets things in origin, apparently, so use spm_vol
% to get origin

[M N P] = size(D);
%[X Y Z] = meshgrid(((1:N)-hdr.origin(1))*hdr.xsize, ((1:M)-hdr.origin(2))*hdr.ysize, ((1:P)-hdr.origin(3))*hdr.zsize);
[X Y Z] = meshgrid(((1:N)*voxsize(1)+origin(1)), ((1:M)*voxsize(2)+origin(2)), ((1:P)*voxsize(3)+origin(3)));

% define threshold
if isempty(intensity_threshold)
    surface_threshold = mean(D(:));  % original way, pre-2009
else
    surface_threshold = prctile(D(:), intensity_threshold);  %mean(mean(mean(D)));
end

%------------------------------------------------------------------------------
% Make patches for cutaway
%------------------------------------------------------------------------------
index = 1;

if strcmp(whichcuts, 'coronal slice right')
    % Special methods
    [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[0 nan coords(2)-2 coords(2) bottommm topmm], surface_threshold);

elseif strcmp(whichcuts, 'coronal slice left')
    [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan 0 coords(2)-10 coords(2) bottommm topmm], surface_threshold);

elseif strcmp(whichcuts, 'coronal slice')
    [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan coords(2)-10 coords(2) bottommm topmm], surface_threshold);

else

    if any(whichcuts == 'w')
        [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan nan nan bottommm topmm], surface_threshold);          % whole head
        index = index + 2;
    end

    % xyz inset cutaway - seems to work only if x does not come first
    if any(whichcuts == 'y')
        [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan nan coords(2) bottommm topmm], surface_threshold);
        index = index + 2;
    end
    if any(whichcuts == 'z')
        [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan nan nan nan bottommm coords(3)], surface_threshold);
        index = index + 2;
    end
    if any(whichcuts == 'x')
        if revx, [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[coords(1) nan nan nan bottommm topmm], surface_threshold);
        else [p(index),p(index+1)] = imagePatch(X,Y,Z,D,Ds,[nan coords(1) nan nan bottommm topmm], surface_threshold);
        end
        index = index + 2;
    end

end

%------------------------------------------------------------------------------
% Set lighting conditions
%------------------------------------------------------------------------------
if dolight && length(p) > 1
    myLight = standardMRIlighting('full',p(1:2));
elseif dolight
    myLight = standardMRIlighting('full',p);
end

if length(p) > 2, standardMRIlighting('reflectance',p(3:4)); end
if length(p) > 4, standardMRIlighting('reflectance',p(5:6)); end

% set(myLight,'Tag','myLight')  % done in stMRIlighting.

rotate3d off
	%------------------------------------------------------------------------------
    % set callback to light follow the camera
	%------------------------------------------------------------------------------
	if exist('lightFollowView') == 2
        set(gcf, 'WindowButtonUpFcn', 'lightFollowView');
    else
        warning('Cannot find lightFollowView.m to set light position.')
    end

%------------------------------------------------------------------------------
% Sub-function for imaging patch
%------------------------------------------------------------------------------
function [p1,p2] = imagePatch(X,Y,Z,D,Ds,inValues, surface_threshold)

    if isempty(inValues)
        inValues = [nan nan nan nan nan nan];
    end

    if isempty(X) | isempty(Y) | isempty(Z)
        % no xyz coordinates
        FV2 = isosurface(Ds,surface_threshold);
        IS2 = isocaps(D,surface_threshold);

        % Draw figure patches
        try
            p1 = patch(FV2,'FaceColor',[.8,.5,.4],'EdgeColor','none','FaceAlpha',1,'SpecularExponent',200,'SpecularStrength',.2);
            p2 = patch(IS2,'FaceColor','interp','EdgeColor','none','FaceAlpha',1);
        catch
            p1 = patch(FV2,'FaceColor',[1,.75,.65],'EdgeColor','none','SpecularExponent',200,'SpecularStrength',.2);
            p2 = patch(IS2,'FaceColor','interp','EdgeColor','none');
        end

    else

        % Define subvolume for cutaway view
        [x y z A] = subvolume(X,Y,Z,D,inValues);
        [x y z As] = subvolume(X,Y,Z,Ds,inValues);
        FV2 = isosurface(x,y,z,As,surface_threshold);
        IS2 = isocaps(x,y,z,A,surface_threshold);

        % Draw figure patches
        try
            p1 = patch(FV2,'FaceColor',[.8,.5,.4],'EdgeColor','none','FaceAlpha',1,'SpecularExponent',200,'SpecularStrength',.2);
            p2 = patch(IS2,'FaceColor','interp','EdgeColor','none','FaceAlpha',1);
        catch
            p1 = patch(FV2,'FaceColor',[.8,.5,.4],'EdgeColor','none','FaceAlpha',1,'SpecularExponent',200,'SpecularStrength',.2);
            p2 = patch(IS2,'FaceColor','interp','EdgeColor','none');
        end
        % isonormals(A,p1)
    end

    drawnow
    return

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function v = mohsst5_explained_variance_fa(W, CovW, X, CovX)

% This is approximate, because this does not take into account the
% correlations between different time instances or spatial locations.

% Remove temporal mean
X = bsxfun(@minus, X, mean(X,2));

% Compute <XX>
XX = X*X';
if ndims(CovX) == 2 && all(size(CovX)==size(X))
  XX = XX + diag(sum(CovX,2));
else
  XX = XX + sum(CovX,3);
end

% Compute weighted <WW>
w = mohsst5_weights();
w = mohsst5_remove_land(w);
WW = W*diag(w)*W';
if ndims(CovW) == 2 && all(size(CovW)==size(W))
  WW = WW + diag(wsum(CovW,w,2));
else
  WW = WW + wsum(CovW,w,3);
end

% Effective number of samples
%N = sum(sum( w(:)*ones(1,size(X,2)) ));
N = sum(w) * size(X,2);

% Explained variance
v = diagprod(WW,XX) / N;

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


text:
function navego_plot_outage (nav_t, nav_var, OUTAGE, times_out)
% navego_plot_outage: plots GNSS outages periods.
%
% INPUT
%   nav_t,   Nx1 vector time.
%   nav_var, Nx1 navigation variable.
%   OUTAGE, 'ON' or 'OFF' (string).
%   times_out, Tx1 vector with outage times where times_out(1) is the start
%     time of 1st GNSS OUTAGE, times_out(2) is the end of 1st GNSS OUTAGE,
%     times_out(3) is the start of the 2nd GNSS OUTAGE, and so on. T should
%     be even.
%
% OUTPUT
%   One figure.
%
%   Copyright (C) 2014, Rodrigo Gonzalez, all rights reserved.
%
%   This file is part of NaveGo, an open-source MATLAB toolbox for
%   simulation of integrated navigation systems.
%
%   NaveGo is free software: you can redistribute it and/or modify
%   it under the terms of the GNU Lesser General Public License (LGPL)
%   version 3 as published by the Free Software Foundation.
%
%   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 Lesser General Public License for more details.
%
%   You should have received a copy of the GNU Lesser General Public
%   License along with this program. If not, see
%   <http://www.gnu.org/licenses/>.
%
% Version: 001
% Date:    2021/12/14
% Author:  Rodrigo Gonzalez <rodralez@frm.utn.edu.ar>
% URL:     https://github.com/rodralez/navego

if (nargin < 3)

    OUTAGE = 'OFF';
end

%% PARAMETERS

plot_parameters;

%% OUTAGES

if (strcmp(OUTAGE,'ON'))

    OUTAGE_N = max(size(times_out)) / 2;

    for k = 1:OUTAGE_N

        idx  = find(nav_t >= times_out(2*k-1), 1, 'first' );
        fdx  = find(nav_t <= times_out(2*k), 1, 'last' );

        plot(nav_t(idx:fdx), nav_var(idx:fdx), '.r', 'MarkerSize', ms, ...
            'LineWidth', lw, 'DisplayName','GNSS OUTAGE') ;
    end
end

author: rodralez

repo: NaveGo

save_path: github-repos/MATLAB/rodralez-NaveGo


text:
function eer_val = eer(tar,non)
% Calculates the equal error rate from a set of target and
% non-target scores.
% Inputs:
%   tar: vector of target scores
%   non: vector of non-target scores
% Output:
%   eer: the equal error rate.

assert(isvector(tar))
assert(isvector(non))

[Pmiss,Pfa] = rocch(tar,non);
eer_val = rocch2eer(Pmiss,Pfa);

author: nesl


text:
function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)
%GRADIENTDESCENTMULTI Performs gradient descent to learn theta
%   theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by
%   taking num_iters gradient steps with learning rate alpha

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);

for iter = 1:num_iters

    % ====================== YOUR CODE HERE ======================
    % Instructions: Perform a single gradient step on the parameter vector
    %               theta.
    %
    % Hint: While debugging, it can be useful to print out the values
    %       of the cost function (computeCostMulti) and gradient here.
    %

h=theta'*X';

delta=1/m*(X'*X*theta-X'*y);

theta=theta-alpha.*delta;

    % ============================================================

    % Save the cost J in every iteration
    J_history(iter) = computeCostMulti(X, y, theta);

end

end

author: yhyap

repo: machine-learning-coursera


text:
function v = newtonmonoms(p)
% NEWTONMONOMS Computes all monoms inside half Newton polytope
%
% V = NEWTONMONOMS(P)
%
% Input
%  P : Scalar SDPVAR object
%
% Output
%  V : Vector with SDPVAR objects
%
% Example:
%
% sdpvar x y
% sdisplay(newtonmonoms(1+x^4*y^2+x^2*y^4))
%
% See also NEWTONREDUCE, CONSISTENT, CONGRUENCEBLOCKS

if isa(p,'double')
    v = 1;
else
    x = recover(depends(p));
    v = monolist(x,degree(p)/2);
    v = newtonreduce(v,p);
end


text:
function [OutputError,basler_vid,frame_nr_display] = PIVlab_capture_basler_synced_start(nr_of_images,ROI_basler)

hgui=getappdata(0,'hgui');
crosshair_enabled = getappdata(hgui,'crosshair_enabled');
sharpness_enabled = getappdata(hgui,'sharpness_enabled');
OutputError=0;

%% Prepare camera
delete(imaqfind); %clears all previous videoinputs
try
	hwinf = imaqhwinfo;
	%imaqreset
catch
	disp('Error: Image Acquisition Toolbox not available!')
end

info = imaqhwinfo(hwinf.InstalledAdaptors{1});

if strcmp(info.AdaptorName,'gentl')
	disp('gentl adaptor found.')
else
	disp('ERROR: gentl adaptor not found. Please got to Matlab file exchange and search for "gentl" to install it.')
end

basler_name = info.DeviceInfo.DeviceName;
disp(['Found camera: ' basler_name])
basler_supported_formats = info.DeviceInfo.SupportedFormats;
%basler_vid = videoinput(info.AdaptorName,1,basler_supported_formats{1});
basler_vid = videoinput(info.AdaptorName);

basler_settings = get(basler_vid);
basler_settings.Source.DeviceLinkThroughputLimitMode = 'off';

%% prepare axes
PIVlab_axis = findobj(hgui,'Type','Axes');
image_handle_basler=imagesc(zeros(ROI_basler(4),ROI_basler(3)),'Parent',PIVlab_axis,[0 2^8]);
setappdata(hgui,'image_handle_basler',image_handle_basler);

frame_nr_display=text(100,100,'Initializing...','Color',[1 1 0]);
colormap default %reset colormap steps
new_map=colormap('gray');
new_map(1:3,:)=[0 0.2 0;0 0.2 0;0 0.2 0];
new_map(end-2:end,:)=[1 0.7 0.7;1 0.7 0.7;1 0.7 0.7];
colormap(new_map);axis image;
set(gca,'ytick',[])
set(gca,'xtick',[])
colorbar

%% set camera parameters for free run or triggered acquisition
triggerconfig(basler_vid, 'hardware');
basler_settings.TriggerSource = 'Line3';
basler_settings.Source.ExposureMode = 'TriggerWidth';
basler_settings.Source.TriggerSource ='Line3';
basler_settings.Source.TriggerSelector='FrameStart';
basler_settings.Source.TriggerMode ='On';
basler_settings.Source.ExposureOverlapTimeMax = basler_settings.Source.SensorReadoutTime;

ROI_basler=[ROI_basler(1)-1,ROI_basler(2)-1,ROI_basler(3),ROI_basler(4)]; %unfortunaletly different definitions of ROI in pco and basler.
basler_vid.ROIPosition=ROI_basler;

%% start acqusition (waiting for trigger)
basler_frames_to_capture = nr_of_images*2;
basler_vid.FramesPerTrigger = basler_frames_to_capture;
if ~isinf(nr_of_images) %only start capturing if save box is ticked.
	flushdata(basler_vid);
	start(basler_vid);
end
preview(basler_vid,image_handle_basler);
drawnow;

author: Shrediquette

repo: PIVlab

save_path: github-repos/MATLAB/Shrediquette-PIVlab


text:
function [xi,yi] = snakeinterp(x,y,dmax,dmin)
%SNAKEINTERP  Interpolate the snake adaptively
%   [xi,yi] = snakeinterp(x,y,dmax,dmin)
%
%   dmax: the maximum distance between two snake points
%   dmin: the maximum distance between two snake points
%   d(i,i+1)>dmax, then a new point is added between i and i+1
%   d(i,i+1)<dmin, then either i or i+1 is removed
%
%   NOTE: the spacing of original curve must be close to the
%         range defined by dmax and dmin. For arbitrary spacing,
%         try snakeinterp1.
%
%   See also SNAKEINTERP1

%    there is a bug in the program for points removal

%   Chenyang Xu and Jerry L. Prince, 4/1/95, 6/17/97
%   Copyright (c) 1995-97 by Chenyang Xu and Jerry L. Prince
%   Image Analysis and Communications Lab, Johns Hopkins University
    xi=x;
    yi=y;
% convert to column vector
x = x(:); y = y(:);

N = length(x);

d = abs(x([2:N 1])- x(:)) + abs(y([2:N 1])- y(:));

% remove the points which distance to neighbor points is shorter than dmin
IDX = (d<dmin);

idx = find(IDX==0);
x = x(idx);
y = y(idx);

N = length(x);

if N>0

    d = abs(x([2:N 1])- x(:)) + abs(y([2:N 1])- y(:));

    IDX = (d>dmax);

    z = snakeindex(IDX);

    p = 1:N+1;

    xi = interp1(p,[x;x(1)],z');
    yi = interp1(p,[y;y(1)],z');

    N = length(xi);
    d = abs(xi([2:N 1])- xi(:)) + abs(yi([2:N 1])- yi(:));

    while (max(d)>dmax),

        IDX = (d>dmax);
        z = snakeindex(IDX);

        p = 1:N+1;

        xi = interp1(p,[xi;xi(1)],z');
        yi = interp1(p,[yi;yi(1)],z');

        N = length(xi);
        d = abs(xi([2:N 1])- xi(:)) + abs(yi([2:N 1])- yi(:));
    end

end

author: Sable

repo: mcbench-benchmarks


text:
function [x,fval,exitflag,info] = opti_levmar(fun,grad,x0,ydata,lb,ub,A,b,Aeq,beq,opts)
%OPTI_LEVMAR Solve a NLS using LEVMAR (Levenberg-Marquardt by Manolis Lourakis)
%
%   min sum[ (F(x) - ydata)^2 ]       subject to:   A*x <= b
%    x                                              Aeq*x = beq
%                                                   lb <= x <= ub
%
%   x = opti_levmar(fun,grad,x0,ydata) solves a NLS where fun is the
%   fitting function. grad is an optional gradient of the fitting function
%   and x0 is a starting guess. ydata is the data to fit the function to.
%
%   x = opti_levmar(fun,grad,x0,ydata,lb,ub) solves subject to decision
%   variables bounds lb <= x <= ub. Avoid Infinite bounds.
%
%   x = opti_levmar(fun,...,ub,A,b) solves subject to the linear
%   inequalities Ax <= b.
%
%   x = opti_levmar(fun,...,b,Aeq,beq) solves subject to the linear
%   equalities Aeqx = beq.
%
%   x = opti_levmar(fun,...,beq,opts) uses opts to pass optiset options to
%   the solver.
%
%   [x,fval,exitflag,info] = opti_levmar(...) returns the objective value
%   at the solution, together with the solver exitflag, and an information
%   structure.
%
%   THIS IS A WRAPPER FOR LEVMAR
%   See referenced GNU Public License

%   Copyright (C) 2012 Jonathan Currie (I2C2)

if(nargin < 11), opts = optiset; end
if(nargin < 10), beq = []; end
if(nargin < 9), Aeq = []; end
if(nargin < 8), b = []; end
if(nargin < 7), A = []; end
if(nargin < 6), ub = []; end
if(nargin < 5), lb = []; end
if(nargin < 4), error('LEVMAR requires at least 4 arguments'); end

%Setup display level
opts.display = dispLevel(opts.display);

%Check we have a valid x0
if(isempty(x0) || any(isnan(x0)))
    error('LEVMAR requires an initial guess, x0!');
end

t = tic;
% Run LEVMAR
[x, fval, exitflag, iter, feval] = levmar(fun,grad,x0,ydata,lb,ub,A',b,Aeq',beq,opts);

%Collect Results
info.Iterations = iter;
info.FuncEvals = feval;
info.Time = toc(t);
info.Algorithm = 'LEVMAR: Levenberg-Marquardt in C/C++';

switch(exitflag)
    case 1
        info.Status = 'Optimal';
    case 0
        info.Status = 'Exceeded Iterations';
    case -1
        info.Status = 'Infeasible / Could not Converge';
    case -2
        info.Status = 'LEVMAR Error';
    otherwise
        info.Status = 'LEVMAR Error';
end

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
%% Example
% This script is used to detect the double touch of the kuka end effector
% in the Z direction

% Mohammad SAFEEA, 20th of May 2017

close all,clear all,clc

global binaryValArray
global averageVal
binaryValArray=zeros(40,1);
averageVal=0;

fprintf('Double touch the robot up to hear the event')

ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
t=net_establishConnection( ip );

if ~exist('t','var') || isempty(t)
  warning('Connection could not be establised, script aborted');
  return;
else

    num=60*100; % for 1 minute
    for(i=1:num)
        pause(0.01);
        performEventFunctionAtDoubleHit(t);
    end

      %% turn off the server
       net_turnOffServer( t );

       fclose(t);
end

repo: KST-Kuka-Sunrise-Toolbox


text:
function [J, grad] = linearRegCostFunction(X, y, theta, lambda)
%LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear
%regression with multiple variables
%   [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the
%   cost of using theta as the parameter for linear regression to fit the
%   data points in X and y. Returns the cost in J and the gradient in grad

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost and gradient of regularized linear
%               regression for a particular choice of theta.
%
%               You should set J to the cost and grad to the gradient.
%

% We can reuse ex1's computeCost() but it be messier and slower
h0 = X*theta;
J = (sum((h0 - y) .^ 2) + lambda*sum(theta(2:end) .^ 2))/(2*m);

grad = (1/m)*(X'*(h0-y)) + [0; (lambda/m)*theta(2:end)];

% =========================================================================

grad = grad(:);

end

author: SaveTheRbtz

repo: ml-class


text:
function [X, sigma2, W, model, modelInitVardist] = vargplvmEmbed2(Y, dims, varargin)
% VARGPLVMEMBED2 Embed given data Y into a lower dimensional manifold with Bayesian GP-LVM
%
% COPYRIGHT: Andreas C. Damianou, 2012
%
% VARGPLVM

% [X, sigma2, W, model, modelInitVardist] = vargplvmEmbed(Y, dims, varargin)
%
% varargin = {options, initIters, iters, display, optionsDyn}
% To do dynamical embedding, just call the function with all arguments in
% varargin (even if empty values are given, ie
% [..]=vargplvmEmbed2(Y, dims, [],[],[],[],[]);
%
% Like vargplvmEmbed but also has (optional) dynamics

vargplvm_init;

initVardistIters = 15;
iters = 50;
display = 1;

options = vargplvmOptions('dtcvar');
options.kern = 'rbfardjit';
options.numActive = min(50,size(Y,1));
options.optimiser = 'scg2';
options.initSNR = 100;
dynUsed = 0;
optionsDyn = [];

if nargin > 2
    if ~isempty(varargin{1})
        options = varargin{1};
    end
    if length(varargin)>1 && ~isempty(varargin{2}), initVardistIters = varargin{2}; end
    if length(varargin)>2 && ~isempty(varargin{3}), iters = varargin{3}; end
    if length(varargin)>3 && ~isempty(varargin{4}), display = varargin{4}; end
    if length(varargin)>4
        dynUsed=1;
        if ~isempty(varargin{5})
            optionsDyn = varargin{5};
        end
    end
end

globalOpt.initSNR = options.initSNR;

latentDim = dims;
d = size(Y, 2);

% demo using the variational inference method for the gplvm model
model = vargplvmCreate(latentDim, d, Y, options);
%
model = vargplvmParamInit(model, model.m, model.X);
model = vargplvmModelInit(model, globalOpt);

fprintf('#--- vargplvmEmbed from %d dims to %d dims (initSNR=%f)...\n',d,latentDim,vargplvmShowSNR(model, false));

if dynUsed
    %-------- Add dynamics to the model -----
    fprintf('  # Adding dynamics to the model...\n')
    if isempty(optionsDyn)
        optionsDyn.type = 'vargpTime';
        optionsDyn.t=[];
        optionsDyn.inverseWidth=30;
        optionsDyn.initX = model.X;%options.initX;
    end
    if ~isfield(optionsDyn, 'initX'), optionsDyn.initX = model.X; end
    % Fill in with default values whatever is not already set
    optionsDyn = vargplvmOptionsDyn(optionsDyn, model.X);
    optionsDyn.initX = options.initX;
    model = vargplvmAddDynamics(model, 'vargpTime', optionsDyn, optionsDyn.t, 0, 0,optionsDyn.seq);
    model = vargplvmInitDynamics(model,optionsDyn);
end

modelInit = model;%%%% Delete
%if dynUsed
%    model.dynamics.kern.comp{2}.variance = 1;
%end
% Optimise the model.
fprintf('  # vargplvmEmbed: Optimising var. distr. for %d iters...\n',initVardistIters);
if initVardistIters > 0
    model.initVardist = 1; model.learnSigmaf = false;
    model = vargplvmOptimise(model, display, initVardistIters);
end
modelInitVardist = model;
model.initVardist = false; model.learnSigmaf = true;
if ~isempty(iters)
    for i=1:length(iters)
        fprintf('\n  # vargplvmEmbed: Optimising for %d iters... (Session %d) \n',iters(i),i);
        model = vargplvmOptimise(model, display, iters(i));
    end
end
X = model.vardist.means;
sigma2 = model.vardist.covars;
W = vargplvmScales('get', model);

SNRfinal = vargplvmShowSNR(model, false);
fprintf('#--- Finished embedding. SNR: %f \n',SNRfinal);
fprintf('#--- Scales: %s\n\n', num2str(W));
if SNRfinal < 10
    warning(['During vargplvmEmbed SNR was too low (' num2str(SNRfinal) ')!'])
end

author: SheffieldML

repo: vargplvm


text:
% Script to report the bug of inconsistent
% Behavior when linear indexing sparse matrix on 32-bit platform
% Bruno Luong <b.luong@fogale.fr>

if ~isempty(strfind(computer(),'64'))
    fprintf('Test valid only on 32-bit machine\n')
    return
end

if datenum(version('-date'))>datenum('03-Apr-2009')
    fprintf('This bug could be already fixed after v.2009A (?).\n')
end

m=66050;
n=65026;
icritical=mod(m*n,2^32)+1;
S=sparse([1 m],[1 n],[1 2],m,n) % Error not occurs for size=3e5

ind=[1 icritical];

disp('ind')
disp(ind)

% Flag to tell if Matlab is buggy
Buggy = 0;

% OK, access both index separately
disp('OK: access both index separately')
disp('S(ind(1))');
disp(S(ind(1))) % 1
disp('S(ind(2))');
disp(S(ind(2))); % 2

% Not OK, access both index at the same time
try
    % ??? Index exceeds matrix dimensions.
    disp('Not OK: access both index at the same time');
    disp('S(ind)');
    disp(S(ind)); % error
catch
    Buggy = 1;
    fprintf('\t-> Error: %s\n\n', lasterr());
end

% OK, acess with large double linear index
disp('OK: acess with large double linear index ');
disp('S(icritical)');
disp(S(icritical)); % 2

disp('OK: acess with "small" double linear index ');
disp('S(icritical-1)');
disp(S(icritical-1)); % 0

% Not OK, acess with large integer linear index
try
    % ??? Index exceeds matrix dimensions.
    disp('Not OK: acess with large integer linear index ');
    disp('S(int32(icritical))');
    disp(S(int32(icritical))); % error
catch
    Buggy = 1;
    fprintf('\t-> Error: %s\n\n', lasterr());
end

if Buggy
    fprintf('You have a matlab that have a bug in linear indexing\n');
else
    fprintf('Congratulation your sparse linear-index is working fine\n');
end


text:
% Copyright 2013 Oliver Johnson, Srikanth Patala
%
% This file is part of MisorientationMaps.
%
%     MisorientationMaps 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.
%
%     MisorientationMaps 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 MisorientationMaps.  If not, see <http://www.gnu.org/licenses/>.

function S=colormap222(v)

pts = reshape(double(v),[],3);

k1 = sqrt(3)*max(pts,[],2)./(sum(pts,2) + 1*(sum(pts,2) == 0));
pts = [k1.*pts(:,1) k1.*pts(:,2) k1.*pts(:,3)];

%%% Rotate Prism %%%%%%%%
g1 = rotvec2mat([1,1,1,pi/4]);g2 = rotvec2mat([-1,1,0,acos(1/sqrt(3))]);
g3 = rotvec2mat([0,0,1,-pi/3]);pts = pts*g1*g2*g3;pts(:,3)=pts(:,3)-1;

%%%%%% Prism --> Cone %%%%%%%%%%%
phi=atan2(pts(:,2),pts(:,1));maxphi = 2*pi; phi = mod(phi,maxphi);
rfin = hypot(pts(:,1),pts(:,2)).*sin(pi/6+mod(phi,2*pi/3))./(sin(pi/6));
pts = [sqrt(1/2).*rfin.*cos(phi) sqrt(1/2).*rfin.*sin(phi) pts(:,3)];

%%%%%% Cone --> Hemisphere %%%%%%
r = sqrt(pts(:,1).^2 + pts(:,2).^2 + pts(:,3).^2);
rad = sqrt(pts(:,1).^2 + pts(:,2).^2);

pts = [pts(:,1).*(rad - pts(:,3))./(r+1*(r==0)) ...
    pts(:,2).*(rad - pts(:,3))./(r+1*(r==0)) ...
    pts(:,3).*(rad - pts(:,3))./(r+1*(r==0))];

%%%%% Hemisphere --> Sphere

phi1 = atan2(pts(:,2),pts(:,1));phi1 = mod(phi1,2*pi);
ind1=find(phi1 < 2*pi/3 & phi1 > 0*pi/3);ind2=find(phi1 < 4*pi/3 & phi1 > 2*pi/3);
ind3=find(phi1 < 6*pi/3 & phi1 > 4*pi/3);ind = [ind1;ind2;ind3];

g4 = rotvec2mat([0,0,1,pi/3]);g5 = rotvec2mat([0,0,1,pi]);g6 = rotvec2mat([0,0,1,5*pi/3]);
pts(ind1,:) = pts(ind1,:)*g4;pts(ind2,:) = pts(ind2,:)*g5;pts(ind3,:) = pts(ind3,:)*g6;

phi2 = atan2(pts(ind,2),pts(ind,1));rad1 = hypot(pts(ind,2),pts(ind,1));
pts(ind,:) = [rad1.*cos(3*phi2/2) rad1.*sin(3*phi2/2) pts(ind,3)];

mult = 1 + 1;
phi4 = atan2(pts(ind,1),-pts(ind,3));rad4 = hypot(pts(ind,1),pts(ind,3));
pts(ind,:) = [rad4.*sin(mult*phi4) pts(ind,2) rad4.*-cos(mult*phi4)];

phi3 = atan2(pts(ind,2),pts(ind,1));rad3 = hypot(pts(ind,2),pts(ind,1));
pts(ind,:) = [rad3.*cos(2*phi3/3) rad3.*sin(2*phi3/3) pts(ind,3)];

pts(ind1,:) = pts(ind1,:)*g4';pts(ind2,:) = pts(ind2,:)*g5';pts(ind3,:) = pts(ind3,:)*g6';

g1 = rotvec2mat([0,0,1,pi/3]);
pts=pts*g1;

S = hsvsphere(pts);

author: mtex-toolbox

repo: mtex

save_path: github-repos/MATLAB/mtex-toolbox-mtex


text:
function main
%
% This is a demo program of the paper J. Tian, L. Ma, and W. Yu, "Ant
% colony optimization for wavelet-based image interpolation using a
% three-component exponential mixture model," Expert Systems with
% Applications, Vol. 38, No. 10, Sept. 2011, pp. 12514-12520.
%
% Contact: eejtian@gmail.com
%
% Note that the PSNR values could be slightly different with that reported
% in paper due to the random number generator.
%
% The input image should have a square size.
%
% Acknowledgement: This program needs Wavelet transform toolbox, which is
% downloaded from http://www-stat.stanford.edu/~wavelab/.

clear all; close all; clc;

img_truth = im2double(imread('lena_truth.bmp'));

% Generate low-resolution image
psf_filter =  fspecial('average', 3);
img_in = imfilter(img_truth, psf_filter, 'symmetric');
wfilter_type = 'bior2.2';
[Lo_D,Hi_D,Lo_R,Hi_R] = wfilters(wfilter_type);
Lo_D = Lo_D ./ sqrt(2);
Hi_D = Hi_D ./ sqrt(2);
Lo_R = Lo_R .* sqrt(2);
Hi_R = Hi_R .* sqrt(2);
[ca1,ch1,cv1,cd1] = dwt2(img_in, Lo_D, Hi_D, 'mode', 'per');
img_low = ca1;

%--------------------------------------------------------------------------
%-------------- PASS 1: Generate mask using ACO for interpolation ---------
%--------------------------------------------------------------------------
[ca1,ch1,cv1,cd1] = dwt2(img_low, Lo_D, Hi_D, 'mode', 'per');
[ca2,ch2,cv2,cd2] = dwt2(ca1, Lo_D, Hi_D, 'mode', 'per');

ch1_mask = func_aco_thresholding_estimate_mask(ch1);
cv1_mask = func_aco_thresholding_estimate_mask(cv1);
cd1_mask = func_aco_thresholding_estimate_mask(cd1);
ch2_mask = func_aco_thresholding_estimate_mask(ch2);
cv2_mask = func_aco_thresholding_estimate_mask(cv2);
cd2_mask = func_aco_thresholding_estimate_mask(cd2);

%--------------------------------------------------------------------------
%-------------- PASS 2: Image interpolation in wavelet domain -------------
%--------------------------------------------------------------------------
% Parameter setting
img_in = img_low;
nEnlargeFactor = 2;
win_size = 7;
nTotalIteration = 10;

[ca1,ch1,cv1,cd1] = dwt2(img_in, Lo_D, Hi_D, 'mode', 'per');
[ca2,ch2,cv2,cd2] = dwt2(ca1, Lo_D, Hi_D, 'mode', 'per');

[ch1_par1, ch1_par2, ch1_par3] = func_proposed_three_state_estimation_aco_seg(ch1, ch1_mask, win_size);
[ch2_par1, ch2_par2, ch2_par3] = func_proposed_three_state_estimation_aco_seg(ch2, ch2_mask, win_size);
[cd1_par1, cd1_par2, cd1_par3] = func_proposed_three_state_estimation_aco_seg(cd1, cd1_mask, win_size);
[cd2_par1, cd2_par2, cd2_par3] = func_proposed_three_state_estimation_aco_seg(cd2, cd2_mask, win_size);
[cv1_par1, cv1_par2, cv1_par3] = func_proposed_three_state_estimation_aco_seg(cv1, cv1_mask, win_size);
[cv2_par1, cv2_par2, cv2_par3] = func_proposed_three_state_estimation_aco_seg(cv2, cv2_mask, win_size);

% Variance estimation
ch0_par1 = func_proposed_par_propogation(ch1_par1,ch2_par1,nEnlargeFactor);
cv0_par1 = func_proposed_par_propogation(cv1_par1,cv2_par1,nEnlargeFactor);
cd0_par1 = func_proposed_par_propogation(cd1_par1,cd2_par1,nEnlargeFactor);

ch0_par2 = func_proposed_par_propogation(ch1_par2,ch2_par2,nEnlargeFactor);
cv0_par2 = func_proposed_par_propogation(cv1_par2,cv2_par2,nEnlargeFactor);
cd0_par2 = func_proposed_par_propogation(cd1_par2,cd2_par2,nEnlargeFactor);

ch0_par3 = func_proposed_par_propogation(ch1_par3,ch2_par3,nEnlargeFactor);
cv0_par3 = func_proposed_par_propogation(cv1_par3,cv2_par3,nEnlargeFactor);
cd0_par3 = func_proposed_par_propogation(cd1_par3,cd2_par3,nEnlargeFactor);

% Coefficient index extrapolation
ch0_mask = imresize(ch1_mask, size(ch1_mask)*nEnlargeFactor, 'nearest');
cv0_mask = imresize(cv1_mask, size(cv1_mask)*nEnlargeFactor, 'nearest');
cd0_mask = imresize(cd1_mask, size(cd1_mask)*nEnlargeFactor, 'nearest');

rand('state',sum(100*clock));
ch0_mask_change = rand(size(ch0_mask));
ch0_mask_change = (ch0_mask_change>=0.5);
ch0_mask = (ch0_mask==1).*(ch0_mask_change==1).*0 + (ch0_mask==1).*(ch0_mask_change==0).*1 ...
            + (ch0_mask==-1).*(ch0_mask_change==1).*0 + (ch0_mask==-1).*(ch0_mask_change==0).*-1 ...
            + (ch0_mask==0).*ch0_mask;

cv0_mask_change = rand(size(cv0_mask));
cv0_mask_change = (cv0_mask_change>=0.5);
cv0_mask = (cv0_mask==1).*(cv0_mask_change==1).*0 + (cv0_mask==1).*(cv0_mask_change==0).*1 ...
            + (cv0_mask==-1).*(cv0_mask_change==1).*0 + (cv0_mask==-1).*(cv0_mask_change==0).*-1 ...
            + (cv0_mask==0).*cv0_mask;

cd0_mask_change = rand(size(ch0_mask));
cd0_mask_change = (ch0_mask_change>=0.5);
cd0_mask = (cd0_mask==1).*(cd0_mask_change==1).*0 + (cd0_mask==1).*(cd0_mask_change==0).*1 ...
            + (cd0_mask==-1).*(cd0_mask_change==1).*0 + (cd0_mask==-1).*(cd0_mask_change==0).*-1 ...
            + (cd0_mask==0).*cd0_mask;

% Generate the highest subbands
result = zeros(size(img_in,1).*nEnlargeFactor, size(img_in,2).*nEnlargeFactor);

for ii=1:nTotalIteration
    ch0 = func_proposed_gen_subband(ch0_par1, ch0_par2, ch0_par3, ch0_mask);
    cv0 = func_proposed_gen_subband(cv0_par1, cv0_par2, cv0_par3, cv0_mask);
    cd0 = func_proposed_gen_subband(cd0_par1, cd0_par2, cd0_par3, cd0_mask);
    temp = idwt2(img_in,ch0,cv0,cd0, Lo_R, Hi_R, 'mode', 'per');
    temp(temp<0) = 0;
    temp(temp>1) = 1;
    result = result + temp./nTotalIteration;
end

% Write the output image and perform PSNR evaluation
fprintf('The psnr is %.2f dB \n', func_psnr_gray(img_truth.*255, result.*255));
imwrite(uint8(result.*255), ['lena_rec.bmp'], 'bmp');

% *************************************************************************
% **************************Inner Function ********************************
% *************************************************************************
function result = func_aco_thresholding_estimate_mask(wxin)

ant_search_range_row_min = ones(size(wxin));
ant_search_range_row_max = ones(size(wxin)).*size(wxin,1);
ant_search_range_col_min = ones(size(wxin));
ant_search_range_col_max = ones(size(wxin)).*size(wxin,2);

% System setup
ant_move_step_within_iteration = 15;
total_iteration_num = 10;
search_clique_mode = 8;

wx = abs(wxin);
[nrow, ncol] = size(wx);
wx_1D = func_2D_LexicoOrder(wx);

% initialization
h = zeros(size(wx));
h_1D = func_2D_LexicoOrder(h);
p = 1./(wx.*(wx~=0)+1.*(wx==0)).*(wx~=0)+(wx==0);
p_1D = func_2D_LexicoOrder(p);

alpha = 1;
beta = 2;
rho = 0.1;
w = 0.6;
A = 5000;
B = 10;

%use one ant for each pixel position
ant_total_num = nrow*ncol;
ant_current_row = zeros(ant_total_num, 1);
ant_current_col = zeros(ant_total_num, 1);
ant_current_val = zeros(ant_total_num, 1);
rr = (meshgrid(1:nrow))'; cc = meshgrid(1:ncol);
ant_current_row = rr(:);
ant_current_col = cc(:);
ant_current_val = wx_1D((ant_current_row-1).*ncol+ant_current_col);

ant_search_range_row_min = ant_search_range_row_min(:);
ant_search_range_row_min = padarray(ant_search_range_row_min, [0 search_clique_mode-1],'replicate','post');
ant_search_range_row_max = ant_search_range_row_max(:);
ant_search_range_row_max = padarray(ant_search_range_row_max, [0 search_clique_mode-1],'replicate','post');
ant_search_range_col_min = ant_search_range_col_min(:);
ant_search_range_col_min = padarray(ant_search_range_col_min, [0 search_clique_mode-1],'replicate','post');
ant_search_range_col_max = ant_search_range_col_max(:);
ant_search_range_col_max = padarray(ant_search_range_col_max, [0 search_clique_mode-1],'replicate','post');

for nIteration = 1: total_iteration_num

    ant_current_path_val_mean = zeros(ant_total_num,1);
    ant_current_path_val_mean = ant_current_val;

    for nMoveStep = 1: ant_move_step_within_iteration-1

        if search_clique_mode == 4
            ant_search_range_row = [ant_current_row-1, ant_current_row, ant_current_row+1, ant_current_row];
            ant_search_range_col = [ant_current_col, ant_current_col+1, ant_current_col, ant_current_col-1];
        elseif search_clique_mode == 8
            ant_search_range_row = [ant_current_row-1, ant_current_row-1, ant_current_row-1, ant_current_row, ant_current_row,ant_current_row+1, ant_current_row+1, ant_current_row+1];
            ant_search_range_col = [ant_current_col-1, ant_current_col, ant_current_col+1, ant_current_col-1, ant_current_col+1, ant_current_col-1, ant_current_col, ant_current_col+1];
        end

        ant_current_row_extend = padarray(ant_current_row, [0 search_clique_mode-1],'replicate','post');
        ant_current_col_extend = padarray(ant_current_col, [0 search_clique_mode-1],'replicate','post');
        ant_search_range_val = zeros(ant_total_num,search_clique_mode);

        %replace the positions our of the image's range

        temp = (ant_search_range_row>=ant_search_range_row_min) & (ant_search_range_row<=ant_search_range_row_max) & (ant_search_range_col>=ant_search_range_col_min) & (ant_search_range_col<=ant_search_range_col_max);
        ant_search_range_row = temp.*ant_search_range_row + (~temp).*ant_current_row_extend;
        ant_search_range_col = temp.*ant_search_range_col + (~temp).*ant_current_col_extend;

        ant_search_range_transit_prob_h = zeros(size(ant_search_range_val));
        ant_search_range_transit_prob_p = zeros(size(ant_search_range_val));

        for ii=1:search_clique_mode
            ant_search_range_val(:,ii) = wx_1D((ant_search_range_row(:,ii)-1).*ncol+ant_search_range_col(:,ii));

            temp = ant_search_range_val(:,ii);
            temp = abs(temp - ant_current_path_val_mean);
            temp = 1./(temp.*(temp~=0)+1.*(temp==0)) .* (temp~=0)+(temp==0);

            ant_search_range_transit_prob_h(:,ii) = temp;
            ant_search_range_transit_prob_p(:,ii) = p_1D((ant_search_range_row(:,ii)-1).*ncol+ant_search_range_col(:,ii));

        end
        temp = (ant_search_range_transit_prob_h.^alpha) .* (ant_search_range_transit_prob_p.^beta);

        temp_sum = sum(temp,2);
        temp_sum = padarray(temp_sum, [0 search_clique_mode-1],'replicate','post');

        ant_search_range_transit_prob = temp ./ temp_sum;

        % generate a random number to determine the next position.
        rand('state', sum(100*clock));
        temp = rand(ant_total_num,1);
        temp = padarray(temp, [0 search_clique_mode-1],'replicate','post');
        temp = cumsum(ant_search_range_transit_prob,2)>=temp;
        temp = padarray(temp, [0 1],'pre');
        temp = (diff(temp,1,2)==1);

        temp_row = (ant_search_range_row .* temp)';
        [ii, jj, vv] = find(temp_row);
        ant_next_row = vv;
        temp_col = (ant_search_range_col .* temp)';
        [ii, jj, vv] = find(temp_col);
        ant_next_col = vv;

        ant_current_row = ant_next_row;
        ant_current_col = ant_next_col;
        ant_current_val = wx_1D((ant_current_row-1).*ncol+ant_current_col);
        ant_current_path_val_mean = (ant_current_path_val_mean.*nMoveStep + ant_current_val)/(nMoveStep+1);

        rr = ant_current_row;
        cc = ant_current_col;
        p_1D((rr-1).*ncol+cc,1) = w*p_1D((rr-1).*ncol+cc,1) + 1./(A+B.*ant_current_path_val_mean);
        p = func_LexicoOrder_2D(p_1D, nrow, ncol);

    end % end of nMoveStep

    p = (1-rho).*p;
    p_1D = func_2D_LexicoOrder(p);

end % end of nIteration

clear h h_1D temp
clear ant_current_row ant_current_col ant_current_val
clear ant_current_path_val_mean
clear ant_search_range_row search_range_path_col ant_search_range_val
clear ant_search_range_transit_prob_h ant_search_range_transit_prob_v ant_search_range_transit_prob
clear ant_search_range_row_min ant_search_range_row_max ant_search_range_col_min ant_search_range_col_max

result = func_determine_class_fcm(wxin, p);

% ******************************************************************************
% **************************Inner Function *************************************
% ******************************************************************************

function idx = func_determine_class_fcm(wxin, p)
wx = abs(wxin);
p_1D = func_2D_LexicoOrder(p);
wx_1D = func_2D_LexicoOrder(wx);
[nrow, ncol] = size(wx);

nFeature(:,1) = p_1D(:)./(max2(p_1D));
nFeature(:,2) = wx_1D(:)./(max2(wx_1D));
[center,U,obj_fcn] = fcm(nFeature, 2,[2.0 100 1e-5 0]);

idx = zeros(nrow:ncol,1);
if sum(sum(U(1,:) >= U(2,:))) >= sum(sum(U(1,:) < U(2,:)))
    idx = (U(1,:) < U(2,:));
else
    idx = (U(1,:) >= U(2,:));
end
idx = func_LexicoOrder_2D(idx, nrow, ncol);
idx = double(idx);
idx((idx==1)&(wxin<0)) = -1;
idx((idx==1)&(wxin>=0)) = 1;
idx(idx==0) = 0;

% *************************************************************************
% **************************Inner Function ********************************
% *************************************************************************
function result = func_LexicoOrder_2D(x, nRow, nColumn)
result = reshape(x, nColumn, nRow)';

% *************************************************************************
% **************************Inner Function ********************************
% *************************************************************************
function result = func_2D_LexicoOrder(x)
[nRow, nColumn] = size(x);
temp = x';
result = temp(:);

% *************************************************************************
% **************************Inner Function ********************************
% *************************************************************************
function result = func_psnr_gray(f, g)
f = double(f);
g = double(g);
Q=255;MSE=0;
[M,N]=size(f);
h = f - g;
MSE = sum(sum(h.*h));
MSE=MSE/M/N;
result=10*log10(Q*Q/MSE);

% *************************************************************************
% **************************Inner Function ********************************
% *************************************************************************
function [result1, result2, result3] = func_proposed_three_state_estimation_aco_seg(I, I_mask, win_size)

thre = graythresh(abs(I));
[nrow, ncol] = size(I);
padnum = (win_size-1)/2;
A = padarray(I, [padnum padnum], 'replicate', 'bot');
B = padarray(I_mask, [padnum padnum], 'replicate', 'bot');
A = im2col(A, [win_size win_size],'sliding');
B = im2col(B, [win_size win_size],'sliding');

result1 = (sum(A.*(B==1),1).*(sum((B==1),1)~=0) + 0.*(sum((B==1),1)==0)) ./ (sum((B==1),1) + (sum((B==1),1)==0).*1);
result1 = reshape(result1, size(I));
result2 = (sum(A.*(B==-1),1).*(sum((B==-1),1)~=0) + 0.*(sum((B==-1),1)==0)) ./ (sum((B==-1),1) + (sum((B==-1),1)==0).*1);
result2 = reshape(result2, size(I));
result3 = (sum(A.*A.*(B==0),1).*(sum((B==0),1)~=0) + 0.*(sum((B==0),1)==0)) ./ (sum((B==0),1) + (sum((B==0),1)==0).*1);
result3 = reshape(result3, size(I));

% *************************************************************************
% **************************Inner Function ********************************
% *************************************************************************
function ch0_var = func_proposed_par_propogation(ch1_var,ch2_var,nEnlargeFactor)

temp1 = imresize(ch1_var, size(ch1_var)*nEnlargeFactor, 'nearest').^2;
temp2 = imresize(ch2_var, size(ch2_var)*2*nEnlargeFactor, 'nearest');
ch0_var = ((temp2~=0).*temp1+(temp2==0).*0)./ ((temp2~=0).*temp2 + (temp2==0).*1);

% *************************************************************************
% **************************Inner Function ********************************
% *************************************************************************
function result = func_proposed_gen_subband(I_par1, I_par2, I_par3, I_mask)

rand('state',sum(100*clock));
result1 = exprnd(I_par1);
result2 = exprnd(I_par2);
result3 = randn(size(I_par3)).*sqrt(I_par3);
result1(isnan(result1))=0;
result2(isnan(result2))=0;
result3(isnan(result3))=0;
result = (I_mask==1).*result1 + (I_mask==-1).*result2 + (I_mask==0).*result3;


text:
function sftpack_test ( )

%*****************************************************************************80
%
%% SFTPACK_TEST tests the SFTPACK library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 August 2010
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SFTPACK_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the SFTPACK library.\n' );

  sftpack_test01 ( );
  sftpack_test02 ( );
  sftpack_test03 ( );
  sftpack_test04 ( );
  sftpack_test05 ( );
  sftpack_test06 ( );
  sftpack_test07 ( );
  sftpack_test08 ( );

  sftpack_test11 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SFTPACK_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


text:
function v = wing(size)

%WING Create a wing graphics 3D object.
%   WING creates a multi-patch object representing a plane, sort of a
%   hang-glider wing.
%
%   WING(SIZE) allows for choosing the wing's size. Default is 1.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

if nargin == 0
    size = 1;
end

v.vert0 = [ 0.6  0.0 0.0
           -0.6  1.0 0.0
           -0.4  0.0 0.0
           -0.6 -1.0 0.0
           -0.4  0.0 0.3
            0.0  0.0 0.0] * size/2;

v.vert = v.vert0;
v.faces = [1 2 3 4
           3 5 6 3];

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
function imdb = fmd_get_database(fmdDir, varargin)
opts.seed = 0 ;
opts = vl_argparse(opts, varargin) ;

rng(opts.seed, 'twister') ;

imdb.imageDir = fullfile(fmdDir, 'image') ;
imdb.maskDir = fullfile(fmdDir, 'mask') ;

cats = dir(imdb.imageDir) ;
cats = cats([cats.isdir] & ~ismember({cats.name}, {'.','..'})) ;
imdb.classes.name = {cats.name} ;
imdb.images.id = [] ;

for c=1:numel(cats)
  ims = dir(fullfile(imdb.imageDir, imdb.classes.name{c}, '*.jpg'));
  %imdb.images.name{c} = fullfile(imdb.classes.name{c}, {ims.name}) ;
  imdb.images.name{c} = cellfun(@(S) fullfile(imdb.classes.name{c}, S), ...
    {ims.name}, 'Uniform', 0);
  imdb.images.label{c} = c * ones(1,numel(ims)) ;
  if numel(ims) ~= 100, error('ops') ; end
  sets = [1 * ones(1,40), 2 * ones(1,10), 3 * ones(1,50)] ;
  imdb.images.set{c} = sets(randperm(100)) ;
end
imdb.images.name = horzcat(imdb.images.name{:}) ;
imdb.images.label = horzcat(imdb.images.label{:}) ;
imdb.images.set = horzcat(imdb.images.set{:}) ;
imdb.images.id = 1:numel(imdb.images.name) ;

imdb.segments = imdb.images ;
imdb.segments.imageId = imdb.images.id ;
imdb.segments.mask = strrep(imdb.images.name, 'image', 'mask') ;

% make this compatible with the OS imdb
imdb.meta.classes = imdb.classes.name ;
imdb.meta.inUse = true(1,numel(imdb.meta.classes)) ;
imdb.segments.difficult = false(1, numel(imdb.segments.id)) ;

author: mcimpoi

repo: deep-fbanks

save_path: github-repos/MATLAB/mcimpoi-deep-fbanks


text:
function result=libra_mahalanobis(x,locvct,varargin)

%MAHALANOBIS computes the distance of each observation in x
%   from the location estimate (locvct) of the data,
%   relative to the shape of the data.
%
% Required input arguments:
%                  x : data matrix (n observations in rows, p variables in columns)
%             locvct : location estimate of the data (p-dimensional vector)
%      cov or invcov : scatter estimate of the data or the inverse of the scatter estimate (pxp matrix)
%
% I/O: result=libra_mahalanobis(x,locvct,'cov',covmat,'n',size(x,1),'p',size(x,2))
%   The user should only give the input arguments that have to change their default value.
%   The name of the input arguments needs to be followed by their value.
%   The order of the input arguments is of no importance.
%
% Examples:
%   result=libra_mahalanobis(x,loc,'cov',covx,'n',10)
%   result=libra_mahalanobis(x,loc,'p',2,'invcov',invcovx)
%   result=libra_mahalanobis(x,loc,'invcov',invcovx)
%
% Output:
%   A vector containing the distances of all the observations to locvct.
%
% This function is part of LIBRA: the Matlab Library for Robust Analysis,
% available at:
%              http://wis.kuleuven.be/stat/robust.html
%
% Written by Katrien Van Driessen
% Revisions by Sabine Verboven
% Last update on 18/09/2003
%

%Initialisation
n = size(x,1);
p = size(x,2);
if nargin<3
    error('Missing a required input variable')
end
counter=1;
default=struct('cov',0,'invcov',NaN);
list=fieldnames(default);
options=default;
IN=length(list);
i=1;
%reading the user's input
if nargin>2
    %
    %placing inputfields in array of strings
    %
    for j=1:nargin-2
        if rem(j,2)~=0
            chklist{i}=varargin{j};
            i=i+1;
        end
    end
    %
    %Checking which default parameters have to be changed
    % and keep them in the structure 'options'.
    %
    while counter<=IN
        index=strmatch(list(counter,:),chklist,'exact');
        if ~isempty(index) %in case of similarity
            for j=1:nargin-2 %searching the index of the accompanying field
                if rem(j,2)~=0 %fieldnames are placed on odd index
                    if strcmp(chklist{index},varargin{j})
                        I=j;
                    end
                end
            end
            options=setfield(options,chklist{index},varargin{I+1});
            index=[];
        end
        counter=counter+1;
    end
end
if size(locvct,2)==1
    locvct=locvct'; %converting to a rowvector
end
if options.cov==0 & options.invcov==0
    error('The scatter matrix or its inverse is a required input argument.')
end
%%%%%%MAIN%%%%%%%%%
if ~isnan(options.invcov)
    covmat=options.invcov;
    if min(size(covmat))==1
        covmat=diag(covmat);
    end
else
    if min(size(options.cov))==1
        options.cov=diag(options.cov);
    end
    covmat=pinv(options.cov);
end
hlp=x-repmat(locvct,n,1);
dist=sum(hlp*covmat.*hlp,2)';
result=dist;

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
%   AUTHORSHIP
%   Primary Developer: Stephen Meehan <swmeehan@stanford.edu>
%   Math Lead & Secondary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>
%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%

classdef UmapExamples
    methods(Static)
        function DisplayPub(which)
            disp('PLEASE NOTE:The sample data for this example is made public with the publication');
            fprintf('%s\n\n', UmapExamples.SampleURL(which));
        end

        function url=SampleURL(which)
            switch which
                case 1
                    url='https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4896314/';
                case 2
                    url='https://www.frontiersin.org/articles/10.3389/fimmu.2019.01194/full';
                otherwise
                    url='https://www.pnas.org/content/107/6/2568';

            end
        end
        function sample=SolveClue(sampleClue)
            if isnumeric(sampleClue)
                switch sampleClue
                    case 27
                        UmapExamples.DisplayPub(2);
                        sample='genentech_d1_27D.csv';
                    case 29
                        UmapExamples.DisplayPub(1);
                        sample='s1s2_samusikImported_29D.csv';
                    case 11
                        UmapExamples.DisplayPub(3);

                        sample='balbc_Bcells_Macrophages.csv';
                    case 11.12
                        UmapExamples.DisplayPub(3);
                        sample='sampleBalbcLabeled12k.csv';

                    otherwise
                        error('Do not understand sample clue %d',...
                            sampleClue );
                end
            else
                sample=sampleClue;
            end
        end

        function SplitSlow(sampleClue)
           if nargin<1
               sampleClue=29;
           end
            UstTest.Split(...
                UmapExamples.SolveClue(sampleClue),...
                'ust_test_components', [3 2], ...
                'ust_test_basic_reduction', true, ...
                'cluster_detail', {'most high', 'low'}, ...
                'match_html', 1, 'ust_test_cases', [ 1 4]);
        end

        function SplitFast(sampleClue)
            if nargin<1
               sampleClue=29;
           end
            UstTest.Split(...
                UmapExamples.SolveClue(sampleClue),...
               'ust_test_cases', 1, 'ust_test_basic_reduction', true, ...
                'cluster_detail', {'most high', 'low'}, 'match_html', 1);
        end

        function SplitFastest(sampleClue)
            if nargin<1
                sampleClue=29;
            end
            UstTest.Split(...
                UmapExamples.SolveClue(sampleClue),...
                'cluster_detail', 'most high',...
                'ust_test_components', 3,...
                'ust_test_cases', 1, 'ust_test_basic_reduction', false, ...
                'match_html', 1, 'match_supervisors', 3 , ...
                'match_scenarios', 4);
        end

        %The sample data for this example is made public with the publication
        %https://www.frontiersin.org/articles/10.3389/fimmu.2019.01194/full
        function Genentech(clusterDetail, scenarios, matchTypes)
            if nargin<3
                matchTypes=1;
                if nargin<2
                    scenarios=[];
                    if nargin<1
                        clusterDetail={};
                    end
                end
            end
            if isempty(scenarios)
                scenarios=[1 4];
            end
            if isempty(clusterDetail)
                clusterDetail={'most high', 'low'};
            end
            if ischar(clusterDetail)
                clusterDetail={clusterDetail};
            end
            UmapExamples.DisplayPub(2);
            run_umap('genentech_d1_27D_70k.csv', ...
                'label_file', 'genentech_d1_27D.properties', ...
                'label_column', 'end', ...
                'template_file', 'genentech_d1_27D_3D.mat',...
                'see_training', true, ...
                'cluster_detail', clusterDetail, ...
                'color_file', 'colorsByName.properties',...
                'match_supervisors', matchTypes, ...
                'match_histogram_fig', false,...
                'match_html', -1, 'match_scenarios', scenarios);
        end

        function Samusik(clusterDetail, scenarios, matchTypes, ...
                sampleSetClue, sampleClue, templateClue, nn, D)
            if nargin<8
                D=3;
                if nargin<7
                    nn=15;
                    if nargin<6
                        templateClue=1;
                        if nargin<5
                            sampleClue=2;
                            if nargin<4
                                sampleSetClue=29;
                                if nargin<3
                                    matchTypes=3;
                                    if nargin<2
                                        scenarios=[];
                                        if nargin<1
                                            clusterDetail={};
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
            if isempty(scenarios)
                scenarios=[1 4];
            end
            if isempty(clusterDetail)
                clusterDetail='most high';
            end
            if ischar(clusterDetail)
                clusterDetail={clusterDetail};
            end
            [tmplt, ss]=UstTest.Supervise(sampleSetClue, templateClue, ...
                true, D, nn);
            smpl=['s' num2str(sampleClue) '_' ss ];
            rf=fullfile(UmapUtil.LocalSamplesFolder, 'ustTest.pair');
            mf=sprintf('%s_s%d_t%d__mt%s__ms%s_%dnn_%dD', ss, ...
                sampleClue, templateClue, String.Num2Str(matchTypes), ...
                String.Num2Str(scenarios),  nn, D);
            run_umap([smpl '.csv'], ...
                'label_file', [smpl '.properties'], ...
                'label_column', 'end', ...
                'template_file', tmplt ,...
                'see_training', true, ...
                'cluster_detail', clusterDetail, ...
                'color_file', 'colorsByName.properties',...
                'match_supervisors', matchTypes, ...
                'match_histogram_fig', false,...
                'match_html', 1, ...
                'result_folder', rf,...
                'match_file', mf, ...
                'match_scenarios', scenarios);
        end

        %The sample data for this example is made public with the publication
        %https://www.pnas.org/content/107/6/2568
        function Balbc12(clusterDetail, scenarios, matchTypes)
            if nargin<3
                matchTypes=1;
                if nargin<2
                    scenarios=[];
                    if nargin<1
                        clusterDetail={};
                    end
                end
            end
            if isempty(scenarios)
                scenarios=4;
            end
            if isempty(clusterDetail)
                clusterDetail={'most high'};
            end
            if ischar(clusterDetail)
                clusterDetail={clusterDetail};
            end
            rf=fullfile(UmapUtil.LocalSamplesFolder, 'ustTest.pair');
            [~,~,~,extras]=run_umap('sampleBalbcLabeled12k.csv', ...
                'label_file', 'balbcLabels.properties', ...
                'label_column', 'end', ...
                'template_file', 'ustBalbc3D.mat',...
                'see_training', true, ...
                'cluster_detail', clusterDetail, ...
                'color_file', 'colorsByName.properties',...
                'match_supervisors', matchTypes, ...
                'match_histogram_fig', false,...
                'result_folder', rf, ...
                'match_html', -1, ...
                'match_scenarios', scenarios);
            records=extras.getFalsePosNeg;
            if ~isempty(records)
                extras.getFalsePosNeg(true);
                extras.saveMatchFiles;
                FalsePositiveNegative.Plot([0 1], extras.falsePosNegFile);
            end
        end

        %The sample data for this example is made public with the publication
        %https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4896314/
        function PairSamusikManual(D, nn)
            if nargin<2
                D=3;
                if nargin<1
                    nn=15;
                end
            end
            UmapExamples.DisplayPub(1);
            UstTest.Pair(1, [2 10], 29.2, 'verbose', 'text', 'match_supervisors', 1:4, 'ust_test_basic_reduction', false, 'match_table_fig', true, 'match_scenarios', [1 2 3 4], 'ust_test_components', D, 'n_neighbors', nn);
        end

        %The sample data for this example is made public with the publication
        %https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4896314/
        function PairSamusikImport(nn, D, testSets, synthesize, templateClue)
            if nargin<5
                templateClue=1;
                if nargin<4
                    synthesize=0;
                    if nargin<3
                        testSets=[2 10];
                        if nargin<2
                            D=3;
                            if nargin<1
                                nn=30;
                            end
                        end
                    end
                end
            end
            UmapExamples.DisplayPub(1);
            UstTest.Pair(templateClue, testSets, 29, ...
                'ust_test_synthesize', synthesize, ...
                'verbose', 'text', ...
                'match_supervisors', 3, ...
                'ust_test_basic_reduction', false, ...
                'match_scenarios', 4, ...
                'ust_test_components', D, 'n_neighbors', nn);
        end

        %The sample data for this example is made public with the publication
        %https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4896314/
        function PairSamusikImport19(nn, D)
            if nargin<2
                D=3;
                if nargin<1
                    nn=15;
                end
            end
            UmapExamples.DisplayPub(1);
            UstTest.Pair(1, [2 10], 19, 'verbose', 'text', 'match_supervisors', 3, 'ust_test_basic_reduction', false, 'match_table_fig', true, 'match_scenarios', 4, 'ust_test_components', D, 'n_neighbors', nn);
        end

        %The sample data for this example is made public with the publication
        %https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4896314/
        function PairSamusikNn(nn)
            if nargin<1
                nn=20;
            end
            UmapExamples.DisplayPub(1);
            UstTest.Pair(1, 2, 29, 'verbose', 'graphic', 'match_supervisors', 1:4, 'ust_test_basic_reduction', true, 'match_table_fig', true, 'match_scenarios', 4, 'ust_test_components', 3, 'n_neighbors', nn);
        end

        %The sample data for this example is made public with the publication
        %https://www.pnas.org/content/107/6/2568
        function SplitBalbc55
            UmapExamples.DisplayPub(3);
            UstTest.Split('sampleBalbcLabeled55k.csv',...
                'ust_test_cases', 1, 'ust_test_basic_reduction', false, ...
                'cluster_detail', {'most high', 'low'}, 'match_html', 1, ...
                'match_scenarios', [ 1 3 4 ], 'match_supervisors', [1 3]);
        end

        %The sample data for this example is made public with the publication
        %https://www.pnas.org/content/107/6/2568
        function SplitBalbc55withBasic
            UmapExamples.DisplayPub(3);
            UstTest.Split('sampleBalbcLabeled55k.csv',...
                'ust_test_cases', 1, 'ust_test_basic_reduction', false, ...
                'cluster_detail', {'most high', 'low'}, 'match_html', 1, ...
                'match_scenarios', [ 1 3 4 ], 'ust_test_basic_reduction', ...
                true);
        end

        %The sample data for this example is made public with the publication
        %https://www.pnas.org/content/107/6/2568
        function Split5
            UmapExamples.DisplayPub(3);
            UstTest.Split('sampleBalbcLabeled55k.csv',...
                'ust_test_cases', 1, 'ust_test_basic_reduction', true, ...
                'cluster_detail', {'most high', 'low'}, 'match_html', 1, ...
                'match_scenarios', [ 1 2 3 4 ], 'ust_test_components', [3 2]);
        end

       %The sample data for this example is made public with the publication
        %https://www.pnas.org/content/107/6/2568
        function EliverSplitFast
            UmapExamples.DisplayPub(3);
            UstTest.Split('sampleBalbcLabeled12k.csv',...
                'ust_test_cases', 4, 'ust_test_basic_reduction', false, ...
                'cluster_detail', 'most high', 'match_html', 1, ...
                'match_supervisors', [3 4], ...
                'match_scenarios', 4, 'ust_test_basic_reduction', ...
                false, 'ust_test_components', 2);
        end

        function Split6
            UmapExamples.DisplayPub(3);
            UstTest.Split('sampleBalbcLabeled55k.csv',...
                'ust_test_cases', 1, 'ust_test_basic_reduction', false, ...
                'cluster_detail', {'most high', 'low'}, 'match_html', 1, ...
                'match_scenarios', [ 1 4 ], 'ust_test_basic_reduction', ...
                true, 'ust_test_components', [3 2],'ust_test_cases',...
                3);
        end
        function SplitGenenTech(synthesize, matchTypes)
            if nargin<2
                matchTypes=[3 4];
                if nargin<1
                    synthesize=0;
                end
            end
            UmapExamples.DisplayPub(2);
            UstTest.Split('genentech_d1_27D.csv', ...
                'ust_test_synthesize', synthesize, ...
                'ust_test_components', 2, ...
                'ust_test_basic_reduction', false, ...
                'cluster_detail', 'most high', ...
                'match_html', 1, ...
                'n_neighbors', 30, ...
                'match_supervisors', matchTypes, ...
                'match_scenarios', 4, ...
                'ust_test_cases', [ 1 2 4]);
        end

        function RunTest1
            UstTest.RunBig(10);
        end

    end
end


text:
function decim=decimage(im,M)
% IMAGE DECIMATION
% LSS MATLAB WEBSERVER
[imysize,imxsize]=size(im);
decim = im([1:M:imysize],[1:M:imxsize]);


text:
function combo_test30 ( )

%*****************************************************************************80
%
%% COMBO_TEST30 tests PRUEFER_*.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 January 2011
%
%  Author:
%
%    John Burkardt
%
  n = 4;

  fprintf ( 1, ' \n' );
  fprintf ( 1, 'COMBO_TEST30\n' );
  fprintf ( 1, '  Pruefer codes:\n' );
  fprintf ( 1, ' \n' );
  fprintf ( 1, '  PRUEFER_ENUM enumerates,\n' );
  fprintf ( 1, '  PRUEFER_RANK ranks,\n' );
  fprintf ( 1, '  PRUEFER_SUCCESSOR lists,\n' );
  fprintf ( 1, '  PRUEFER_UNRANK unranks.\n' );
%
%  Enumerate.
%
  ncode = pruefer_enum ( n );

  fprintf ( 1, ' \n' );
  fprintf ( 1, '  For N = %d\n', n );
  fprintf ( 1, '  the number of Pruefer codes is %d\n', ncode );
  fprintf ( 1, ' \n' );
%
%  List
%
  p = [];
  rank = -1;

  while ( 1 );

    rank_old = rank;

    [ p, rank ] = pruefer_successor ( n, p, rank );

    if ( rank <= rank_old )
      break
    end

    fprintf ( 1, '  %3d  ', rank );
    for i = 1 : n - 2
      fprintf ( 1, '%5d', p(i) );
    end
    fprintf ( 1, '\n' );

  end
%
%  Unrank.
%
  rank = floor ( ncode / 2 );

  p = pruefer_unrank ( rank, n );

  fprintf ( 1, ' \n' );
  fprintf ( 1, '  The element of rank %d:\n', rank );
  fprintf ( 1, ' \n' );
  for i = 1 : n - 2
    fprintf ( 1, '%5d', p(i) );
  end
  fprintf ( 1, '\n' );
%
%  Rank.
%
  rank = pruefer_rank ( n, p );

  fprintf ( 1, ' \n' );
  fprintf ( 1, '  The rank of the element is computed as %d:\n', rank );

  return
end


text:
function hypercube_grid_test02 ( )

%*****************************************************************************80
%
%% HYPERCUBE_GRID_TEST02 tests HYPERCUBE_GRID on a five dimensional example.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 August 2014
%
%  Author:
%
%    John Burkardt
%
  m = 5;

  a = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
  b = [ 1.0, 1.0, 1.0, 1.0, 1.0 ];
  c = [ 1, 2, 3, 4, 5 ];
  ns = [ 2, 2, 2, 2, 2 ];

  n = prod ( ns(1:m) );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'HYPERCUBE_GRID_TEST02\n' );
  fprintf ( 1, '  Create a grid using HYPERCUBE_GRID.\n' );
  fprintf ( 1, '  Use a two point grid in each dimension.\n' );
  fprintf ( 1, '  Use a different centering option in each dimension.\n' );
  fprintf ( 1, '  Spatial dimension M = %d\n', m );
  fprintf ( 1, '  Number of grid points N = %d\n', n );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     I    NS     C      A         B\n' );
  fprintf ( 1, '\n' );
  for i = 1 : m
    fprintf ( 1, '  %4d  %4d  %4d  %8.4f  %8.4f\n', i, ns(i), c(i), a(i), b(i) );
  end

  x = hypercube_grid ( m, n, ns, a, b, c );
  r8mat_transpose_print ( m, n, x, '  Grid points:' );

  return
end


text:
function c = getColor(cidxs)

% http://colorbrewer2.org/

color = cell(8,4);

% qualitative
color{1}{1} = [55,126,184];
color{2}{1} = [255,127,0];
color{3}{1} = [77,175,74];
color{4}{1} = [228,26,28];
color{5}{1} = [255,255,51];%[178,223,138];
color{6}{1} = [0,0,0];
% color{6}{1} = [255,255,51];
color{7}{1} = [152,78,163];
color{8}{1} = [247,129,191];

% sequential
color{1}{2} = [253,141,60];
color{1}{3} = [254,204,92];
color{1}{4} = [255,255,178];
color{1}{5} = [254,240,217];

color{2}{2} = [107,174,214];
color{2}{3} = [189,215,231];
color{2}{4} = [117,107,177];

color{3}{2} = [194,230,153];

color{4}{2} = [140,150,198];
color{4}{3} = [179,205,227];
color{4}{4} = [237,248,251];

c = color{cidxs(1)}{cidxs(2)};

end

author: eldar

repo: deepcut

save_path: github-repos/MATLAB/eldar-deepcut


text:
function convertAnnotationsToVersion11()
% convertAnnotationsToVersion11()
%
% This script takes the unzipped contents of cocostuff-10k-v1.0.zip and
% converts the annotations from version 1.0 to 1.1, where COCO has 91 thing
% classes instead of 80. Afterwards the annotations1.1 folder needs to be
% manually renamed to annotations.
%
% Copyright by Holger Caesar, 2017

% Settings
cocoStuffFolder = '/home/holger/Downloads/cocostuff-10k-v1.0';
inputFolder = fullfile(cocoStuffFolder, 'annotations');
outputFolder = fullfile(cocoStuffFolder, 'annotations1.1');

% Create output Folder
if ~exist(outputFolder, 'dir')
    mkdir(outputFolder);
end

% Get file list
[fileList, fileCount] = dirSubfolders(inputFolder, '.mat', true);

for fileIdx = 1 : fileCount
    % Check if output file exists
    fileName = fileList{fileIdx};
    filePath = fullfile(inputFolder, [fileName, '.mat']);
    outFilePath = fullfile(outputFolder, [fileName, '.mat']);
    if exist(outFilePath, 'file')
        fprintf('Skipping existing file: %s\n', outFilePath);
        continue;
    end

    % Load file
    fileStruct = load(filePath);

    % Update names
    assert(numel(fileStruct.names) == 172)
    thingNames = {'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'street sign', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'hat', 'backpack', 'umbrella', 'shoe', 'eyeglasses', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'plate', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'mirror-things', 'dining table', 'window', 'desk-things', 'toilet', 'door-things', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'blender', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'hairbrush'}';
    stuffNames = fileStruct.names(82:end)';
    assert(isempty(intersect(thingNames, stuffNames)));
    namesNew = [thingNames; stuffNames]; % Unlabeled is not listed anymore and will take label 0

    % Create mapping from old to new
    mapping = [0; find(ismember(namesNew, fileStruct.names))];

    % Map labels
    Snew = mapping(fileStruct.S);
    regionLabelsStuffNew = mapping(fileStruct.regionLabelsStuff);
    assert(isequal(namesNew(Snew(Snew > 0)), fileStruct.names(fileStruct.S(Snew > 0))'));

    % Save changes
    fileStruct.names = namesNew;
    fileStruct.S = Snew;
    fileStruct.regionLabelsStuff = regionLabelsStuffNew;
    save(outFilePath, '-struct', 'fileStruct');
end

author: nightrome


text:
function [nodes2, edges2] = grMergeNodesMedian(nodes, edges, mnodes)
%GRMERGENODESMEDIAN Replace several nodes by their median coordinate.
%
%   [NODES2, EDGES2] = grMergeNodesMedian(NODES, EDGES, NODES2MERGE)
%   NODES ans EDGES are the graph structure, and NODES2MERGE is the list of
%   indices of nodes to be merged.
%   The median coordinate of merged nodes is computed, and all nodes are
%   merged to this new node.
%
%

% ------
% Author: David Legland
% E-mail: david.legland@inrae.fr
% Created: 2003-08-13
% Copyright 2003-2022 INRA - TPV URPOI - BIA IMASTE

% coordinates of reference node
x = median(nodes(mnodes, 1));
y = median(nodes(mnodes, 2));

% index of reference node
refNode = findPoint([x y], nodes);
mnodes = sort(mnodes(mnodes ~= refNode));

for n = 1:length(mnodes)
    node = mnodes(n);

    % process each neighbor of the current node
    neighbors = grAdjacentNodes(edges, node);
    for e = 1:length(neighbors)
        edge = neighbors(e);

        if edges(edge, 1) == refNode || edges(edge, 2) == refNode
            continue;
        end

        % find if the node is referenced as 1 or 2 in the edge,
        % and replace it with the reference node.
        if edges(edge, 1) == node
            edges(edge, 1) = refNode;
        else
            edges(edge, 2) = refNode;
        end

    end
end

% remove nodes from the list, except the reference node.
for n = 1:length(mnodes)
    [nodes, edges] = grRemoveNode(nodes, edges, mnodes(n)-n+1);
end

nodes2 = nodes;
edges2 = edges;

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function test_triangulation_test ( )

%*****************************************************************************80
%
%% TEST_TRIANGULATION_TEST tests the TEST_TRIANGULATION library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 April 2009
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_TRIANGULATION_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TEST_TRIANGULATION library.\n' );

  test_triangulation_test01 ( );
  test_triangulation_test02 ( );
  test_triangulation_test03 ( );
% test_triangulation_test04 ( );
  test_triangulation_test05 ( );
  test_triangulation_test06 ( );
  test_triangulation_test07 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_TRIANGULATION_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end

author: johannesgerer

repo: jburkardt-m