text:
%%
% Copyright (c) 2019-present, Mahmoud Afifi
%
% This source code is licensed under the license found in the
% LICENSE file in the root directory of this source tree.
%
% Please, cite the following paper if you use this code:
%
% Mahmoud Afifi and Michael S. Brown. What else can fool deep learning?
% Addressing color constancy errors on deep neural network performance.
% ICCV, 2019
%
% Email: mafifi@eecs.yorku.ca | m.3afifi@gmail.com
%%

%%
% This demo generates ten images from each image in the  given path.
% Each generated file will be in the following format:
% originalName_WB_CS.ext, where originalName is the original filename, WB
% refers to white balance (WB) settings, and CS is the camera style.
% WB settings are:
%   - T: Tungsten WB [2850 Kelvin (K)]
%   - F: Fluorescent WB [3800K]
%   - D: Daylight WB [5500K]
%   - C: Cloudy WB [6500K]
%   - S: Shade WB [7500K]
% Camera styes are:
%   - AS: Adobe Standard
%   - CS: Camera Standard
% The generated images and a copy of the input image (optional) will be
% saved in the output directory (output_dir)

%%
clear;
clc;

use_GPU = 0; % to use GPU
datasetbase = fullfile('..','images'); % path of images directory
output_dir = fullfile('..','results'); % output directory (will contain
% generated images and copy of original images
NumOfImgs = 10; % should be less than or equal 10
saveOrig = true; % to save a copy of original images in output_dir

if exist(output_dir, 'dir') == 0
	mkdir(output_dir)
end

if NumOfImgs > 10
    error('Cannot generate more than 10 images for each input image');
end

imds = imageDatastore(datasetbase,'IncludeSubfolders' ,1);
images = {imds.Files{:}}'; % get all input filenames

if use_GPU==1
    load('synthWBmodel_GPU.mat'); % load WB_emulator GPU model
else
    load('synthWBmodel.mat'); % load WB_emulator CPU model
end

for i = 1 : length (images) % for each input image, do
    fprintf('processing image: %s...\n',images{i});
    imgin = images{i};
    I_in = imread(imgin); % read input image
    [~,name,ext] = fileparts(imgin);
    if saveOrig == true
        imwrite(I_in,fullfile(output_dir,... % save a copy of it in output dir
            sprintf('%s%s%s',name,'_original',ext)));
    end
    try
        % generate images with synthetic WB effects
        out = WB_emulator.generate_wb_srgb(I_in, NumOfImgs);
        if use_GPU==1 % if GPU is used,
            out = gather(out); % convert gpuArray to double tensor
        end
        for j =1 : size(out,4) % save generated images
            imwrite(out(:,:,:,j),fullfile(output_dir,...
                sprintf('%s%s%s',name,...
                WB_emulator.wb_photo_finishing{j},ext)));
        end
    catch
        fprintf('Error in image %s!\n', imgin);
    end
end

author: mahmoudnafifi


text:
function [ i, j ] = i4_to_pascal ( k )

%*****************************************************************************80
%
%% I4_TO_PASCAL converts a linear index to Pascal triangle coordinates.
%
%  Location:
%
%    http://people.sc.fsu.edu/~jburkardt/m_src/triangle_integrals/i4_to_pascal.m
%
%  Discussion:
%
%    We describe the grid points in Pascal's triangle in two ways:
%
%    As a linear index K:
%
%                     1
%                   2   3
%                 4   5   6
%               7   8   9   10
%
%    As elements (I,J) of Pascal's triangle:
%
%                     0,0
%                  1,0   0,1
%               2,0   1,1    0,2
%            3,0   2,1   1,2    0,3
%
%  Example:
%
%     K  I  J
%
%     1  0  0
%     2  1  0
%     3  0  1
%     4  2  0
%     5  1  1
%     6  0  2
%     7  3  0
%     8  2  1
%     9  1  2
%    10  0  3
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 April 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer K, the linear index of the (I,J) element.
%    1 <= K.
%
%    Output, integer I, J, the Pascal indices.
%
  if ( k <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4_TO_PASCAL - Fatal error!\n' );
    fprintf ( 1, '  K must be positive.\n' );
    error ( 'I4_TO_PASCAL - Fatal error!' );
  end

  d = i4_to_pascal_degree ( k );

  j = k - ( d * ( d + 1 ) ) / 2 - 1;
  i = d - j;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% DEMO of subplot Vs subplot_tight
func_hndl={@subplot;@subplot_tight};
dir_file=dir('*.jpg');
for p=1:length(dir_file)
   img=imread(dir_file(p).name);
   for func_ind=1:length(func_hndl)
      figure(func_ind)
      func_hndl{func_ind}(3,3,p);
      imshow(img);
   end
end
peaks_data=peaks(50);
for func_ind=1:length(func_hndl);
   figure(func_ind)
   func_hndl{func_ind}(3,3,[8,9]);
   surf(peaks_data);
   axis tight;
   xlabel('x');
   ylabel('y');
   zlabel('z');
   title('Peaks Plot','FontSize', 14);
end
set(1,'Name','Matlab SUBPLOT');
set(2,'Name','Our subplot_tight');
set(1:2,'MenuBar','none')

author: Sable

repo: mcbench-benchmarks


text:
function [traj, infStates] = tapas_hgf_whichworld(r, p, varargin)
% Calculates the trajectories of the agent's representations under the HGF
%
% This function can be called in two ways:
%
% (1) tapas_hgf_whichworld(r, p)
%
%     where r is the structure generated by tapas_fitModel and p is the parameter vector in native space;
%
% (2) tapas_hgf_whichworld(r, ptrans, 'trans')
%
%     where r is the structure generated by tapas_fitModel, ptrans is the parameter vector in
%     transformed space, and 'trans' is a flag indicating this.
%
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2013 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version). For further details, see the file
% COPYING or <http://www.gnu.org/licenses/>.

% Check whether we have a configuration structure
if ~isfield(r,'c_prc')
    error('tapas:hgf:ConfigRequired', 'Configuration required: before calling tapas_hgf_whichworld, tapas_hgf_whichworld_config has to be called.');
end

% Transform paramaters back to their native space if needed
if ~isempty(varargin) && strcmp(varargin{1},'trans');
    p = tapas_hgf_whichworld_transp(r, p);
end

% Number of worlds
nw = r.c_prc.nw;

% Bernoulli parameters that characterize
% worlds (column vector)
bp = [0.85; 0.15];

% Unpack parameters
mu2_0 = p(1:nw);
sa2_0 = p(nw+1:2*nw);
mu3_0 = p(2*nw+1);
sa3_0 = p(2*nw+2);
ka    = p(2*nw+3);
om    = p(2*nw+4);
th    = p(2*nw+5);
m     = p(2*nw+6);
phi   = p(2*nw+7);

% Add dummy "zeroth" trial
u = [0; r.u(:,1)];

% Number of trials (including prior)
n = length(u);

% Initialize updated quantities

% Representations
mu1 = NaN(n,nw);
pi1 = NaN(n,nw);
mu2 = NaN(n,nw);
pi2 = NaN(n,nw);
mu3 = NaN(n,1);
pi3 = NaN(n,1);

% Other quantities
mu1hat = NaN(n,nw);
pi1hat = NaN(n,nw);
mu2hat = NaN(n,nw);
pi2hat = NaN(n,nw);
mu3hat = NaN(n,1);
pi3hat = NaN(n,1);
v2     = NaN(n,1);
w2     = NaN(n,nw);
da1    = NaN(n,nw);
da2    = NaN(n,nw);

% Representation priors
% Note: first entries of the other quantities remain
% NaN because they are undefined and are thrown away
% at the end; their presence simply leads to consistent
% trial indices.
mu1(1,:) = tapas_sgm(mu2_0, 1);
pi1(1,:) = 1./(mu1(1,:).*(1-mu1(1,:)));
mu2(1,:) = mu2_0;
pi2(1,:) = 1./sa2_0;
mu3(1)   = mu3_0;
pi3(1)   = 1/sa3_0;

% Pass through representation update loop
for k = 2:1:n
    if not(ismember(k-1, r.ign))

        %%%%%%%%%%%%%%%%%%%%%%
        % Effect of input u(k)
        %%%%%%%%%%%%%%%%%%%%%%

        % 1st level
        % ~~~~~~~~~
        % Predictions
        mu1hat(k,:) = tapas_sgm(mu2(k-1,:), 1);

        % Precisions of predictions
        pi1hat(k,:) = 1./(mu1hat(k,:).*(1 -mu1hat(k,:)));

        % Updates (simply applying Bayes' theorem)

        % Likelihood of outcome u(k)
        llh = bp.^u(k).*(1-bp).^(1-u(k));

        % Marginal likelihood of outcome
        mllh = mu1hat(k,:)*llh;

        % Posterior for each world
        mu1(k,:) = mu1hat(k,:).*llh'./mllh;

        % Precision of posterior
        pi1(k,:) = 1./(mu1(k,:).*(1-mu1(k,:)));

        % Prediction errors
        da1(k,:) = mu1(k,:) -mu1hat(k,:);

        % 2nd level
        % ~~~~~~~~~
        % Predictions
        mu2hat(k,:) = mu2(k-1,:);

        % Precisions of predictions
        pi2hat(k,:) = 1./(1./pi2(k-1,:) +exp(ka *mu3(k-1) +om));

        % Updates
        pi2(k,:) = pi2hat(k,:) +1./pi1hat(k,:);

        mu2(k,:) = mu2hat(k,:) +1./pi2(k,:) .*da1(k,:);

        % Volatility prediction errors
        da2(k,:) = (1./pi2(k,:) +(mu2(k,:) -mu2hat(k,:)).^2) .*pi2hat(k,:) -1;

        % 3rd level
        % ~~~~~~~~~
        % Predictions
        mu3hat(k) = mu3(k-1) +phi *(m -mu3(k-1));

        % Precision of prediction
        pi3hat(k) = 1/(1/pi3(k-1) +th);

        % Weighting factors
        v2(k)   = exp(ka *mu3(k-1) +om);
        w2(k,:) = v2(k) *pi2hat(k,:);

        % Updates
        pi3(k) = pi3hat(k) +1/nw*sum(1/2 *ka^2 *w2(k,:) .*(w2(k,:) +(2 *w2(k,:) -1) .*da2(k,:)));

        if pi3(k) <= 0
            error('tapas:hgf:NegPostPrec', 'Negative posterior precision. Parameters are in a region where model assumptions are violated.');
        end

        mu3(k) = mu3hat(k) +sum(1/2 *1/pi3(k) *ka *w2(k,:) .*da2(k,:));

    else
        mu1(k,:) = mu1(k-1,:);
        pi1(k,:) = pi1(k-1,:);
        mu2(k,:) = mu2(k-1,:);
        pi2(k,:) = pi2(k-1,:);
        mu3(k)   = mu3(k-1);
        pi3(k)   = pi3(k-1);

        mu1hat(k,:) = mu1hat(k-1,:);
        pi1hat(k,:) = pi1hat(k-1,:);
        mu2hat(k,:) = mu2hat(k-1,:);
        pi2hat(k,:) = pi2hat(k-1,:);
        mu3hat(k)   = mu3hat(k-1);
        pi3hat(k)   = pi3hat(k-1);
        v2(k)       = v2(k-1);
        w2(k,:)     = w2(k-1,:);
        da1(k,:)    = da1(k-1,:);
        da2(k,:)    = da2(k-1,:);
    end
end

% Implied learning rates at the first level
sgmmu2 = tapas_sgm(mu2, 1);
lr1    = diff(sgmmu2)./da1(2:n,:);
lr1(da(2:n,1)==0) = 0;

% Remove representation priors
mu1(1,:)  = [];
pi1(1,:)  = [];
mu2(1,:)  = [];
pi2(1,:)  = [];
mu3(1)    = [];
pi3(1)    = [];

% Remove other dummy initial values
mu1hat(1,:) = [];
pi1hat(1,:) = [];
mu2hat(1,:) = [];
pi2hat(1,:) = [];
mu3hat(1,:) = [];
pi3hat(1)   = [];
v2(1)       = [];
w2(1,:)     = [];
da1(1,:)    = [];
da2(1,:)    = [];

% Create result data structure
traj = struct;

traj.mu = NaN(n-1,3,nw);
traj.mu(:,1,:) = mu1;
traj.mu(:,2,:) = mu2;
traj.mu(:,3,1) = mu3;

traj.sa = NaN(n-1,3,nw);
traj.sa(:,1,:) = 1./pi1;
traj.sa(:,2,:) = 1./pi2;
traj.sa(:,3,1) = 1./pi3;

traj.muhat = NaN(n-1,3,nw);
traj.muhat(:,1,:) = mu1hat;
traj.muhat(:,2,:) = mu2hat;
traj.muhat(:,3,1) = mu3hat;

traj.sahat = NaN(n-1,3,nw);
traj.sahat(:,1,:) = 1./pi1hat;
traj.sahat(:,2,:) = 1./pi2hat;
traj.sahat(:,3,1) = 1./pi3hat;

traj.v       = v2;
traj.w       = w2;

traj.da = NaN(n-1,2,nw);
traj.da(:,1,:) = da1;
traj.da(:,2,:) = da2;

% Updates with respect to prediction
traj.ud = traj.mu -traj.muhat;

% Psi (precision weights on prediction errors)
psi        = NaN(n-1,3,nw);
psi(:,2,:) = 1./pi2;
psi(:,3,:) = diag(1./pi3) *pi2hat;
traj.psi   = psi;

% Epsilons (precision-weighted prediction errors)
epsi        = NaN(n-1,3,nw);
epsi(:,2,:) = squeeze(psi(:,2,:)) .*da1;
epsi(:,3,:) = squeeze(psi(:,3,:)) .*da2;
traj.epsi   = epsi;

% Full learning rate (full weights on prediction errors)
wt        = NaN(n-1,3,nw);
wt(:,1,:) = lr1;
wt(:,2,:) = psi(:,2,:);
wt(:,3,:) = 1/2 *ka *diag(1/pi3) *w2;
traj.wt   = wt;

% Create matrices for use by the observation model
infStates = NaN(n-1,3,nw,4);
infStates(:,:,:,1) = traj.muhat;
infStates(:,:,:,2) = traj.sahat;
infStates(:,:,:,3) = traj.mu;
infStates(:,:,:,4) = traj.sa;

return;

author: translationalneuromodeling

repo: tapas


text:
function mogPrintPlot(model, lbls, capName, experimentNo)

% MOGPRINTPLOT Print projection of MOG into two dimensions.
% FORMAT
% DESC prints a projection of mixtures of Gaussians into two dimensions.
% ARG model : the model to use for plotting the latent space.
% ARG lbls : any lables that are available for plotting.
% ARG capName : the name of the saved plots.
% ARG experimentNo : the experiment number to assign to the files.
%
% SEEALSO : mogScatterPlot
%
% COPYRIGHT : Neil D. Lawrence, 2008

% MLTOOLS

if model.d>2
  model = mogProject(model, 2);
end

modelType = model.type;
modelType(1) = upper(modelType(1));

fileName = ['dem' capName modelType num2str(experimentNo)];

clf
ax = axes('position', [0.05 0.05 0.9 0.9]);
hold on
if ~isempty(lbls) && ~strcmp(lbls, 'connect')
  mogTwoDPlot(model, lbls, getSymbols(size(lbls, 2)));
else
  mogTwoDPlot(model, lbls);
end

piVals = linspace(-pi, pi, 200)';
for i=1:model.m
  a = line(model.mean(i, 1), model.mean(i, 2), 'marker', 'o');
  set(a, 'linewidth', 2, 'markersize', 10)
  x = [sin(piVals) cos(piVals)];
  el = x*model.U{i};
  line(model.mean(i, 1) + el(:, 1), model.mean(i, 2) + el(:, 2), ...
      'linewidth', 2);
end
xLim = [min(model.Y(:, 1)) max(model.Y(:, 1))]*1.1;
yLim = [min(model.Y(:, 2)) max(model.Y(:, 2))]*1.1;
set(ax, 'xLim', xLim);
set(ax, 'yLim', yLim);
set(gca, 'fontsize', 20);
printPlot(fileName, '../tex/diagrams/', '../html/')

figure
clf
ax = axes('position', [0.05 0.05 0.9 0.9]);
hold on
if ~isempty(lbls) && ~strcmp(lbls, 'connect')
  mogTwoDPlot(model, lbls, getSymbols(size(lbls, 2)));
else
  mogTwoDPlot(model, lbls);
end

%xLim = [min(model.Y(:, 1)) max(model.Y(:, 1))]*1.1;
%yLim = [min(model.Y(:, 2)) max(model.Y(:, 2))]*1.1;
set(ax, 'xLim', xLim);
set(ax, 'yLim', yLim);

%set(ax, 'fontname', 'arial');
set(ax, 'fontsize', 20);
printPlot([fileName 'NoOvals'], '../tex/diagrams/', '../html/')

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function [H_t] = shift_t(H,t)

% Shifts the matrix H by t spots to the right
% Use a negative t to shift to the left
% To be used with the convolutive NMF algorithms

[K,N] = size(H);

if t>0
      H_trunc = H(:,1:N-t);
      H_t = [zeros(K,t)+eps,H_trunc];

elseif t<0
      H_trunc = H(:,-t+1:end);
      H_t = [H_trunc,zeros(K,-t)+eps];
else
      H_t = H;
end

end

author: hiroyuki-kasai

repo: NMFLibrary


text:
function test_approx_test03 ( )

%*****************************************************************************80
%
%% TEST_APPROX_TEST03 uses polynomial interpolation on data vector problems.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 August 2011
%
%  Author:
%
%    John Burkardt
%
  max_tab = 12;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_APPROX_TEST03\n' );
  fprintf ( 1, '  Polynomial interpolation to a vector of data.\n' );

  prob_num = p00_prob_num ( );

  for prob = 1 : prob_num

    title = p00_title ( prob );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Problem  %d\n', prob );
    fprintf ( 1, '  %s\n', title )

    data_num = p00_data_num ( prob );

    fprintf ( 1, '  DATA_NUM = %d\n', data_num )

    if ( max_tab < data_num )
      fprintf ( 1, '\n' );
      fprintf ( 1, '  This problem has too much data for polynomial interpolation.\n' );
      continue
    end

    [ xdata, ydata ] = p00_dat ( prob, data_num );

    ntab = data_num;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Interpolating polynomial order = %d\n', ntab );
    fprintf ( 1, '\n' );
%
%  Construct the interpolating polynomial via finite differences.
%
    diftab = data_to_dif ( ntab, xdata, ydata );
%
%  Print out the approximation, including midpoints of the intervals.
%
    for i = 1 : ntab

      if ( i < ntab )
        jhi = 2;
      else
        jhi = 1;
      end

      for j = 1 : jhi

        if ( i < ntab )
          x = ( ( jhi - j + 1 ) * xdata(i)     ...
              + (       j - 1 ) * xdata(i+1) ) ...
              / ( jhi         );
        else
          x = xdata(ntab);
        end

        if ( j == 1 )
          mark = '*';
        else
          mark = ' ';
        end

        yapprox = dif_val ( ntab, xdata, diftab, x );

        fprintf ( 1, '  %c  %14g  %14g\n', mark, x, yapprox );

      end

    end

  end

  return
end


text:
function [y,fs,h]=readcnx(filename,mode)
%READCNX  Read a .CNX format sound file [Y,FS,H]=(FILENAME)
%
% Inputs:
%           filename : character string containing filename (default extension .cnx)
%           mode:    't' = trim leading and trailing silences
%                    'h' = read header only
%             'd'    Look in data directory: voicebox('dir_data')
%
% Outputs:
%           y  : column vector containing waveform
%           fs : sample frequency
%           h  : parameter array:
%                h(1) = number of samples in file
%                h(2) = status: 0=good, 1=bad
%                h(3) = start sample number
%                h(4) = ending sample number
%                h(5) = speaker identification number
%                h(6) = speaker age group
%                h(7) = speaker sex: 0=male, 1=female
%                h(8) = ascii character
%                h(9) = repetition number
%
% This is the format of the BT Connex-S1 alphabet database
% Note: the decoding is not particularly robust and assumes
%       that all headers contain the same sequence of fields

%	   Copyright (C) Mike Brookes 1998
%      Version: $Id: readcnx.m,v 1.4 2007/05/04 07:01:39 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ix=[17 71; 18 0; 19 0; 10 0; 12 0; 13 77; 15 -1; 16 0; ];

if nargin<2  mode='0'; end
if any(mode=='d')
    filename=fullfile(voicebox('dir_data'),filename);
end
fid=fopen(filename,'rb','l');
if fid == -1
    fn=[filename,'.cnx'];
    fid=fopen(fn,'rb','l');
    if fid ~= -1 filename=fn; end
end
if fid == -1 error(sprintf('Can''t open %s for input',filename)); end
[hdr,n]=fread(fid,512,'uchar');
if n ~= 512 error(sprintf('Can''t read header from connex file %s',filename)); end
del=find(hdr(5:end)=='|')';
fs=sscanf(char(hdr(17:del(1)+3)),'%f');
h=zeros(size(ix,1),1);
for i=1:length(h)
    e=find(hdr(del(ix(i)-1)+5:del(ix(i))+3)=='=');
    if ix(i,2)
        h(i)=hdr(del(ix(i)-1)+e+5);
        if ix(i,2)>0
            h(i)=1-(h(i)==ix(i,2));
        end
    else
        h(i)=sscanf(char(hdr(del(ix(i)-1)+e+5:del(ix(i))+3)),'%d');
    end
end
if any(mode =='h')
    y=[];
elseif any(mode =='t')
    fseek(fid,2*h(2),0);
    [y,n]=fread(fid,h(3)-h(2)+1,'short');
    if n ~= h(3)-h(2)+1 error(sprintf('Error reading data from connex file %s',filename)); end
else
    y=fread(fid,inf,'short');
end
fseek(fid,0,1);
h=[ftell(fid)/2-256; h];
fclose(fid);

author: decouples


text:
classdef CoreSystemUtilities
    % CoreSystemUtilities. Utility functions relating to the hardware or operating system.
    %
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    methods (Static)

        function uid = GenerateUid()
            % Creates a random unique identifier

            % On unix systems, if java is not running we can use the system
            % command
            if isunix && ~usejava('jvm')
                [status, uid] = system('uuidgen');
                if status ~= 0
                    error('Failure running uuidgen');
                end
            else
                uid = char(java.util.UUID.randomUUID);
            end
        end

        function hash = StringToHash(string)
            % Performs an SHA hash on a string
            persistent messageDigest
            if isempty(messageDigest)
                messageDigest = java.security.MessageDigest.getInstance('SHA-256');
            end
            hash = sprintf('%2.2x', typecast(messageDigest.digest(uint8(string)), 'uint8')');
        end

        function dimensions = GetMonitorDimensions()
            % Gets the resolution of the screen

            if usejava('jvm')
                d = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
                dimensions = [d.width, d.height];
            else
                dimensions = get(0, 'ScreenSize');
                dimensions = dimensions(3:4);
            end
        end

        function bytes_in_type = GetBytesInType(type_string)
            % Returns the number of bytes in the given Matlab type

            switch type_string
                case {'int8', 'uint8'}
                    bytes_in_type = 1;
                case {'uint16', 'int16'}
                    bytes_in_type = 2;
                case {'uint32', 'int32'}
                    bytes_in_type = 4;
                case {'uint64', 'int64'}
                    bytes_in_type = 8;
                otherwise
                    error('CoreSystemUtilities:GetBytesInType', 'Unknown number type');
            end
        end

        function computer_endian = GetComputerEndian()
            % Returns an enumeration for the endian of this computer

            [~, ~, computer_endian_str] = computer;

            switch computer_endian_str
                case 'B'
                    computer_endian = CoreEndian.BigEndian;
                case 'L'
                    computer_endian = CoreEndian.LittleEndian;
                otherwise
                    error('CoreSystemUtilities:GetComputerEndian', 'Unknown endian');
            end
        end

        function DeleteIfValidObject(object_handle)
            % Deletes an object

            if ~isempty(object_handle)
                if isvalid(object_handle)
                    delete(object_handle);
                end
            end
        end

        function DeleteIfGraphicsHandle(handle)
            % Removes a graphics handle

            if ishandle(handle)
                delete(handle);
            end
        end

        function colormap = BackwardsCompatibilityColormap()
            % Returns a colormap which replicates the default colormap from
            % Matlab versions pre-hg2

            old_colormap = [0 0 1; 0 0.5 0; 1 0 0; 0 0.75 0.75; 0.75 0 0.75; 0.75 0.75 0; 0.25 0.25 0.25];
            colormap = repmat(old_colormap, [9, 1]);
            colormap = [colormap; [0 0 1]];
        end

        function [major_version, minor_version] = GetMatlabVersion()
            % Returns the major and minor version numbers of Matlab

            [matlab_version, ~] = version;
            version_matrix = sscanf(matlab_version, '%d.%d.%d.%d');
            major_version = version_matrix(1);
            minor_version = version_matrix(2);
        end

        function toolbox_installed = IsImageProcessingToolboxInstalled()
            % Returns true if the Matlab image processing toolbox is
            % installed

            matlab_version = ver;
            toolbox_installed = any(strcmp('Image Processing Toolbox', {matlab_version.Name}));
        end

        function toolbox_licensed = IsImageProcessingToolboxLicensed()
            % Returns true if the Matlab image processing toolbox has a valid licence

            [error_code, error_message] = license('checkout', 'image_toolbox');
            toolbox_licensed = error_code == 1;
        end

        function path_to_executable = FindFirstExecutableOnPath(executable_name)
            % Returns the path of the first executable found on the system
            % path with the specified name

            if ispc
                [status, path_to_executable] = system(['where ' executable_name]);
            else
                [status, path_to_executable] = system(['which ' executable_name]);
            end

            if status == 0
                % Extract out the first executable, if more than one are
                % returned (which can happen with where on Windows)
                path_to_executable = CoreTextUtilities.RemoveNonprintableCharactersAndStrip(strtok(path_to_executable, char(13)));
            else
                path_to_executable = [];
            end
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function area = trimeshSurfaceArea(v, e, f)
%TRIMESHSURFACEAREA Surface area of a triangular mesh.
%
%   S = trimeshSurfaceArea(V, F)
%   S = trimeshSurfaceArea(V, E, F)
%   Computes the surface area of the mesh specified by vertex array V and
%   face array F. Vertex array is a NV-by-3 array of coordinates.
%   Face array is a NF-by-3, containing vertex indices of each face.
%
%   Example
%     % Compute area of an octahedron (equal to 2*sqrt(3)*a*a, with
%     % a = sqrt(2) in this case)
%     [v f] = createOctahedron;
%     trimeshSurfaceArea(v, f)
%     ans =
%         6.9282
%
%     % triangulate a compute area of a unit cube
%     [v f] = createCube;
%     f2 = triangulateFaces(f);
%     trimeshSurfaceArea(v, f2)
%     ans =
%         6
%
%   See also
%   meshes3d, meshSurfaceArea, trimeshMeanBreadth, triangulateFaces

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2011-08-26,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

% check input number
if nargin == 2
    f = e;
end

% compute two direction vectors, using first vertex of each face as origin
v1 = v(f(:, 2), :) - v(f(:, 1), :);
v2 = v(f(:, 3), :) - v(f(:, 1), :);

% area of each triangle is half the cross product norm
vn = vectorNorm3d(crossProduct3d(v1, v2));

% sum up and normalize
area = sum(vn) / 2;

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function fixed_num = p01_fixed_num ( )

%*****************************************************************************80
%
%% P01_FIXED_NUM returns the number of fixed points in problem 01.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Output, integer FIXED_NUM, the number of fixed points.
%
  fixed_num = 0;

  return
end


text:
%%% test the model performance

% clear; clc;
format compact;

addpath(fullfile('data','utilities'));
% folderTest  = fullfile('data','Test','Set12'); %%% test dataset
folderTest  = fullfile('data','Test','Set68'); %%% test dataset

showResult  = 1;
useGPU      = 1;
pauseTime   = 0;

modelName   = 'model_64_25_Res_Bnorm_Adam';
epoch       = 1;
noiseSigma  = 25;  %%% image noise level

%%% load Gaussian denoising model
load(fullfile('data',modelName,[modelName,'-epoch-',num2str(epoch),'.mat']));
net = vl_simplenn_tidy(net);
net.layers = net.layers(1:end-1);

%%%
net = vl_simplenn_tidy(net);

% for i = 1:size(net.layers,2)
%     net.layers{i}.precious = 1;
% end

%%% move to gpu
if useGPU
    net = vl_simplenn_move(net, 'gpu') ;
end

%%% read images
ext         =  {'*.jpg','*.png','*.bmp'};
filePaths   =  [];
for i = 1 : length(ext)
    filePaths = cat(1,filePaths, dir(fullfile(folderTest,ext{i})));
end

%%% PSNR and SSIM
PSNRs = zeros(1,length(filePaths));
SSIMs = zeros(1,length(filePaths));

for i = 1:length(filePaths)

    %%% read images
    label = imread(fullfile(folderTest,filePaths(i).name));
    [~,nameCur,extCur] = fileparts(filePaths(i).name);
    label = im2double(label);

    randn('seed',0);
    input = single(label + noiseSigma/255*randn(size(label)));

    %%% convert to GPU
    if useGPU
        input = gpuArray(input);
    end

    res    = vl_simplenn(net,input,[],[],'conserveMemory',true,'mode','test');
    output = input - res(end).x;

    %%% convert to CPU
    if useGPU
        output = gather(output);
        input  = gather(input);
    end

    %%% calculate PSNR and SSIM
    [PSNRCur, SSIMCur] = Cal_PSNRSSIM(im2uint8(label),im2uint8(output),0,0);
    if showResult
        imshow(cat(2,im2uint8(label),im2uint8(input),im2uint8(output)));
        title([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])
        drawnow;
        pause(pauseTime)
    end
    PSNRs(i) = PSNRCur;
    SSIMs(i) = SSIMCur;
end

disp([mean(PSNRs),mean(SSIMs)]);

author: cszn

repo: DnCNN

save_path: github-repos/MATLAB/cszn-DnCNN


text:
function desc = calYcbcr(rgb_im, seg, numRegion)
% y cb cr
    im = rgb2ycbcr(rgb_im);

    ind={};
    for iReg=1:numRegion
        ind{iReg} = seg(:)==iReg;
    end

    desc = zeros([numRegion 3]);

    for ch=1:3
        for iReg = 1:numRegion
            feature = im(:,:,ch);
            feature = feature(ind{iReg});
            desc(iReg, ch) = sum(feature) / sum(ind{iReg});
        end
    end

end

author: kittenish

repo: Image-Shadow-Detection-and-Removal


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%	Implemetation of the tracker described in paper
%	"MEEM: Robust Tracking via Multiple Experts using Entropy Minimization",
%   Jianming Zhang, Shugao Ma, Stan Sclaroff, ECCV, 2014
%
%	Copyright (C) 2014 Jianming Zhang
%
%	This program is free software: you can redistribute it and/or modify
%	it under the terms of the GNU General Public License as published by
%	the Free Software Foundation, either version 3 of the License, or
%	(at your option) any later version.
%
%	This program is distributed in the hope that it will be useful,
%	but WITHOUT ANY WARRANTY; without even the implied warranty of
%	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%	GNU General Public License for more details.
%
%	You should have received a copy of the GNU General Public License
%	along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%	If you have problems about this software, please contact: jmzhang@bu.edu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function iou = getIOU(r1,r2)

left = max((r1(:,1)),(r2(:,1)));
top = max((r1(:,2)),(r2(:,2)));
right = min((r1(:,1)+r1(:,3)),(r2(:,1)+r2(:,3)));
bottom = min((r1(:,2)+r1(:,4)),(r2(:,2)+r2(:,4)));
ovlp = max(right - left,0).*max(bottom - top, 0);
iou = ovlp./(r1(:,3).*r1(:,4)+r2(:,3).*r2(:,4)-ovlp);

end

author: flyers

repo: drone-tracking


text:
function [Ain,bin,Aeq,beq] = mix2gen(A,b,e)
%MIX2GEN  Convert Mixed linear constraints to General Linear inequality and equality
%   [A,b,Aeq,beq] = mix2gen(A,b,e)
%
%   Use -1 for <=, 0 for =, and 1 for >= in vector e

%   Copyright (C) 2011 Jonathan Currie (IPL)

if(size(A,1) ~= length(b))
    error('A and b sizes do not correspond');
end
if(length(b) ~= length(e))
    error('b and e are not the same length!');
end
if(any(e < -1) || any(e > 1))
    error('The vector e must only contain values -1, 0 or 1');
end

eq = find(e == 0);
leq = find(e == -1);
geq = find(e == 1);

%Transpose as neccesary
if(size(b,2) > 1)
    b = b';
end

%Process Equality Constraints
if(isempty(eq))
    Aeq = []; beq = [];
else
    Aeq = A(eq,:);
    beq = b(eq);
end

%Process <= Constraints
if(isempty(leq))
    Ain = []; bin = [];
else
    Ain = A(leq,:);
    bin = b(leq);
end

%Process >= Constraints
if(~isempty(geq))
    Ain = [Ain;-A(geq,:)];
    bin = [bin;-b(geq)];
end


text:
%% dependencies

addpath(fullfile(pwd, 'camera_pipeline_simple'));
addpath(fullfile(pwd, 'RBF_ThinPlate_image_warping'));
addpath(fullfile(pwd, 'efficient_subpixel_registration'));

%% data and parameters (replace with your preferences)

dngDir = fullfile(pwd, 'DNGs'); % contains only 3 images
defectivePixelsMask = load(fullfile(dngDir, 'DefectivePixelsMask.mat'));
defectivePixelsMask = defectivePixelsMask.DefectivePixelsMask;
% if not available, use an empty array
% defectivePixelsMask = [];
refIdx = 1; % use first image as reference for spatial alignment

%% prepare parallel pool

NUM_WORKERS = 4;
prepare_parallel_pool(NUM_WORKERS);

%% ground truth image estimation

[MeanUnprocessed, AlignedMeanImage, RobustMeanImage, ...
    MeanUnprocessedSrgb, AlignedMeanImageSrgb, RobustMeanImageSrgb, ...
    refImage, refImageSrgb, refMetadata] ...
    = EstimateGroundTruthImage(dngDir, defectivePixelsMask, refIdx);

%% saving outputs

parsave(fullfile(pwd, 'output', 'MeanUnprocessed.mat'), MeanUnprocessed);
parsave(fullfile(pwd, 'output', 'AlignedMeanImage.mat'), AlignedMeanImage);
parsave(fullfile(pwd, 'output', 'GT_RAW.mat'), RobustMeanImage);

imwrite(MeanUnprocessedSrgb, ...
    fullfile(pwd, 'output', 'MeanUnprocessedSrgb.png'));
imwrite(AlignedMeanImageSrgb, ...
    fullfile(pwd, 'output', 'AlignedMeanImageSrgb.png'));
imwrite(RobustMeanImageSrgb, ...
    fullfile(pwd, 'output', 'GT_SRGB.png'));

parsave(fullfile(pwd, 'output', 'NOISY_RAW.mat'), refImage);
imwrite(refImageSrgb, fullfile(pwd, 'output', 'NOISY_SRGB.png'));
parsave(fullfile(pwd, 'output', 'METADATA_RAW.mat'), refMetadata);

%% Display

Display(refImageSrgb, RobustMeanImageSrgb);

author: AbdoKamel

repo: sidd-ground-truth-image-estimation


text:
function varargout = cdr(varargin)
%CDR decomposition of a DISKFUN.
%   [C,D,R] = CDR(F) produces a diagonal matrix D of size length(F) by
%   length(F) and quasimatrices C and R of size inf by length(F) such that
%   f(theta,r) = C(r,:) * D * R(theta,:)'.
%
%   D = CDR(F) returns a vector containing the pivot values used in the
%   construction of F.
%
% See also DISKFUN/PIVOTS, DISKFUN/SVD.

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

[varargout{1:nargout}] = cdr@separableApprox(varargin{:});

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function gd=ref_tgabdual(ttype,g,L,a,M)
%REF_WIN   Compute appropriate dual window for transform
%

if nargin<5
  error('Too few input parameters.');
end;

info=ref_transforminfo(ttype,L,a,M);

gd=info.winscale*gabdual(g,info.a,info.M);

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function [week,sow]=time2gpst(t)

gpst0=[1980,1, 6,0,0,0]; %gps time reference

t0=epoch2time(gpst0);

sec=t.time-t0.time;
week=fix(sec/7/86400);
sow=sec-week*7*86400+t.sec;

return

repo: GINav


text:
function [ext, platform] = mexexts
%MEXEXTS List of Mex files extensions
%  MEXEXTS returns a cell array containing the Mex files platform
%  dependent extensions and another cell array containing the full names
%  of the corresponding platforms.
%
%  See also MEX, MEXEXT

%  Copyright (C) 2003 Guillaume Flandin <Guillaume@artefact.tk>
%  $Revision: 1.0 $Date: 2003/29/04 17:33:43 $

ext = {'.mexsol' '.mexhpux' '.mexhp7' '.mexglx' '.mexa64' '.mexi64' '.mexmac' '.dll' '.mexw32' '.mexw64'};

platform = {'Sun Solaris' 'HP-UX' 'HP-UX' 'Linux PC' 'Linux AMD Opteron' 'Linux Intel Itanium2' 'MacIntosh' 'Windows' 'Windows 32' 'Windows 64'};

author: opencobra

repo: cobratoolbox


text:
function lcd = getLowComplexityDistance(image,labels,graphDistances,colorHists,gradient,labelSet1,labelSet2,edgeImg , labelIndices)
Dmax = -Inf;
Dg = Inf;
De = 0;

lsum = 0;
for i = labelSet1
    for j = labelSet2
        Dmax = max(Dmax, getColorDistance(image,labels,colorHists,gradient,i,j));
        Dg = min(Dg, graphDistances(i,j));
        [de, l] = calculateGradientEdgeCost(edgeImg, labels, labelIndices, i,j);
        lsum = l + lsum;
        De = De + l * de;
    end
end

if(lsum == 0)
    De = 0;
else
    De = De/lsum;
end

lcd = Dg + Dmax + De;

end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm

path: github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/识别算法/Object Recognition based on super pixel/getLowComplexityDistance.m


text:
function [H,mu,SR]=standardGaussKernelBW(param1,method,spherData,N)
%%STANDARDGAUSSKERNELBW Estimate the (univariate or multivariate) kernel
%             bandwidth when approximating a PDF using a set of samples
%             with a Gaussian kernel. This function provides the bandwidth
%             estimate based on the optimal solution if the underlying
%             density of the samples is normal. If the density is not
%             normal, then this function is just an approximation. The
%             kernel bandwidth estimate can be used with the points xi in
%             the function kernelApprox to approximate the continuous
%             density.
%
%INPUTS: param1 If N is an empty matrix or is omitted, then this is:
%              xi A numDimXnumSamples set of samples of the distribution
%                 from which a Gaussian kernel estimator should interpolate
%                 a PDF. For multidimensional estimation, there must be
%                 >=numDim samples. Specifically, the sample covariance
%                 matrix must be positive definite.
%           If N is given, then this is:
%              SR A root covariance matrix such that SR*SR' equals the
%                 (exact or approximated) covariance matrix of the PDF
%                 being approximated.
%    method An optional parameter specifying the method that should be used
%           to estimate the bandwidth. Possible values are
%           0 Use the method implied by Equation 3.30 and 3.28 in [1],
%             which uses the lesser of the sample standard deviation or a
%             scaled interquartile range. This approach is supposed to work
%             well when the underlying distribution of the samples is not
%             actually normal and might be bimodal. This method cannot be
%             used if N is given.
%           1 (The default if omitted or an empty matrix is passed) Use the
%             method of Equation 3.28 in [1], based on the sample standard
%             deviation.
%           2 Use the method of Equation 3.29 in [1], based on the
%             interquartile range of the samples. This method cannot be
%             used if N is given.
% spherData When the underlying density is truly normal, then the
%           approximation here is only valid if the cross terms of the
%           correlation are zero. To make that the case, if this parameter
%           is true, then the data is "sphered" --premultiplied by the
%           inverse of the square root (lower-triangular Cholesky
%           decomposition) of the sample covariance matrix, and then the
%           final result is multipled by the square root of the sample
%           covariance matrix to scale everything back. However, when this
%           function is used for approximations, sphering can sometimes
%           make thing worse. Thus, if this is false, then only the
%           diagonal terms of the sample covariance matrix are used and the
%           data is not squared. The default if this parameter is omitted
%           or an empty matrix is passed is true.
%         N If this parameter is provided, then param1 is assumed to be SR
%           and N is the number of samples that are being smoothed.
%           Otherwise, if this is omitted or an empty matrix is passed,
%           param1 is xi.
%
%OUTPUTS: H The kernel bandwidth matrix that can be used in the function
%           kernelApprox. This will be a lower-triangular matrix.
%         mu If xi is given, then this is the sample mean. Otherwise, this
%            is an empty matrix.
%         SR The root covariance matrix from the input or computed from xi.
%
%The methods in Chapter 3 of [1] are for a scalar distribution. We are able
%to apply them to a multivariate distribution by pre-multiplying the
%multivariate distribution by the inverse of the sample standard deviation
%of the points. If the samples were from a normal distribution (the
%approximation used here), then we can replace the scalar bandwidth
%formula with the solution for numDim-dimensions given in Chapter 2.4.2 of
%[2]. The pre-multiplication to decorrelate the dimensions is necessary for
%the use of that formula. Ultimately, we then have then rotate the final
%result back. The techniques from Chapter 3 of 1 that are used here only
%differ in how they try to obtain a robust estimate of the standard
%deviation values.
%
%REFERENCES:
%[1] B. W. Silverman, Density Estimation for Statistics and Data Analysis.
%    Chapman and Hall, 1986.
%[2] A. D. Bowman and A. Azzalini, Applied Smoothing Techniques for Data
%    Analysis: The Kernel Approach with S-Plus Illustrations. Oxford:
%    Clarendon Press, 2004.
%
%December 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin<4)
    N=[];
end

if(nargin<3||isempty(spherData))
    spherData=true;
end

if(nargin<2||isempty(method))
    method=1;
end
numDims=size(param1,1);

if(isempty(N))%xi is given
    xi=param1;
    [mu,S]=calcMixtureMoments(xi);
    SR=cholSemiDef(S,'lower',1);%Not fully triangular. but S=SR*SR'
    if(method~=1&&spherData)
        xi=SR\xi;
    end
    N=size(xi,2);%Number of points
else%S and N are given.
    if(method~=1)
        error('If N is given, then method=1 must be used.')
    end

    mu=[];
    SR=param1;
end

if(numDims>1&&spherData)
    sigma1=ones(numDims,1);
else
    sigma1=diag(SR);
end

switch(method)
    case 0%Use Equation 3.30 and 3.28 in [1].
        sigma2=interquartileRange(xi,2)/(GaussianD.invCDF(0.75)-GaussianD.invCDF(0.25));
        sigma=min([sigma1,sigma2],[],2);
    case 1%Use Equation 3.28 in [1].
        sigma=sigma1;
    case 2%Use the interquartile range (scaled appropriately) instead of
          %the standard deviation in [1]. This is Equation 3.29.
        sigma=interquartileRange(xi,2)/(GaussianD.invCDF(0.75)-GaussianD.invCDF(0.25));
    otherwise
        error('Unknown method specified')
end

h=(4/(N*(numDims+2)))^(1/(numDims+4))*sigma;

%Undo any rotation/scaling.
if(numDims>1&&spherData)
    %H is actually aking to the square root of a covariance matrix. h is a
    %list of scalars--the diagonls of the rotated matrix. This builds that
    %diagonal matrix and then scales it.
    H=SR*diag(h);
else
    H=diag(h);
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function h = setPlotProp2(hfig, opt)
% function h = setPlotProp2(hfig, opt)
% This function is a compatibility layer on top of setPlotProp, which
% provides compatibility to MATLAB line/patch functions.
% Like setPlotProp, this function changes the properties of the figure
% represented by 'hfig' and exports it as a publication quality image file.
% The resolution of the image can be chosen by the user. Supported image
% formats are EPS, PDF, PNG, JPEG and TIFF. The figure properties are
% specified by the options structure 'opt'.
%
% Parameters:
%
% hfig:         Figure handle.
%
% opt: options structure:
%   BoxDim:       vector [width, height]: size of the axes box in inches; default: [6, 2.5]
%   ShowBox:      'on' = show or 'off' = hide bounding box; default: 'on'
%   FontName:     string: font name; default: 'Arial'
%   FontSize:     integer; default: 26
%   LineWidth:    vector [width1, width2, ..]: element i changes the property of i-th dataset; default: 2
%   LineStyle:    cell array {'style1', 'style2', ..}: element i changes the property of i-th dataset; default: '-'
%   Markers:      cell array {'marker1', 'marker2', ..}: element i changes the property of i-th dataset; default: 'None'
%   MarkerSpacing:vector [space1, space2, ..]: element i changes the property of i-th dataset; default: 0
%   Colors:       3xN matrix, [red, green, blue] where N is the number of datasets.
%   AxisColor:    [red, green, blue]; color of the axis lines; default: black
%   AxisLineWidth:Witdth of the axis lines; default: 2
%   XLabel:       X axis label
%   YLabel:       Y axis label
%   ZLabel:       Z axis label
%   Title:        Plot title
%   XTick:        [tick1, tick2, ..]: major ticks for X axis.
%   YTick:        [tick1, tick2, ..]: major ticks for Y axis.
%   ZTick:        [tick1, tick2, ..]: major ticks for Z axis.
%   XMinorTick:   'on' or 'off': show X minor tick?
%   YMinorTick:   'on' or 'off': show Y minor tick?
%   ZMinorTick:   'on' or 'off': show Z minor tick?
%   TickDir:      tick direction: 'in' or 'out'; default: 'in'
%   TickLength:   tick length; default: [0.02, 0.02]
%   XLim:         [min, max]: X axis limit.
%   YLim:         [min, max]: Y axis limit.
%   ZLim:         [min, max]: Z axis limit.
%   XScale:       'linear' or 'log': X axis scale.
%   YScale:       'linear' or 'log': Y axis scale.
%   ZScale:       'linear' or 'log': Z axis scale.
%   XGrid:        'on' or 'off': show grid in X axis?
%   YGrid:        'on' or 'off': show grid in Y axis?
%   ZGrid:        'on' or 'off': show grid in Z axis?
%   XDir:         'in' or 'out': X axis tick direction
%   YDir:         'in' or 'out': Y axis tick direction
%   ZDir:         'in' or 'out': Z axis tick direction
%   Legend:       {'legend1','legend2',...}
%   LegendBox:    bounding box of legend: 'on'/'off'; default: 'off'
%   LegendBoxColor: color of the bounding box of legend; default: 'none'
%   LegendTextColor: color of the legend text; default: [0,0,0]
%   LegendEdgeColor: color of the legend edges; default: [0,0,0]
%   LegendLoc:    'NorthEast', ..., 'SouthWest': legend location
%   Resolution:   Resolution (dpi) for bitmapped file. Default:600.
%   HoldLines:    true/false. true == only modify axes settings, do not touch plot lines/surfaces. Default false.
%   FileName:     Save? Give a file name.
%
%
%
% Written by: K M Masum Habib (http://masumhabib.com)
% Copyright (c) K M Masum Habib 2012-2015.
%
% Distributed under the BSD License.
%
% Version: 2.2
%

h = setPlotProp(opt, hfig);

author: masumhabib

repo: PlotPub

save_path: github-repos/MATLAB/masumhabib-PlotPub


text:
function [h, array] = display_samples(A, opt_normalize, opt_graycolor, cols, opt_colmajor)
% This function visualizes filters in matrix A. Each column of A is a
% filter. We will reshape each column into a square image and visualizes
% on each cell of the visualization panel.
% All other parameters are optional, usually you do not need to worry
% about it.
% opt_normalize: whether we need to normalize the filter so that all of
% them can have similar contrast. Default value is true.
% opt_graycolor: whether we use gray as the heat map. Default is true.
% cols: how many columns are there in the display. Default value is the
% squareroot of the number of columns in A.
% opt_colmajor: you can switch convention to row major for A. In that
% case, each row of A is a filter. Default value is false.
warning off all

if ~exist('opt_normalize', 'var') || isempty(opt_normalize)
    opt_normalize= true;
end

if ~exist('opt_graycolor', 'var') || isempty(opt_graycolor)
    opt_graycolor= true;
end

if ~exist('opt_colmajor', 'var') || isempty(opt_colmajor)
    opt_colmajor = false;
end

% rescale
A = A - mean(A(:));

if opt_graycolor, colormap(gray); end

% compute rows, cols
[L M]=size(A);
sz=sqrt(L);
buf=1;
if ~exist('cols', 'var')
    if floor(sqrt(M))^2 ~= M
        n=ceil(sqrt(M));
        while mod(M, n)~=0 && n<1.2*sqrt(M), n=n+1; end
        m=ceil(M/n);
    else
        n=sqrt(M);
        m=n;
    end
else
    n = cols;
    m = ceil(M/n);
end

array=-ones(buf+m*(sz+buf),buf+n*(sz+buf));

if ~opt_graycolor
    array = 0.1.* array;
end

if ~opt_colmajor
    k=1;
    for i=1:m
        for j=1:n
            if k>M,
                continue;
            end
            clim=max(abs(A(:,k)));
            if opt_normalize
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/clim;
            else
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/max(abs(A(:)));
            end
            k=k+1;
        end
    end
else
    k=1;
    for j=1:n
        for i=1:m
            if k>M,
                continue;
            end
            clim=max(abs(A(:,k)));
            if opt_normalize
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/clim;
            else
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz);
            end
            k=k+1;
        end
    end
end

if opt_graycolor
    h=imagesc(array,'EraseMode','none',[-1 1]);
else
    h=imagesc(array,'EraseMode','none',[-1 1]);
end
axis image off

drawnow;

warning on all

author: jimmy-ren


text:
% Description:
%
%     Create a custom design matrix and use it in a call to mancovan, mStepwise,
%     and mT.
%
% Syntax:
%
%     mDemoA
%
% Inputs:
%
% Outputs:
%
% Details:
%
% Examples:
%
% Notes:
%
% Author(s):
%
%     William Gruner (williamgruner@gmail.com)
%
% References:
%
% Acknowledgements:
%
%     Many thanks to Dr. Erik Erhardt and Dr. Elena Allen of the Mind Research
%     Network (www.mrn.org) for their continued collaboration.
%
% Version:
%
%     $Author: williamgruner $
%     $Date: 2010-04-01 11:39:09 -0600 (Thu, 01 Apr 2010) $
%     $Revision: 482 $

function mDemoA

    % Create a set of simulated data with 2 groups and 2 covariates.

    n          = 100;
    groups     = round(3 * rand(n, 2) + 0.5);
    covariates = randn(n, 2);
    Y          = groups + covariates + randn(n, 2);

    % Create a design matrix for group 1, covariate 2, and their interaction.

    terms = { 0 };
    X     = ones(n, 1);

    [ x, t ] = mG2X(groups, 0, {}, 1);
    terms    = cat(2, terms, t);
    X        = cat(2, X, x);

    [ x, t ] = mC2X(covariates, size(groups, 2), {}, 2);
    terms    = cat(2, terms, t);
    X        = cat(2, X, x);

    [ x, t ] = mGC2X(groups, covariates, 0, size(groups, 2), {}, [ 1 2 ]);
    terms    = cat(2, terms, t);
    X        = cat(2, X, x);

    % Use the custom design matrix in a call to mancovan.

    fprintf('\nOutput from mancovan:\n\n')

    [ T, p ] = mancovan(Y, X, terms, { 'verbose' });

    % Use the custom design matrix in a call to mStepwise.

    fprintf('\nOutput from mStepwise:\n\n')

    [ T, p ] = mStepwise(Y, X, terms, 0.10, { 'verbose' });

    % Use the custom design matrix in a few calls to mT.

    fprintf('\nOutput from mT:\n\n')

    [ t, p ] = mT(Y, X, terms, 1)
    [ t, p ] = mT(Y, X, terms, 4)
    [ t, p ] = mT(Y, X, terms, [ 1 4 ])

author: Sable

repo: mcbench-benchmarks


text:
function blas0_test03 ( )

%*****************************************************************************80
%
%% BLAS0_TEST03 tests R8_SIGN.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 March 204
%
%  Author:
%
%    John Burkardt
%
  test_num = 5;
  x_test = [ -1.25, -0.25, 0.0, +0.5, +9.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'BLAS0_TEST03\n' );
  fprintf ( 1, '  R8_SIGN returns the sign of a number.\n' );
  fprintf ( 1, '\n' );

  for test = 1 : test_num
    x = x_test(test);
    fprintf ( 1, '  %8f  %8f\n', x, r8_sign ( x ) );
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%IM_DBR Image Database Retrieval GUI
%
%    [RANK,TARG,OUTL] = IM_DBR(DBASE,FSETS,CLASSF,COMB)
%
% INPUT
%   DBASE   - Dataset or datafile with N object images
%   FSETS   - Cell array with maximum 4 feature sets
%   CLASSF  - Cell array with untrained classifiers (Default: KNNC([],1))
%   COMB    - Combining classifier (Default: MEANC)
%
% OUTPUT
%   RANK    - Index array ranking the N object images
%   TARG    - Index array pointing to user defined target images
%   OUTL    - Index array pointing to user defined outlier images
%
% DESCRIPTION
% This command generates a Graphical User Interface (GUI) enabling the user
% to label a database of images in 'target' and 'outlier' images in an
% interactive and iterative way. Up to four feature sets can be given and
% corresponding classifiers that assist the user by predict an object ranking
% based on classification confidences for the 'target' class.
%
% The GUI shows the top-10 of the ranking and the user should classify
% them as targets or outliers (original object labels in DBASE are
% neglected). There are buttons for browsing through the ranked database
% or through the selected targets and outliers. Classifiers can be trained
% according to two different strategies using the top right buttons:
% Classify - uses all stored target and outlier objects (shown in the top
%            left windows) for building a training set as well as the
%            hand labeled images in the present screen.
% Label    - uses just the hand labeled images in the present screen
%            and neglects the stored targets and outliers. This enables
%            a more flexible, but still controlled browsing throug the
%            database.
% Reset    - Resets the entire procedure by deleting all selected targets
%            and outliers.
% Quit     - Deletes the GUI and returns the ranking and selected targets
%            and outliers to the user.
% A few additional buttons and sliders for controlling the system behavior:
% - Delete and move buttons for the selected targets and outliers
% - Weights for the feature sets. For each feature set a different
%   classifier is computed generating target confidences for all images.
%   This influences the operation of the combiniong classifier.
%   The weights can be changed by a slider for every feature set.
%   By default weights are 1.
% - Two buttons for setting all labels as target ('All target') or outlier
%   ('All outlier').
% - Labels for the individual images can be changed by a mouse-click in the
%   image or on the image check-box.
% - For all images a target confidence is computed. Depending on the 'all'
%   and 'unlabeled' radio buttons at the bottom the ranking of all images
%   or of the yet unlabeled images are shown.
% Note: It is not an error, but for most classifiers useless or
% counterproductive to label an object as target as well as outlier.
%
% EXAMPLE
% % This example assumes that the Kimia images are available as datafile
% % and that the DipImage image processing package is available.
% prwaitbar on
% a = kimia_images;
% x = im_moments(a,'hu');
% x = setname(x,'Hu moments');
% y = im_measure(a,a,{'size','perimeter','ccbendingenergy'});
% y = setname(y,'Shape features');
% [R,T,L] = im_dbr(a,{x,y});  % do your own search
% delfigs
% figure(1); show(a(R,:)); % show ranking
% figure(2); show(a(T,:)); % show targets
% figure(3); show(a(L,:)); % show outliers
% showfigs
%
% SEE ALSO (PRTools Guide)
% DATASETS, DATAFILES, MAPPINGS, KNNC, MEANC

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

function [R,T,L] = im_dbr(dbase,featsets,classf,comb);

	if sscanf(version('-release'),'%i') < 14
		error('IM_DBR needs Matlab version 14 or higher')
	end

	if nargin < 4, comb = meanc; end
	if nargin < 3, classf = knnc([],1); end
	[R,T,L] = image_dbr(dbase,featsets,classf,comb);

return

author: marianux

repo: ecg-kit

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


text:
function cell_task ( work_directory, index )

%*****************************************************************************80
%
%% CELL_TASK carries out the task of detecting cells in one image.
%
%  Discussion:
%
%    This function opens a particular file, reads the image data it contains,
%    applies an image processing operation to the data, and writes the
%    processed image to a new file.
%
%    The first input file will have the name 'AT3_1m4_01.tif' and the
%    first output file will have the name 'BT3_1m4_01.tif'.
%
%    The input images are gray-scale microscropic photographs of a
%    number of cells.
%
%    The image processing is intended to detect the edges of the cells
%    and to highlight them with a white line.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 June 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string WORK_DIRECTORY, the directory where the files are.
%
%    Input, integer INDEX, the index of the file to be processed by this task.
%

%
%  Move to the working directory.
%
  cd ( work_directory )
%
%  The name of the input file is by inserting the frame index
%  into a standard string.  The format we use guarantees that
%  small integers are left-padded with zeros.
%
  filename_input = sprintf ( 'AT3_1m4_%02d.tif', index );
%
%  Get the image data.
%
  I = imread ( filename_input );
%
%  The EDGE function is used to seek edges in an intensity (gray scale)
%  image.  'Sobel' is one method of doing this.
%  On the first call, we are interested in getting the threshold value.
%
%  Use |edge| and the Sobel operator to calculate the threshold
% value.
%
%  Using the ~ symbol to indicate that the given output quantity
%  is not to be stored does not work in older versions of MATLAB.

  [ ~, threshold ] = edge ( I, 'sobel' );
%
%  Now we adjust the threshold value and call EDGE again, but this
%  time we ignore the output threshold, we only want the binary mask.
%
  threshold = 0.5 * threshold;
  [ BW, ~ ] = edge ( I, 'sobel', threshold );
%
%  Create vertical and horizontal flat linear structural
%  elements of length 3.
%
  se90 = strel ( 'line', 3, 90 );
  se0 = strel ( 'line', 3, 0 );
%
%  Dilate the image.
%
  BWdilate = imdilate ( BW, [ se90 se0 ] );
%
%  Suppress light structures connected to the border.
%
  BWnobord = imclearborder ( BWdilate, 4 );
%
%  Remove small objects (of less than 200 pixels).
%
  BWopen = bwareaopen ( BWnobord, 200 );
%
%  Perform binary closure (dilation + erosion).
%
  BWclose = bwmorph ( BWopen, 'close' );
%
%  Fill holes in the image.
%
  BWfill = imfill ( BWclose, 'holes' );
%
%  Find the pixels that represent the perimeters of objects in the
%  black and white image.
%
  BWoutline = bwperim ( BWfill );
%
%  Form the new image by starting with the original image, and then marking
%  the cell perimeters with white (color 255).
%
  segmentedCells = I;
  segmentedCells(BWoutline) = 255;
%
%  Create the output filename.
%
  filename_output = sprintf ( 'BT3_1m4_%02d.tif', index );
%
%  Write the file.
%
  imwrite ( segmentedCells, filename_output, 'tif' );

  return
end


text:
function test_suite=test_pca
% tests for cosmo_pca
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #
    try % assignment of 'localfunctions' is necessary in Matlab >= 2016
        test_functions=localfunctions();
    catch % no problem; early Matlab versions can use initTestSuite fine
    end
    initTestSuite;

function [pca_samples,coef,mu,expl]=helper_cosmo_pca_wrapper(samples,...
                                                            keep_count)
    if isnan(keep_count)
        args={};
    else
        args={keep_count};
    end

    [pca_samples,params]=cosmo_pca(samples,args{:});
    coef=params.coef;
    mu=params.mu;
    expl=params.explained;

function [pca_samples,coef,mu,expl]=helper_matlab_pca_wrapper(samples,...
                                                            keep_count)
    % PCA implementation using Matlab statistics toolbox
    cosmo_check_external('!pca',true);

    if isnan(keep_count)
        args={};
    else
        args={'NumComponents',keep_count};
    end

    [coef,pca_samples,unused,unused,expl,mu]=pca(samples,args{:});
    expl=expl';

function test_pca_more_samples_than_features
    nsamples=ceil(rand()*10)+10;
    nfeatures=nsamples+10;

    nfeatures=5;
    nsamples=2;

    helper_test_pca_correspondence(nsamples,nfeatures)

function test_pca_more_features_than_samples
    nfeatures=ceil(rand()*10)+10;
    nsamples=nfeatures+10;

    helper_test_pca_correspondence(nsamples,nfeatures)

function test_pca_col_vector
    nfeatures=1;
    nsamples=ceil(rand()*10)+10;

    helper_test_pca_correspondence(nsamples,nfeatures)

function test_pca_row_vector
    nfeatures=ceil(rand()*10)+10;
    nsamples=1;

    helper_test_pca_correspondence(nsamples,nfeatures)

function test_pca_near_square_samples
    nfeatures=ceil(rand()*10)+10;
    for nsamples=nfeatures+(-1:1);
        helper_test_pca_correspondence(nsamples,nfeatures)
    end

function test_pca_too_many_components
    nsamples=ceil(rand()*10)+10;
    nfeatures=nsamples;
    for nkeep=nfeatures+(-1:1)
        handle=@()cosmo_pca(rand(nsamples,nfeatures),nkeep);
        if nkeep>nfeatures
            assertExceptionThrown(handle,'');
        else
            handle(); % should be ok
        end
    end

function test_pca_regression
    xs=[   2.032   -0.8918  -0.8258    1.163    1.157   -1.291   ;...
           0.5838   1.844    1.166    -0.8484   3.493   -0.1991  ;...
          -1.444   -0.2617  -1.921     3.085   -1.372    1.727   ;...
          -0.5177   2.339    0.4412    1.856    0.4794   0.08323 ;...
           1.191   -0.204   -0.2088    1.755   -0.9548   0.5012  ;...
          -1.326    2.724    0.1476    0.5024   3.407   -0.4803  ];

    s=[  -0.5008    2.8648   -0.7589   -0.5301    0.0144  ;...
          3.5030    0.5915    0.2537    0.8888    0.0226  ;...
         -3.8914   -1.6525   -0.7549    0.4558    0.0157  ;...
          0.1140   -1.3350    1.0615   -0.7253    0.0293  ;...
         -2.1851    1.0744    0.9553    0.2445   -0.0444  ;...
          2.9603   -1.5432   -0.7566   -0.3338   -0.0376];

    coef=[  0.0014    0.7569    0.3369   -0.0540    0.3234  ;...
            0.4052   -0.5164    0.4105   -0.3355   -0.0290  ;...
            0.3133    0.0275    0.6618    0.0901    0.1745  ;...
           -0.4294   -0.2190   -0.0420   -0.5306    0.6797  ;...
            0.7090    0.0436   -0.5070    0.0744    0.4815  ;...
           -0.2251   -0.3313    0.1456    0.7677    0.4127];

    mu=[0.0864    0.9248   -0.2001    1.2522    1.0349    0.0568];

    explained=[64.7794   26.0994    6.0071    3.1059    0.0082];

    for nkeep=[NaN,1:7]
        if isnan(nkeep)
            args={};
            ncomp=5;
        else
            args={nkeep};
            ncomp=min(nkeep,5);
        end

        if nkeep>6
            assertExceptionThrown(@()cosmo_pca(xs,args{:}),'');
        else
            [xs_pca,param]=cosmo_pca(xs,args{:});

            tolerance_arg={'absolute',5e-3};
            assertElementsAlmostEqual(xs_pca,s(:,1:ncomp),...
                                        tolerance_arg{:});

            expected_fieldnames={'coef','explained','mu'};
            assertEqual(sort(fieldnames(param)),...
                            sort(expected_fieldnames(:)));
            assertElementsAlmostEqual(param.coef,coef(:,1:ncomp),...
                                                tolerance_arg{:});
            assertElementsAlmostEqual(param.mu,mu,...
                                                tolerance_arg{:});
            assertElementsAlmostEqual(param.explained,explained,...
                                                tolerance_arg{:});

        end
    end

function test_pca_basic_properties
    nfeatures=ceil(rand()*10+10);
    nsamples=ceil(rand()*10+10)+nfeatures;

    x=randn(nsamples,nfeatures);
    [y,param]=cosmo_pca(x);

    % explained variance is on diagonal
    d=y'*y;
    assertElementsAlmostEqual(100*diag(d)/trace(d),param.explained');

    % components are orthogonal
    d_zero_diag=d-diag(diag(d));
    assertElementsAlmostEqual(d_zero_diag,zeros(nfeatures));

    % average is computed correctly
    assertElementsAlmostEqual(mean(x,1),param.mu);

    % x can be reconstructed
    assertElementsAlmostEqual(x,bsxfun(@plus,param.mu,y*param.coef'));

function test_pca_exceptions()
    aet=@(varargin)assertExceptionThrown(@()...
                    cosmo_pca(varargin{:}),'');
    aet(struct);
    aet({1});
    aet(randn([2 2 2 ]));

function helper_test_pca_correspondence(nsamples,nfeatures)
    if cosmo_skip_test_if_no_external('!pca')
        return;
    end

    for nkeep=[NaN,-1,0,1,...
                ceil(nsamples/2),ceil(nfeatures/2),...
                nsamples-1,nfeatures-1,...
                nsamples,nfeatures,nsamples+1,nfeatures+1]
        helper_test_pca_correspondence_nkeep(nsamples,nfeatures,nkeep);
    end

function helper_test_pca_correspondence_nkeep(nsamples,nfeatures,nkeep)
    x=rand(nsamples,nfeatures);
    try
        % if the following statement throws an exception, then
        % matlab's pca must also throw an exception
        [p1,c1,m1,e1]=helper_matlab_pca_wrapper(x,nkeep);
    catch
        % cosmo pca should also throw error
        assertExceptionThrown(@()helper_cosmo_pca_wrapper(x,nkeep),'');
        return
    end

    % no error, verify that output match
    [p2,c2,m2,e2]=helper_cosmo_pca_wrapper(x,nkeep);

    tolerance_arg={'relative',1e-5};
    assertElementsAlmostEqual(p1,p2,tolerance_arg{:});
    assertElementsAlmostEqual(c1,c2,tolerance_arg{:});
    assertElementsAlmostEqual(m1,m2,tolerance_arg{:});
    assertElementsAlmostEqual(e1,e2,tolerance_arg{:});

function test_pca_retain_is_row_vector()
    nsamples=ceil(10+rand()*10);
    x=randn(nsamples);
    [y,params]=cosmo_pca(x);
    assertEqual(size(params.explained),[1 nsamples-1]);

author: CoSMoMVPA

repo: CoSMoMVPA

save_path: github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA


text:
%% manage paths

path_dict = manage_paths();

path2module = path_dict(1);
path2matlabcode_folder = path_dict(2);
path2input = path_dict(3);
path2output = path_dict(4);

%%
%Handover "mode", "another_map", "raceline_percentage_mode" & "raceline_percent_value" from Workspace
mode=evalin('base', 'mode');
another_map=evalin('base', 'another_map');
centerline_mode=evalin('base', 'centerline_mode');
raceline_percentage_mode=evalin('base', 'raceline_percentage_mode');
if raceline_percentage_mode==1
    raceline_percent_value=evalin('base', 'raceline_percent_value');
end
%Import Track file
if centerline_mode==1
    name=evalin('base','name');
    res_centerline_mode=evalin('base','resolution');
    track=importdata(strcat(path2output,'\tracks\Track_',name,'_',strrep((num2str(res_centerline_mode)),'.','-'),'.mat'));
    map_name=[name,'_',strrep((num2str(res_centerline_mode)),'.','-')];
else
    path_track=evalin('base','path_track');
    filename=evalin('base', 'filename');
    track=importdata(path_track);
    map_name=filename(7:end-4);
end

%Convert track to double
track=double(track);

%Get size of track_limits_filled file
pixelwidth_x=size(track,2);
pixelwidth_y=size(track,1);
if pixelwidth_x>=pixelwidth_y
    pixelwidth=pixelwidth_x;
else
    pixelwidth=pixelwidth_y;
end

%Extract origin of coordinates from track_limits_filled file
x_min_lim=track(1,1);
x_max_lim=track(1,2);
y_min_lim=track(2,1);
y_max_lim=track(2,2);

%Generate x-y-range array
x_lim=[x_min_lim x_max_lim];
y_lim=[y_min_lim y_max_lim];

%Generate parameter for random mode depending on size of track_limits_filled.pgm file
rand_n=round(pixelwidth/113)+1;

%Extract resolution of Map
resolution=track(1,3)/100;

%Generate origin of coordinates Array
limits=[x_min_lim x_max_lim ; y_min_lim y_max_lim ];

%Delete origin information
track(1:2,1:3)=0;
%Calculate raceline mode "normal" and "percentage"
if strcmp(mode,'raceline') || raceline_percentage_mode ==1
        %Handover Raceline Path from base workspace
        path_raceline=evalin('base','path_raceline');
        %Read in Raceline
        fid=fopen(path_raceline,'r');
        exportraceline=textscan(fid, '%f %f %f %f %f %f %f', 'Headerlines', 3, 'delimiter', ';');
        %exportraceline=textscan(fid, '%f %f', 'Headerlines', 2, 'delimiter', ';');
        fclose(fid);
        %Separate Columns of Raceline file, short file and get size
        x_0_race=exportraceline{:,2};
        y_0_race=exportraceline{:,3};
        intervall=round(size(x_0_race,1)/300);
        x_0_race=x_0_race(1:intervall:end,:);
        y_0_race=y_0_race(1:intervall:end,:);
        height=size(x_0_race,1);
        %Calculate gradients and normals of all points
        m_tang_race=gradient(y_0_race,x_0_race);
        m_normal_race= (-1./m_tang_race);
        %Calculate X and Y-component of displacement of 2 meters
        x_komp_2m=sqrt((2^2)./((1+m_normal_race.^2)));
        y_komp_2m=m_normal_race.*x_komp_2m;
        %Get variables from base workspace
        if strcmp(mode,'raceline')
            raceline_value_1=evalin('base', 'raceline_value_1');
            raceline_value_2=evalin('base', 'raceline_value_2');
        elseif raceline_percentage_mode==1
            raceline_value_1=1+raceline_percent_value/100;
            if raceline_value_1<1
                raceline_value_2=-0.03;
            else
                raceline_value_2=0.03;
            end
        end
        %Calculate new coordinates with distance of 0m, 4m and 10 meters
        xyz_0m=[x_0_race y_0_race raceline_value_1*ones(height,1)];
        xyz_4m_plus= [x_0_race+2*(x_komp_2m) y_0_race+2*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*4^2)*ones(height,1)];
        xyz_4m_minus= [x_0_race-2*(x_komp_2m) y_0_race-2*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*4^2)*ones(height,1)];
        xyz_10m_plus= [x_0_race+5*(x_komp_2m) y_0_race+5*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*10^2)*ones(height,1)];
        xyz_10m_minus= [x_0_race-5*(x_komp_2m) y_0_race-5*(y_komp_2m) raceline_value_1*exp(-raceline_value_2*0.1*10^2)*ones(height,1)];
        xyz=[xyz_0m;xyz_4m_plus;xyz_4m_minus;xyz_10m_plus;xyz_10m_minus];

        %Calculate conversion factors coordinates <-> pixels
        x_change=(pixelwidth_x/(abs(x_lim(1))+abs(x_lim(2))));
        y_change=(pixelwidth_y/(abs(y_lim(1))+abs(y_lim(2))));

        %Generate intervall in coordination space
        x_intervall=linspace(x_change*x_lim(1),x_change*x_lim(2),pixelwidth_x);
        y_intervall=linspace(y_change*y_lim(1),y_change*y_lim(2),pixelwidth_y);
        y_intervall=y_intervall(:);

        %Interpolate points in mesh
        [X,Y,Z]= griddata(x_change*xyz(:,1), y_change*xyz(:,2), xyz(:,3),x_intervall, y_intervall, 'cubic');
        Z=flipud(Z);
        %if raceline mode
        if strcmp(mode,'raceline')
            Z(isnan(Z))=0;
            Z(Z<0)=0;
        %if raceline percentage mode
        elseif raceline_percentage_mode==1
            Z(isnan(Z))=1;
            if raceline_value_1>1
                Z(Z<1)=1;
            else
                Z(Z>1)=1;
            end
        end
end

%Handover of other variables from Workspace depending on mode
%Insert origin of coordinates information and save file
currentFolder=cd;
switch mode
    case 'global'
         global_value=evalin('base', 'global_value');
         result=track.*global_value*100;
         if raceline_percentage_mode==1
             result=result.*Z;
         end
         result=int16(round(result));
         surf(result,'EdgeColor','none');
         set(gca,'YDir', 'reverse');
         set(gca,'XLim',[0, pixelwidth_x],'XTick',[0 pixelwidth_x]);
         set(gca,'YLim',[0, pixelwidth_y],'YTick',[0 pixelwidth_y]);
         view([0 90]);
         caxis([0 global_value*100+20]);
         colorbar
         result(1:2,1:2)=limits;
         result(1,3)=resolution*100;
         if raceline_percentage_mode==1
%             save([currentFolder,'\frictionmap_tools\matlab_code\outputs\maps\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'_Raceline_', strrep((num2str(raceline_percent_value)),'.','-'),'_Percent.mat'], 'result');
            save([currentFolder,'\variable_friction\generate_map\outputs\maps\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'_Raceline_', strrep((num2str(raceline_percent_value)),'.','-'),'_Percent.mat'], 'result');
         else
%             save([currentFolder,'\frictionmap_tools\matlab_code\outputs\maps\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'.mat'], 'result');
            save([currentFolder,'\variable_friction\generate_map\outputs\maps\Map_',map_name,'Meter_Global_',strrep((num2str(global_value)),'.','-'),'.mat'], 'result');
         end
    case 'random'
         random_value_1=evalin('base', 'random_value_1');
         random_value_2=evalin('base', 'random_value_2');
         A=rand(rand_n);
         B=A.*(random_value_2-random_value_1)+random_value_1;
         C=interp2(B,7,'cubic',0);
         D=C(1:pixelwidth_y,1:pixelwidth_x);
         result=D.*track*100;
         if raceline_percentage_mode==1
             result=result.*Z;
         end
         result=int16(round(result));
         surf(result,'EdgeColor','none');
         set(gca,'YDir', 'reverse');
         set(gca,'XLim',[0, pixelwidth_x],'XTick',[0 pixelwidth_x]);
         set(gca,'YLim',[0, pixelwidth_y],'YTick',[0 pixelwidth_y]);
         caxis([random_value_1*100-20 random_value_2*100+20]);
         colorbar
         view([0 90]);
         result(1:2,1:2)=limits;
         result(1,3)=resolution*100;
         if raceline_percentage_mode==1
             save(strcat(path2output,'\maps\Map_',map_name,'Meter_Random_',strrep((num2str(random_value_1)),'.','-'),'_',strrep((num2str(random_value_2)),'.','-'),'_Raceline_', strrep((num2str(raceline_percent_value)),'.','-'),'_Percent.mat'), 'result');
         else
             save(strcat(path2output,'\maps\Map_',map_name,'Meter_Random_',strrep((num2str(random_value_1)),'.','-'),'_',strrep((num2str(random_value_2)),'.','-'),'.mat'), 'result');
         end
    case 'raceline'
        result=Z.*track*100;
        result=int16(round(result));
        surf(result,'EdgeColor','none');
        set(gca,'YDir', 'reverse');
        set(gca,'XLim',[0, pixelwidth_x],'XTick',[0 pixelwidth_x]);
        set(gca,'YLim',[0, pixelwidth_y],'YTick',[0 pixelwidth_y]);
        view([0 90]);
        caxis([0 raceline_value_1*100]);
        colorbar
        result(1:2,1:2)=limits;
        result(1,3)=resolution*100;
        save([path2output, '\maps\Map_',map_name,'Meter_Raceline_',strrep((num2str(raceline_value_1)),'.','-'),'_',strrep((num2str(raceline_value_2)),'.','-'),'.mat'], 'result');
end
%If another_map==1, run Read_FrictionmodeGUI again
if another_map==1
    Read_FrictionmodeGUI();
    clc
    "Friction Coefficient Map(s) generated successfully!" %#ok<NOPTS>
elseif another_map==0
    clc
    "Friction Coefficient Map(s) generated successfully!" %#ok<NOPTS>
    evalin('base','clear');
end

author: TUMFTM


text:
function y = load_signal(name, n, options)

% load_signal - load a 1D signal
%
%   y = load_signal(name, n, options);
%
% name is a string that can be :
%   'regular' (options.alpha gives regularity)
%   'step', 'rand',
%   'gaussiannoise' (options.sigma gives width of filtering in pixels),
%   [natural signals]
%   'tiger', 'bell', 'bird'
%   [WAVELAB signals]
%   'HeaviSine', 'Bumps', 'Blocks',
%   'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',
%   'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',
%   'MishMash', 'WernerSorrows' (Heisenberg),
%   'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),
%	'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'
%	'sineoneoverx','Cusp2','SmoothCusp','Gaussian'
%	'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)

if nargin<2
    n = 1024;
end
options.null = 0;
if isfield(options, 'alpha')
    alpha = options.alpha;
else
    alpha = 2;
end

options.rep = '';
switch lower(name)
    case 'regular'
        y = gen_signal(n,alpha);
    case 'step'
        y = linspace(0,1,n)>0.5;
    case 'stepregular'
        y = linspace(0,1,n)>0.5; y=y(:);
        a = gen_signal(n,2); a = a(:);
        a = rescale(a,-0.1,0.1);
        y = y+a;
    case 'gaussiannoise'
        % filtered gaussian noise
        y = randn(n,1);
        if isfield(options, 'sigma')
            sigma = options.sigma; % variance in number of pixels
        else
            sigma = 20;
        end
        m = min(n, 6*round(sigma/2)+1);
        h = compute_gaussian_filter(m,sigma/(4*n),n);
        options.bound = 'per';
        y = perform_convolution(y,h, options);
    case 'rand'
        if isfield(options, 'p1')
            p1 = options.p1;
        else
            c = 10;
            p1 = 1:c; p1 = p1/sum(p1);
        end
        p1 = p1(:); c = length(p1);
        if isfield(options, 'p2')
            p2 = options.p2;
        else
            if isfield(options, 'evol')
                evol = options.evol;
            else
                evol = 0;
            end
            p2 = p1(:) + evol*(rand(c,1)-0.5);
            p2 = max(p2,0); p2 = p2/sum(p2);
        end
        y = zeros(n,1);
        for i=1:n
            a = (i-1)/(n-1);
            p = a*p1+(1-a)*p2; p = p/sum(p);
            y(i) = rand_discr(p, 1);
        end
    case 'bird'
        [y,fs] = load_sound([name '.wav'], n, options);
    case 'tiger'
        [y,fs] = load_sound([name '.au'], n, options);
    case 'bell'
        [y,fs] = load_sound([name '.wav'], n, options);
    otherwise
        y = MakeSignal(name,n);
end

y = y(:);

function y = gen_signal(n,alpha)

%   gen_signal -  generate a 1D C^\alpha signal of length n.
%
%   y = gen_signal(n,alpha);
%
%   The signal is scaled in [0,1].
%
%   Copyright (c) 2003 Gabriel Peyr?

if nargin<2
    alpha = 2;
end

y = randn(n,1);
fy = fft(y);
fy = fftshift(fy);
% filter with |omega|^{-\alpha}
h = (-n/2+1):(n/2);
h = (abs(h)+1).^(-alpha-0.5);
fy = fy.*h';
fy = fftshift(fy);
y = real( ifft(fy) );

y = (y-min(y))/(max(y)-min(y));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sig = MakeSignal(Name,n)
% MakeSignal -- Make artificial signal
%  Usage
%    sig = MakeSignal(Name,n)
%  Inputs
%    Name   string: 'HeaviSine', 'Bumps', 'Blocks',
%            'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',
%            'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',
%            'MishMash', 'WernerSorrows' (Heisenberg),
%            'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),
%	     'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'
%	     'sineoneoverx','Cusp2','SmoothCusp','Gaussian'
%	     'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)
%    n      desired signal length
%  Outputs
%    sig    1-d signal
%
%  References
%    Various articles of D.L. Donoho and I.M. Johnstone
%
if nargin > 1,
    t = (1:n) ./n;
end
Name = lower(Name);
if strcmp(Name,'heavisine'),
    sig = 4.*sin(4*pi.*t);
    sig = sig - sign(t - .3) - sign(.72 - t);
elseif strcmp(Name,'bumps'),
    pos = [ .1 .13 .15 .23 .25 .40 .44 .65  .76 .78 .81];
    hgt = [ 4  5   3   4  5  4.2 2.1 4.3  3.1 5.1 4.2];
    wth = [.005 .005 .006 .01 .01 .03 .01 .01  .005 .008 .005];
    sig = zeros(size(t));
    for j =1:length(pos)
        sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
    end
elseif strcmp(Name,'blocks'),
    pos = [ .1 .13 .15 .23 .25 .40 .44 .65  .76 .78 .81];
    hgt = [4 (-5) 3 (-4) 5 (-4.2) 2.1 4.3  (-3.1) 2.1 (-4.2)];
    sig = zeros(size(t));
    for j=1:length(pos)
        sig = sig + (1 + sign(t-pos(j))).*(hgt(j)/2) ;
    end
elseif strcmp(Name,'doppler'),
    sig = sqrt(t.*(1-t)).*sin((2*pi*1.05) ./(t+.05));
elseif strcmp(Name,'ramp'),
    sig = t - (t >= .37);
elseif strcmp(Name,'cusp'),
    sig = sqrt(abs(t - .37));
elseif strcmp(Name,'sing'),
    k = floor(n * .37);
    sig = 1 ./abs(t - (k+.5)/n);
elseif strcmp(Name,'hisine'),
    sig = sin( pi * (n * .6902) .* t);
elseif strcmp(Name,'losine'),
    sig = sin( pi * (n * .3333) .* t);
elseif strcmp(Name,'linchirp'),
    sig = sin(pi .* t .* ((n .* .500) .* t));
elseif strcmp(Name,'twochirp'),
    sig = sin(pi .* t .* (n .* t)) + sin((pi/3) .* t .* (n .* t));
elseif strcmp(Name,'quadchirp'),
    sig = sin( (pi/3) .* t .* (n .* t.^2));
elseif strcmp(Name,'mishmash'),  % QuadChirp + LinChirp + HiSine
    sig = sin( (pi/3) .* t .* (n .* t.^2)) ;
    sig = sig +  sin( pi * (n * .6902) .* t);
    sig = sig +  sin(pi .* t .* (n .* .125 .* t));
elseif strcmp(Name,'wernersorrows'),
    sig = sin( pi .* t .* (n/2 .* t.^2)) ;
    sig = sig +  sin( pi * (n * .6902) .* t);
    sig = sig +  sin(pi .* t .* (n .* t));
    pos = [ .1 .13 .15 .23 .25 .40 .44 .65  .76 .78 .81];
    hgt = [ 4  5   3   4  5  4.2 2.1 4.3  3.1 5.1 4.2];
    wth = [.005 .005 .006 .01 .01 .03 .01 .01  .005 .008 .005];
    for j =1:length(pos)
        sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
    end
elseif strcmp(Name,'leopold'),
    sig = (t == floor(.37 * n)/n);  % Kronecker
elseif strcmp(Name,'riemann'),
    sqn = round(sqrt(n));
    sig = t .* 0;  % Riemann's Non-differentiable Function
    sig((1:sqn).^2) = 1. ./ (1:sqn);
    sig = real(ifft(sig));
elseif strcmp(Name,'hypchirps'), % Hyperbolic Chirps of Mallat's book
    alpha	= 15*n*pi/1024;
    beta    = 5*n*pi/1024;
    t  	= (1.001:1:n+.001)./n;
    f1      = zeros(1,n);
    f2      = zeros(1,n);
    f1  	= sin(alpha./(.8-t)).*(0.1<t).*(t<0.68);
    f2  	= sin(beta./(.8-t)).*(0.1<t).*(t<0.75);
    M  	= round(0.65*n);
    P 	= floor(M/4);
    enveloppe = ones(1,M); % the rising cutoff function
    enveloppe(1:P) = (1+sin(-pi/2+((1:P)-ones(1,P))./(P-1)*pi))/2;
    enveloppe(M-P+1:M) = reverse(enveloppe(1:P));
    env 	= zeros(1,n);
    env(ceil(n/10):M+ceil(n/10)-1) = enveloppe(1:M);
    sig     = (f1+f2).*env;
elseif strcmp(Name,'linchirps'), % Linear Chirps of Mallat's book
    b 	= 100*n*pi/1024;
    a 	= 250*n*pi/1024;
    t 	= (1:n)./n;
    A1 	= sqrt((t-1/n).*(1-t));
    sig	= A1.*(cos((a*(t).^2)) + cos((b*t+a*(t).^2)));
elseif strcmp(Name,'chirps'), % Mixture of Chirps of Mallat's book
    t 	= (1:n)./n.*10.*pi;
    f1 	= cos(t.^2*n/1024);
    a 	= 30*n/1024;
    t 	= (1:n)./n.*pi;
    f2 	= cos(a.*(t.^3));
    f2 	= reverse(f2);
    ix 	= (-n:n)./n.*20;
    g 	= exp(-ix.^2*4*n/1024);
    i1 	= (n/2+1:n/2+n);
    i2 	= (n/8+1:n/8+n);
    j  	= (1:n)/n;
    f3 	= g(i1).*cos(50.*pi.*j*n/1024);
    f4 	= g(i2).*cos(350.*pi.*j*n/1024);
    sig 	= f1+f2+f3+f4;
    enveloppe = ones(1,n); % the rising cutoff function
    enveloppe(1:n/8) = (1+sin(-pi/2+((1:n/8)-ones(1,n/8))./(n/8-1)*pi))/2;
    enveloppe(7*n/8+1:n) = reverse(enveloppe(1:n/8));
    sig 	= sig.*enveloppe;
elseif strcmp(Name,'gabor'), % two modulated Gabor functions in
    % Mallat's book
    N = 512;
    t = (-N:N)*5/N;
    j = (1:N)./N;
    g = exp(-t.^2*20);
    i1 = (2*N/4+1:2*N/4+N);
    i2 = (N/4+1:N/4+N);
    sig1 = 3*g(i1).*exp(i*N/16.*pi.*j);
    sig2 = 3*g(i2).*exp(i*N/4.*pi.*j);
    sig = sig1+sig2;
elseif strcmp(Name,'sineoneoverx'), % sin(1/x) in Mallat's book
    N = 1024;
    a = (-N+1:N);
    a(N) = 1/100;
    a = a./(N-1);
    sig = sin(1.5./(i));
    sig = sig(513:1536);
elseif strcmp(Name,'cusp2'),
    N = 64;
    a = (1:N)./N;
    x = (1-sqrt(a)) + a/2 -.5;
    M = 8*N;
    sig = zeros(1,M);
    sig(M-1.5.*N+1:M-.5*N) = x;
    sig(M-2.5*N+2:M-1.5.*N+1) = reverse(x);
    sig(3*N+1:3*N + N) = .5*ones(1,N);
elseif strcmp(Name,'smoothcusp'),
    sig = MakeSignal('Cusp2');
    N = 64;
    M = 8*N;
    t = (1:M)/M;
    sigma = 0.01;
    g = exp(-.5.*(abs(t-.5)./sigma).^2)./sigma./sqrt(2*pi);
    g = fftshift(g);
    sig2 = iconv(g',sig)'/M;
elseif strcmp(Name,'piece-regular'),
    sig1=-15*MakeSignal('Bumps',n);
    t = (1:fix(n/12)) ./fix(n/12);
    sig2=-exp(4*t);
    t = (1:fix(n/7)) ./fix(n/7);
    sig5=exp(4*t)-exp(4);
    t = (1:fix(n/3)) ./fix(n/3);
    sigma=6/40;
    sig6=-70*exp(-((t-1/2).*(t-1/2))/(2*sigma^2));
    sig(1:fix(n/7))= sig6(1:fix(n/7));
    sig((fix(n/7)+1):fix(n/5))=0.5*sig6((fix(n/7)+1):fix(n/5));
    sig((fix(n/5)+1):fix(n/3))=sig6((fix(n/5)+1):fix(n/3));
    sig((fix(n/3)+1):fix(n/2))=sig1((fix(n/3)+1):fix(n/2));
    sig((fix(n/2)+1):(fix(n/2)+fix(n/12)))=sig2;
    sig((fix(n/2)+2*fix(n/12)):-1:(fix(n/2)+fix(n/12)+1))=sig2;
    sig(fix(n/2)+2*fix(n/12)+fix(n/20)+1:(fix(n/2)+2*fix(n/12)+3*fix(n/20)))=...
        -ones(1,fix(n/2)+2*fix(n/12)+3*fix(n/20)-fix(n/2)-2*fix(n/12)-fix(n/20))*25;
    k=fix(n/2)+2*fix(n/12)+3*fix(n/20);
    sig((k+1):(k+fix(n/7)))=sig5;
    diff=n-5*fix(n/5);
    sig(5*fix(n/5)+1:n)=sig(diff:-1:1);
    % zero-mean
    bias=sum(sig)/n;
    sig=bias-sig;
elseif strcmp(Name,'piece-polynomial'),
    t = (1:fix(n/5)) ./fix(n/5);
    sig1=20*(t.^3+t.^2+4);
    sig3=40*(2.*t.^3+t) + 100;
    sig2=10.*t.^3 + 45;
    sig4=16*t.^2+8.*t+16;
    sig5=20*(t+4);
    sig6(1:fix(n/10))=ones(1,fix(n/10));
    sig6=sig6*20;
    sig(1:fix(n/5))=sig1;
    sig(2*fix(n/5):-1:(fix(n/5)+1))=sig2;
    sig((2*fix(n/5)+1):3*fix(n/5))=sig3;
    sig((3*fix(n/5)+1):4*fix(n/5))=sig4;
    sig((4*fix(n/5)+1):5*fix(n/5))=sig5(fix(n/5):-1:1);
    diff=n-5*fix(n/5);
    sig(5*fix(n/5)+1:n)=sig(diff:-1:1);
    %sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=-ones(1,fix(n/10))*20;
    sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=ones(1,fix(n/10))*10;
    sig((n-fix(n/10)+1):(n+fix(n/20)-fix(n/10)))=ones(1,fix(n/20))*150;
    % zero-mean
    bias=sum(sig)/n;
    sig=sig-bias;
elseif strcmp(Name,'gaussian'),
    sig=GWN(n,beta);
    g=zeros(1,n);
    lim=alpha*n;
    mult=pi/(2*alpha*n);
    g(1:lim)=(cos(mult*(1:lim))).^2;
    g((n/2+1):n)=g((n/2):-1:1);
    g = rnshift(g,n/2);
    g=g/norm(g);
    sig=iconv(g,sig);
else
    disp(sprintf('MakeSignal: I don*t recognize <<%s>>',Name))
    disp('Allowable Names are:')
    disp('HeaviSine'),
    disp('Bumps'),
    disp('Blocks'),
    disp('Doppler'),
    disp('Ramp'),
    disp('Cusp'),
    disp('Crease'),
    disp('Sing'),
    disp('HiSine'),
    disp('LoSine'),
    disp('LinChirp'),
    disp('TwoChirp'),
    disp('QuadChirp'),
    disp('MishMash'),
    disp('WernerSorrows'),
    disp('Leopold'),
    disp('Sing'),
    disp('HiSine'),
    disp('LoSine'),
    disp('LinChirp'),
    disp('TwoChirp'),
    disp('QuadChirp'),
    disp('MishMash'),
    disp('WernerSorrows'),
    disp('Leopold'),
    disp('Riemann'),
    disp('HypChirps'),
    disp('LinChirps'),
    disp('Chirps'),
    disp('sineoneoverx'),
    disp('Cusp2'),
    disp('SmoothCusp'),
    disp('Gabor'),
    disp('Piece-Regular');
    disp('Piece-Polynomial');
    disp('Gaussian');
end

%
% Originally made by David L. Donoho.
% Function has been enhanced.

%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail wavelab@stat.stanford.edu
%

author: gpeyre

repo: matlab-toolboxes


text:
function [TorF, vstr, rdate] = have_feature_ipopt()
%HAVE_FEATURE_IPOPT  Detect availability/version info for IPOPT
%
%   Feature detection function implementing 'ipopt' tag for HAVE_FEATURE
%   to detect availability/version of IPOPT, a nonlinear programming
%   solver from COIN-OR (https://github.com/coin-or/Ipopt).
%
%   See also HAVE_FEATURE, NLPS_MASTER, QPS_MASTER, IPOPT.

%   MP-Opt-Model
%   Copyright (c) 2004-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MP-Opt-Model.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mp-opt-model for more info.

TorF = exist('ipopt', 'file') == 3;
vstr = '';
rdate = '';
if TorF
    if have_feature('evalc')
        str = evalc('qps_ipopt([],[1; 1],[1 1],[2],[2],[1; 1],[1; 1],[1; 1],struct(''verbose'', 2))');
        pat = 'Ipopt version ([^\s,]+)';
        [s,e,tE,m,t] = regexp(str, pat);
        if ~isempty(t)
            vstr = t{1}{1};
            if vstr2num(vstr) >= 3.011 && ~exist('ipopt_auxdata', 'file')
                TorF = 0;
                warning('Improper installation of IPOPT. Version %s detected, but IPOPT_AUXDATA.M is missing.', vstr);
            end
        end
    else
        try
            x = feval('qps_ipopt', [],[1; 1],[1 1],[2],[2],[1; 1],[1; 1],[1; 1],struct('verbose', 0));
            if ~isequal(x, [1;1])
                TorF = 0;
            end
        catch
            TorF = 0;
        end
    end
end

function num = vstr2num(vstr)
% Converts version string to numerical value suitable for < or > comparisons
% E.g. '3.11.4' -->  3.011004
pat = '\.?(\d+)';
[s,e,tE,m,t] = regexp(vstr, pat);
b = 1;
num = 0;
for k = 1:length(t)
    num = num + b * str2num(t{k}{1});
    b = b / 1000;
end

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
%% Hit-or-Miss Morphological Operation
%
% In this tutorial you will learn how to find a given configuration or pattern
% in a binary image by using the Hit-or-Miss transform (also known as
% Hit-and-Miss transform).
%
% This transform is also the basis of more advanced morphological operations
% such as thinning or pruning.
%
% We will use the OpenCV function |cv.morphologyEx|.
%
% Sources:
%
% * <https://docs.opencv.org/3.3.0/db/d06/tutorial_hitOrMiss.html>
% * <https://github.com/opencv/opencv/blob/3.3.0/samples/cpp/tutorial_code/ImgProc/HitMiss.cpp>
%

%% Theory
%
% Morphological operators process images based on their shape. These operators
% apply one or more _structuring elements_ to an input image to obtain the
% output image. The two basic morphological operations are the _erosion_ and
% the _dilation_. The combination of these two operations generate advanced
% morphological transformations such as _opening_, _closing_, or _top-hat_
% transform. To know more about these and other basic morphological operations
% refer to previous demos.
%
% The Hit-or-Miss transformation is useful to find patterns in binary images.
% In particular, it finds those pixels whose neighbourhood matches the shape
% of a first structuring element $B_1$ while not matching the shape of a
% second structuring element $B_2$ at the same time. Mathematically, the
% operation applied to an image $A$ can be expressed as follows:
%
% $$A \otimes B = (A \ominus B_1) \cap (A^c \ominus B_2)$$
%
% Therefore, the hit-or-miss operation comprises three steps:
%
% *# Erode image $A$ with structuring element $B_1$.
% *# Erode the complement of image $A$ ($A^c$) with structuring element $B_2$.
% *# AND results from step 1 and step 2.
%
% The structuring elements $B_1$ and $B_2$ can be combined into a single
% element $B$. Let's see an example:
%
% <<https://docs.opencv.org/3.3.0/hitmiss_kernels.png>>
%
% *Structuring elements (kernels). Left: kernel to 'hit'. Middle: kernel to
% 'miss'. Right: final combined kernel*
%
% In this case, we are looking for a pattern in which the central pixel
% belongs to the background while the north, south, east, and west pixels
% belong to the foreground. The rest of pixels in the neighbourhood can be of
% any kind, we don't care about them. Now, let's apply this kernel to an input
% image:
%
% <<https://docs.opencv.org/3.3.0/hitmiss_input.png>>
%
% You can see that the pattern is found in just one location within the image.
%
% <<https://docs.opencv.org/3.3.0/hitmiss_output.png>>
%
%% Other examples
%
% Here you can find the output results of applying different kernels to the
% same input image used before:
%
% * Kernel and output result for finding top-right corners
%
% <<https://docs.opencv.org/3.3.0/hitmiss_example2.png>>
%
% * Kernel and output result for finding left end points
%
% <<https://docs.opencv.org/3.3.0/hitmiss_example3.png>>
%
% Now try your own patterns!
%

%% Code

function hitmiss_demo()
    %%
    % input image
    img = 255 * uint8([
        0 0 0 0 0 0 0 0; ...
        0 1 1 1 0 0 0 1; ...
        0 1 1 1 0 0 0 0; ...
        0 1 1 1 0 1 0 0; ...
        0 0 1 0 0 0 0 0; ...
        0 0 1 0 0 1 1 0; ...
        0 1 0 1 0 0 1 0; ...
        0 1 1 0 0 0 0 0
    ]);
    figure, show_image(img), title('Original')

    %%
    % structuring element
    kernel = int32([0 1 0; 1 -1 1; 0 1 0]);
    figure, show_image(kernel), colorbar, title('Kernel')

    %%
    % hit-or-mess operation
    out = cv.morphologyEx(img, 'HitMiss', 'Element',kernel);
    figure, show_image(out), title('Hit or Miss')
end

%%
function show_image(img)
    % pad because PCOLOR chops off last row and column
    img = cv.copyMakeBorder(img, [0 1 0 1], 'BorderType','Constant');
    if mexopencv.isOctave()
        img = double(img);
    end
    h = pcolor(img);
    set(h, 'EdgeColor','b');
    set(gca, 'XAxisLocation','top')
    axis image ij, colormap(gray(3))
end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv