text:
function [A1nmb] = moran(initsize, popsize)
% MORAN generates a trajectory of a Moran type process
%  which gives the number of genes of allelic type A1 in a population
%  of haploid individuals that can exist in either type A1 or type A2.
%  The population size is popsize and the initial number of type A1
%  individuals os initsize.
%
%  [A1nmb] = galtonwatson(initsize, popsize)
%
%  Inputs: initsize - initial number of A1 genes
%          popsize - the total population size (preserved)
%
%  Outputs: A1nmb - the successive number of type A1 genes in the population

% Authors: R.Gaigalas, I.Kaj
% v1.2 04-Oct-02

if (nargin==0)
  initsize=10;
  popsize=30;
end

A1nmb=zeros(1,popsize);
A1nmb(1)=initsize;

lambda = inline('(x-1).*(1-(x-1)./N)', 'x', 'N');
mu = inline('(x-1).*(1-(x-1)./N)', 'x', 'N');

x=initsize;
i=1;
while  (x>1 & x<popsize+1)
  if (lambda(x,popsize)/(lambda(x,popsize)+mu(x,popsize))>rand)
   x=x+1;
   A1nmb(i)=x;
  else
   x=x-1;
   A1nmb(i)=x;
  end;
  i=i+1;
end;
nmbsteps=length(A1nmb);
rate = lambda(A1nmb(1:nmbsteps-1),popsize) ...
        +mu(A1nmb(1:nmbsteps-1),popsize);

jumptimes=cumsum(-log(rand(1,nmbsteps-1))./rate);
jumptimes=[0 jumptimes];

stairs(jumptimes,A1nmb);
axis([0 jumptimes(nmbsteps) 0 popsize+1]);

author: Sable

repo: mcbench-benchmarks


text:
function files_out = bids_spreadsheet2participants(varargin)
    %
    % routine to takes an spreadsheet file (for example: excel) as input and export as participants.tsv
    % and participants.json
    %
    % FORMAT files_out = bids_spreadsheet2participants(file_in,'ignore','field1','field2',...)
    %
    % INPUTS if empty user is prompted:
    %
    %   - 'file_in' is the excel file, with at least the 3 BIDS mandatory fields in the 1st sheet:
    %       - participant_id,
    %       - age,
    %       - gender
    %
    %     A second sheet can be used to specify variables for the json file column format:
    %       - variable name (same as sheet 1),
    %       - description,
    %       - values (optional)
    %
    %   - 'ignore' is the key to ignore specific fields (columns) in the excel file
    %     for example: 'ignore', 'variableX', 'variableY'
    %
    %   - 'export_dir' is the directory to save output files
    %
    % OUTPUT:
    %
    %   - 'files_out' is a cell array with:
    %       - files_out{1} the full name of the particpiants.tsv
    %       - files_out{2} the full name of the particpiants.json
    %
    % EXAMPLE:
    %
    %   files_out = bids_spreadsheet2participants('D:\icpsr_subset.xlsx','ignore','EEGtesttime')
    %
    % the spreadsheet must have:
    %   worksheet 1 with data, each column has a variable name and values
    %       -- note missing values MUST be n/a or nill
    %   worksheet 2 is optional with columns variables, Description, Levels, Units to describe worksheet 1
    %   variables similar to
    % https://bids-specification.readthedocs.io/en/stable/03-modality-agnostic-files.html#participants-file
    %       -- note the order of 'Levels' names should match the order of apparition in the data
    %          to have an exact match
    %
    % Requires matlab 2018a or above
    %
    % Cyril Pernet - March 2021
    % ---------------------------------

    if verLessThan('matlab', '9.4')
        error('This function requires matlab 2018a or above.');
    end

    files_out = cell(2, 1);
    % check library
    if ~exist('jsonwrite.m', 'file')
        if exist(fullfile(fileparts(which('bids_spreadsheet2participants.m')), 'JSONio'), 'dir')
            addpath(fullfile(fileparts(which('bids_spreadsheet2participants.m')), 'JSONio'));
        else
            error(['JSONio library needed, available with EEGLAB bids-matlab-tools or', ...
                   'at https://github.com/gllmflndn/JSONio']);
        end
    end

    %% deal with input file
    if nargin == 0
        [filename, pathname] = uigetfile({'*.xlsx;*.ods;*.xls'}, 'Pick an spreadsheet file');
        if isequal(filename, 0) || isequal(pathname, 0)
            disp('Selection cancelled');
            return
        else
            filein = fullfile(pathname, filename);
            disp(['file selected: ', filein]);
        end
    else
        filein = varargin{1};
        if ~exist(filein, 'file')
            error('%s not found', filein);
        end
    end

    % detect what's inside the selected file
    sheet1_opts = detectImportOptions(filein, 'Sheet', 1);
    try
        sheet2_opts = detectImportOptions(filein, 'PreserveVariableNames', true, 'Sheet', 2);
    catch one_sheet
        fprintf('import only variables: %s\n', one_sheet.message);
        sheet2_opts = [];
    end

    %% quickly check other arguments are valid
    if nargin > 1
        if ~any(contains(varargin, {'ignore', 'export'}, 'IgnoreCase', true))
            error('key input arguments in are missing ''ignore'' and/or ''export_dir''');
        else
            if any(contains(varargin, 'export', 'IgnoreCase', true))
                export_dir = varargin{find(contains(varargin, 'export', 'IgnoreCase', true)) + 1};
            end

            if any(contains(varargin, 'ignore', 'IgnoreCase', true))
                if any(contains(varargin, 'export', 'IgnoreCase', true))
                    if find(contains(varargin, 'ignore', 'IgnoreCase', true)) < ...
                      find(contains(varargin, 'export', 'IgnoreCase', true))
                        ignore_var = find(contains(varargin, 'ignore', 'IgnoreCase', true)) + ...
                          1:find(contains(varargin, 'export', 'IgnoreCase', true)) - 1;
                    else
                        ignore_var = find(contains(varargin, 'ignore', 'IgnoreCase', true)) + 1:nargin;
                    end
                else
                    ignore_var = find(contains(varargin, 'ignore', 'IgnoreCase', true)) + 1:nargin;
                end
            end
        end
    end

    %% create particpiants.tsv
    Data = readtable(filein, sheet1_opts);

    % 1st check mandatory/recommended fields are presents
    participant_idvar = any(strcmpi(Data.Properties.VariableNames, 'participant_id'));
    idvar = any(strcmpi(Data.Properties.VariableNames, 'id'));
    if idvar == 0 && participant_idvar == 0
        error('no participant ID variable detected, invalid file');
    elseif idvar == 1 && participant_idvar == 0
        disp('ID variable detected, the BIDS value exported will be participant_id ');
        Data.Properties.VariableNames(strcmpi(Data.Properties.VariableNames, 'id')) = {'participant_id'};
    end

    if length(unique(Data.participant_id)) ~= length(Data.participant_id)
        [~, idx] = unique(Data.participant_id);
        non_unique = setdiff(1:length(Data.participant_id), idx);
        non_unique = cell2mat(Data.participant_id(non_unique));
        for id = 1:size(non_unique, 1)
            warning('some IDs are duplicate: %s', non_unique(id, :));
        end
        error('non unique IDS are not permitted');
    end

    if any(strcmp(Data.Properties.VariableNames, 'Sex'))
        Data.Properties.VariableNames(strcmpi(Data.Properties.VariableNames, 'Sex')) = {'sex'};
    end
    sexvar = any(strcmpi(Data.Properties.VariableNames, 'sex'));
    gendervar = any(strcmpi(Data.Properties.VariableNames, 'gender'));
    if gendervar == 1 && sexvar == 0
        disp('gender variable detected - the recommended optional field is ''sex'' but ok using gender');
    end

    if any(strcmp(Data.Properties.VariableNames, 'Age'))
        Data.Properties.VariableNames(strcmpi(Data.Properties.VariableNames, 'Age')) = {'age'};
    end
    if ~any(strcmpi(Data.Properties.VariableNames, 'age'))
        disp('age variable is missing - this is only an optional field still exporting');
    else
        if ~isnumeric(Data.age)
            for v = 1:length(Data.age)
                Data.age{v} = str2double(Data.age{v});
            end
            Data.age = cell2mat(Data.age); % ensure age treated as number
        end
    end

    % 2nd check if any of those variable should be removed - and feedback if
    % some input variable names were not found
    if nargin > 1
        if any(contains(varargin, 'ignore', 'IgnoreCase', true))
            for var = ignore_var
                if any(contains(Data.Properties.VariableNames, varargin{var}, 'IgnoreCase', true))
                    Data = removevars(Data, varargin{var});
                else
                    fprintf('''%s'' input variable to ignore not recognized - skipping it\n', varargin{var});
                end
            end
        else
            warning('ignore argument not recognized - skipping any options');
        end
    end

    % last check variable values (also useful for metadata)
    if any(~contains(Data.participant_id, 'sub-'))
        disp('participant_id should include ''sub-'', adding it to current IDs');
        for sub = 1:length(Data.participant_id)
            if ~contains(Data.participant_id{sub}, 'sub-')
                Data.participant_id{sub} = ['sub-' Data.participant_id{sub}];
            end
        end
    end

    value_types = varfun(@class, Data, 'OutputFormat', 'cell');
    for v = length(value_types):-1:1
        values{v} = unique(Data.(Data.Properties.VariableNames{v}));
    end

    export_data = convert_NAN_to_na(Data);

    if ~exist('export_dir', 'var')
        export_dir = uigetdir(fileparts(filein), 'Select directory to save exported files');
        if export_dir == 0
            export_dir = fileparts(filein);
        end
    end
    try
        writetable(export_data, [export_dir filesep 'participants.tsv'], 'FileType', 'text', 'Delimiter', '\t');
        files_out{1} = fullfile(export_dir, 'participants.tsv');
        fprintf('participants.tsv file saved in %s\n', export_dir);
        clear export_data;
    catch tsv_error
        files_out{2} = 'particpants.tsv file not created';
        error('participants.tsv not saved %s\n', tsv_error.mewsage);
    end

    %% create participants.json
    if ~isempty(sheet2_opts)
        GivenMetaData = readtable(filein, sheet2_opts);

        if any(contains(GivenMetaData.Properties.VariableNames, 'Variable'))
            GivenMetaData.Properties.VariableNames(strcmpi(GivenMetaData.Properties.VariableNames, 'Variable')) = ...
              {'variables'};
        elseif any(contains(GivenMetaData.Properties.VariableNames, 'variable'))
            GivenMetaData.Properties.VariableNames(strcmpi(GivenMetaData.Properties.VariableNames, 'variable')) = ...
              {'variables'};
        end

        if ~any(strcmpi('variables', GivenMetaData.Properties.VariableNames))
            warning('metadata sheet provided but ''variables name'' not found - using worksheet 1');
        else
            % given variables present check description
            if ~any(contains(GivenMetaData.Properties.VariableNames, 'description', 'IgnoreCase', true))
                warning('metadata sheet provided but ''description of variables'' not found - using worksheet 1');
            else
                matched_var = cellfun(@(x) find(strcmpi(x, Data.Properties.VariableNames)), GivenMetaData.variables, ...
                                      'UniformOutput', false);
                matched_var(cellfun(@(x) isempty(x), matched_var')) = {0}; % mark empty as 0
                try
                    matched_var = cell2mat(matched_var); % works if unique, ie one value per cell
                    if any(contains(GivenMetaData.Properties.VariableNames, 'description'))
                        GivenMetaData.Properties.VariableNames(strcmpi(GivenMetaData.Properties.VariableNames, ...
                                                                       'description')) = ...
                          {'Description'};
                    end
                catch matched_var_err
                    warning(['variable names between worksheets likely not unique,', ...
                             ' skipping provided metadata \n%s\n'], ...
                            matched_var_err.message); %#ok<MEXCEP>
                end
            end

            % given variables present check levels
            if ~any(contains(GivenMetaData.Properties.VariableNames, 'level', 'IgnoreCase', true))
                warning('metadata sheet provided but ''levels'' not found - using worksheet 1');
            else
                if any(contains(GivenMetaData.Properties.VariableNames, 'level'))
                    GivenMetaData.Properties.VariableNames(strcmpi(GivenMetaData.Properties.VariableNames, ...
                                                                   'level')) = ...
                      {'Levels'};
                elseif any(contains(GivenMetaData.Properties.VariableNames, 'levels'))
                    GivenMetaData.Properties.VariableNames(strcmpi(GivenMetaData.Properties.VariableNames, ...
                                                                   'levels')) = ...
                      {'Levels'};
                end
            end

            % given variables present check unit
            if ~any(contains(GivenMetaData.Properties.VariableNames, 'unit', 'IgnoreCase', true))
                warning('metadata sheet provided but ''Units'' of variables not found');
            else
                if any(contains(GivenMetaData.Properties.VariableNames, 'unit'))
                    GivenMetaData.Properties.VariableNames(strcmpi(GivenMetaData.Properties.VariableNames, ...
                                                                   'unit')) = ...
                      {'Units'};
                elseif any(contains(GivenMetaData.Properties.VariableNames, 'units'))
                    GivenMetaData.Properties.VariableNames(strcmpi(GivenMetaData.Properties.VariableNames, ...
                                                                   'units')) = ...
                      {'Units'};
                end
            end
        end
    else
        matched_var = zeros(length(Data.Properties.VariableNames), 1);
    end

    % prepare json variables from worksheet 1
    % 'values' are the unique values read on the data
    % 'value_types' gives an indication if we want to use Level or Unit
    % we can complement with GivenMetaData.Description, GivenMetaData.Levels and GivenMetaData.Units
    % using 'matched_var' for instance: variables names match between worksheet

    json = struct;
    for var = 1:length(Data.Properties.VariableNames)
        if ~strcmpi(Data.Properties.VariableNames{var}, 'participant_id')
            % add description
            if ismember(var, matched_var)
                if any(contains(GivenMetaData.Properties.VariableNames, 'Description'))
                    if ~isempty(GivenMetaData.Description{matched_var == var})
                        json.(Data.Properties.VariableNames{var}).Description = ...
                          GivenMetaData.Description{matched_var == var};
                    else
                        json.(Data.Properties.VariableNames{var}).Description = [];
                    end
                end
            else
                json.(Data.Properties.VariableNames{var}).Description = [];
            end

            % add Levels and Units
            if strcmpi(value_types{var}, 'cell') % likely Levels
                if ismember(var, matched_var) && any(contains(GivenMetaData.Properties.VariableNames, 'Levels'))
                    if ~isempty(GivenMetaData.Levels{matched_var == var})
                        tmp = lower(GivenMetaData.Levels{matched_var == var});
                        tmp = regexprep(tmp, '\t', ';'); % in case tab is used
                        tmp(isspace(tmp)) = []; % deblank as well
                        separators = sort([strfind(tmp, ';') strfind(tmp, ',') length(tmp)]);
                        index1 = 1;
                        index2 = separators(1) - 1;
                        for l = 1:length(separators)
                            Levels{l} = tmp(index1:index2);
                            if l < length(separators)
                                index1 = separators(l) + 1;
                                index2 = separators(l + 1);
                            end
                        end

                        tmp = values{var};
                        tmp(strcmpi(tmp, 'n/a')) = [];
                        tmp(strcmpi(tmp, 'nill')) = [];
                        if length(tmp) ~= length(Levels)
                            warning('Levels of ''%s'' between data and metadata don''t match', ...
                                    Data.Properties.VariableNames{var});
                            % only write fields
                            for v = 1:length(tmp)
                                json.(Data.Properties.VariableNames{var}).Levels.(tmp{v}) = [];
                            end
                        else
                            % store levels
                            for v = 1:length(tmp)
                                json.(Data.Properties.VariableNames{var}).Levels.(tmp{v}) = Levels{v};
                            end
                        end
                    else
                        json.(Data.Properties.VariableNames{var}).Levels = [];
                    end
                else % no metadata
                    json.(Data.Properties.VariableNames{var}).Levels = values{var};
                end
            else % likely units
                if ismember(var, matched_var) && any(contains(GivenMetaData.Properties.VariableNames, 'Units'))
                    if ~isempty(GivenMetaData.Levels{var})
                        json.(Data.Properties.VariableNames{var}).Units = ...
                          lower(GivenMetaData.Units{matched_var == var});
                    else
                        json.(Data.Properties.VariableNames{var}).Units = [];
                    end
                else % no metadata
                    json.(Data.Properties.VariableNames{var}).Units = [];
                end
            end
        end
    end

    try
        jsonwrite([export_dir filesep 'participants.json'], json, struct('indent', ' '));
        files_out{2} = fullfile(export_dir, 'participants.json');
        fprintf('participants.json file saved in %s\n', export_dir);
        warndlg(sprintf('json file created, do check it ! \n it is almost certain it needs editing'), ...
                'BIDS spec', 'modal');
    catch json_err
        files_out{2} = 'particpants.json file not created';
        error('participants.json not saved %s\n', json_err.mewsage);
    end

end

function export_data = convert_NAN_to_na(data)

    % make sure to export NaN as n/a
    export_data = data;

    for v = 1:length(export_data.Properties.VariableNames)

        if strcmp(class(export_data.(cell2mat(export_data.Properties.VariableNames(v)))), 'double')

            export_data.(cell2mat(export_data.Properties.VariableNames(v))) = ...
              num2cell(export_data.(cell2mat(export_data.Properties.VariableNames(v))));

            for n = 1:size(export_data.(cell2mat(export_data.Properties.VariableNames(v))), 1)
                if isnan(export_data.(cell2mat(export_data.Properties.VariableNames(v))){n})
                    export_data.(cell2mat(export_data.Properties.VariableNames(v))){n} = 'n/a';
                end
            end

        end

    end

end

author: bids-standard

repo: bids-starter-kit


text:
function plot_overlap_recall_curve(iou_files, methods, num_candidates, fh, ...
  names_in_plot, legend_location, use_long_labels, custom_legend)

  if nargin < 7
    use_long_labels = false;
  end
  if nargin < 8
    custom_legend = [];
  end

  [~,method_order] = sort([methods.sort_key]);
  methods = methods(method_order);
  iou_files = iou_files(method_order);
  if ~isempty(custom_legend)
    custom_legend = custom_legend(method_order);
  end

  labels = {methods.short_name};
  long_labels = {methods.name};
  assert(numel(iou_files) == numel(labels));
  n = numel(iou_files);

  num_pos = zeros(n, 1);

  figure(fh);
  for i = 1:n
    data = load(iou_files{i});
    thresh_idx = find( ...
      [data.best_candidates.candidates_threshold] <= num_candidates, 1, 'last');
    experiment = data.best_candidates(thresh_idx);
    [overlaps, recall, auc] = compute_average_recall(experiment.best_candidates.iou);

    display_auc = auc * 100;
    % round to first decimal
    display_auc = round(display_auc * 10) / 10;
    display_num_candidates = mean([experiment.image_statistics.num_candidates]);
    display_num_candidates = round(display_num_candidates * 10) / 10;
    number_str = sprintf('%g (%g)', display_auc, display_num_candidates);
    if names_in_plot
      labels{i} = sprintf('%s %s', labels{i}, number_str);
      long_labels{i} = sprintf('%s %s', long_labels{i}, number_str);
    else
      labels{i} = number_str;
      long_labels{i} = number_str;
    end
    num_pos(i) = numel(overlaps);
    line_style = '-';
    if methods(i).is_baseline
      line_style = '--';
    end
    if ~isempty(methods(i).line_style)
      line_style = methods(i).line_style;
    end
    plot(overlaps, recall, 'Color', methods(i).color, 'LineWidth', 1.5, 'LineStyle', line_style);
    hold on;
  end
  grid on;
  xlabel('IoU overlap threshold');
  ylabel('recall');
  xlim([0.5, 1]);
  ylim([0, 1]);
  if ~strcmp(legend_location, 'none')
    if ~isempty(custom_legend)
      lgnd = legend(custom_legend, 'Location', legend_location);
    elseif use_long_labels
      lgnd = legend(long_labels, 'Location', legend_location);
    else
      lgnd = legend(labels, 'Location', legend_location);
    end
  %   set(lgnd, 'color','none');
  %   legendshrink(0.5);
    legend boxoff;
  end
end

author: hosang

repo: detection-proposals


text:
% EX_LAPLACE_SQUARE: solve the Poisson problem in the unit square with a B-spline discretization.

% 1) PHYSICAL DATA OF THE PROBLEM
clear problem_data
% Physical domain, defined as NURBS map given in a text file
problem_data.geo_name = 'geo_square.txt';

% Type of boundary conditions for each side of the domain
problem_data.nmnn_sides   = [];
problem_data.drchlt_sides = [1 2 3 4];

% Physical parameters
problem_data.c_diff  = @(x, y) ones(size(x));

% Source and boundary terms
problem_data.f = @(x, y) zeros (size (x));
problem_data.g = @test_square_g_nmnn;
problem_data.h = @(x, y, ind) exp (x) .* sin(y);

% Exact solution (optional)
problem_data.uex     = @(x, y) exp (x) .* sin (y);
problem_data.graduex = @(x, y) cat (1, ...
                       reshape (exp(x).*sin(y), [1, size(x)]), ...
                       reshape (exp(x).*cos(y), [1, size(x)]));

% 2) CHOICE OF THE DISCRETIZATION PARAMETERS
clear method_data
method_data.degree     = [3 3];       % Degree of the splines
method_data.regularity = [2 2];       % Regularity of the splines
method_data.nsub       = [9 9];       % Number of subdivisions
method_data.nquad      = [4 4];       % Points for the Gaussian quadrature rule

% 3) CALL TO THE SOLVER

[geometry, msh, space, u] = solve_laplace (problem_data, method_data);

% 4) POST-PROCESSING
% 4.1) EXPORT TO PARAVIEW

output_file = 'Square_BSP_Deg3_Reg2_Sub9';

vtk_pts = {linspace(0, 1, 20), linspace(0, 1, 20)};
fprintf ('The result is saved in the file %s \n \n', output_file);
sp_to_vtk (u, space, geometry, vtk_pts, output_file, 'u')

% 4.2) PLOT IN MATLAB. COMPARISON WITH THE EXACT SOLUTION

[eu, F] = sp_eval (u, space, geometry, vtk_pts);
[X, Y]  = deal (squeeze(F(1,:,:)), squeeze(F(2,:,:)));
subplot (1,2,1)
surf (X, Y, eu)
title ('Numerical solution'), axis tight
subplot (1,2,2)
surf (X, Y, problem_data.uex (X,Y))
title ('Exact solution'), axis tight

% Display errors of the computed solution in the L2 and H1 norm
[error_h1, error_l2] = ...
           sp_h1_error (space, msh, u, problem_data.uex, problem_data.graduex)

%!demo
%! ex_laplace_square

%!test
%! problem_data.geo_name = 'geo_square.txt';
%! problem_data.nmnn_sides   = [];
%! problem_data.drchlt_sides = [1 2 3 4];
%! problem_data.c_diff  = @(x, y) ones(size(x));
%! problem_data.f = @(x, y) zeros (size (x));
%! problem_data.g = @test_square_g_nmnn;
%! problem_data.h = @(x, y, ind) exp (x) .* sin(y);
%! problem_data.uex     = @(x, y) exp (x) .* sin (y);
%! problem_data.graduex = @(x, y) cat (1, ...
%!                       reshape (exp(x).*sin(y), [1, size(x)]), ...
%!                       reshape (exp(x).*cos(y), [1, size(x)]));
%! method_data.degree     = [3 3];       % Degree of the splines
%! method_data.regularity = [2 2];       % Regularity of the splines
%! method_data.nsub       = [9 9];       % Number of subdivisions
%! method_data.nquad      = [4 4];       % Points for the Gaussian quadrature rule
%! [geometry, msh, space, u] = solve_laplace (problem_data, method_data);
%! [error_h1, error_l2] = ...
%!           sp_h1_error (space, msh, u, problem_data.uex, problem_data.graduex);
%! assert (msh.nel, 81)
%! assert (space.ndof, 144)
%! assert (error_h1, 9.86428525677199e-06, 1e-14)
%! assert (error_l2, 1.68004134750130e-07, 1e-14)

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes


text:
function Out = unPivot(In,dim,rmPad)

% UNPIVOT Ungroup a pivot table into a flat dataset (n m by 3 matrix).
%
%   UNPIVOT(IN) Else by default
%       - In: cell or numeric pivot table (2-D).
%               -- In(1) must be NaN
%               -- Nested cells are not allowed
%
%   UNPIVOT(IN, DIM) How to sort output
%       - Dim: scalar, 1 or 2. Respectively sort output by column header or by row header.
%
%   UNPIVOT(IN, DIM, RMPAD) Remove padded values
%       - rmPad: specify which values are considered as padded.
%                NaN, scalars or char 1 by m.
%
%   OUT = ...
%       - Numeric or cell m by 3 matrix. First two columns, header values.
%         Sorted by the first column (ex-colHead) if DIM == 1 or by the
%         second column (ex-rowHead) if DIM == 2.
%
% Additional features:
% - FEX Pivot/unPivot page
%
% See also PIVOT

% Author: Oleg Komarov (oleg.komarov@hotmail.it)
% 16 dec 2009 - Created
% 20 dec 2009 - Compatibility from 7.1; added link to the submission
% 22 jan 2010 - Fixed column position in Out (the first was switched with the second)

% ------------------------------------------------------------------------
% CHECK
% ------------------------------------------------------------------------

% #Ninput
error(nargchk(1,3,nargin));

% In
if isscalar(In) || isvector(In)
    error('unPivot:inFmt','IN is not a pivot table')
elseif iscell(In)
    if ~isnan(In{1}); error('unPivot:inFmt','IN first element must be NaN'); end
    cellIn = true;
    if any(any(cellfun('isclass', In, 'cell')))
        error('unPivot:inFmt','IN nested cells not admitted')
    end
elseif isnumeric(In); cellIn = false;
    if ~isnan(In(1)); error('unPivot:inFmt','IN first element must be NaN'); end
else error('unPivot:inFmt','IN invalid format')
end

% Dim
if nargin == 1 || isempty(dim); dim = 1;
elseif isnumeric(dim)
    if ~(dim == 1 || dim == 2)
        error('unPivot:dimFmt','DIM must be 1 or 2')
    end
else error('unPivot:dimFmt','DIM invalid format')
end

% rmPad
if nargin < 3 || isempty(rmPad)
    rmPad = NaN;
elseif ~((isnumeric(rmPad) && isscalar(rmPad)) || (ischar(rmPad) && size(rmPad,1) == 1))
    error('unPivot:dimFmt','RMPAD invalid format')
end

% ------------------------------------------------------------------------
% ENGINE
% ------------------------------------------------------------------------

% Extract main parts
rowHead = In(1,2:end); colHead = In(2:end,1); values = In(2:end,2:end); clear In
sz = size(values);

% Index values to unpivot
IDX = 1:numel(values);

% Flip if sorting by rowHeader
if dim == 2
    IDX = reshape(IDX,sz)';
    values = values';
end

% Row and column indexes
[row, col] = ind2sub(sz,IDX(:));

% Output
Out = [reshape(rowHead(col),[],1), reshape(colHead(row),[],1),values(:)];
clear rowHead colHead values

% Unpad
if cellIn
    Out(cellfun('isempty', Out(:,end)),:) = [];
    IDXc = find(cellfun('isclass', Out(:,end),'char'));
    if ~isempty(IDXc)
        Chars = Out(IDXc,end); Out(IDXc,end) = {NaN};
    else Chars = [];
    end
    IDXp = false;
    if ischar(rmPad)
        IDXc(strcmp(rmPad,Chars)) = [];
        Chars = Chars(IDXc);
    elseif ~isnan(rmPad)
        IDXp = cellfun(@(x) rmPad == x, Out(:,end));
    end
        IDXnan = cellfun(@isnan, Out(:,end));
        IDXnan(IDXc) = false;
        if ~isempty(IDXc); Out(IDXc,end) = Chars;end
        Out(IDXnan | IDXp,:) = [];
    else
    if ~ischar(rmPad)
        if ~isnan(rmPad); Out(Out(:,end) == rmPad,:) = []; end
        Out(isnan(Out(:,end)),:) = [];
    end
end
end


text:
function lambda = pei_eigenvalues ( alpha, n )

%*****************************************************************************80
%
%% PEI_EIGENVALUES returns the eigenvalues of the PEI matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real ALPHA, the scalar that defines the Pei matrix.  A
%    typical value of ALPHA is 1.0.
%
%    Input, integer N, the order of A.
%
%    Output, real LAMBDA(N,1), the eigenvalues.
%
  lambda = zeros ( n, 1 );

  lambda(1:n-1,1) = alpha;
  lambda(n,1) = alpha + n;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [eid,emsg,varargout]=getargs(pnames,dflts,varargin)
%GETARGS Process parameter name/value pairs
%   [EID,EMSG,A,B,...]=GETARGS(PNAMES,DFLTS,'NAME1',VAL1,'NAME2',VAL2,...)
%   accepts a cell array PNAMES of valid parameter names, a cell array
%   DFLTS of default values for the parameters named in PNAMES, and
%   additional parameter name/value pairs.  Returns parameter values A,B,...
%   in the same order as the names in PNAMES.  Outputs corresponding to
%   entries in PNAMES that are not specified in the name/value pairs are
%   set to the corresponding value from DFLTS.  If nargout is equal to
%   length(PNAMES)+1, then unrecognized name/value pairs are an error.  If
%   nargout is equal to length(PNAMES)+2, then all unrecognized name/value
%   pairs are returned in a single cell array following any other outputs.
%
%   EID and EMSG are empty if the arguments are valid.  If an error occurs,
%   EMSG is the text of an error message and EID is the final component
%   of an error message id.  GETARGS does not actually throw any errors,
%   but rather returns EID and EMSG so that the caller may throw the error.
%   Outputs will be partially processed after an error occurs.
%
%   This utility can be used for processing name/value pair arguments.
%
%   Example:
%       pnames = {'color' 'linestyle', 'linewidth'}
%       dflts  = {    'r'         '_'          '1'}
%       varargin = {{'linew' 2 'nonesuch' [1 2 3] 'linestyle' ':'}
%       [eid,emsg,c,ls,lw] = statgetargs(pnames,dflts,varargin{:})    % error
%       [eid,emsg,c,ls,lw,ur] = statgetargs(pnames,dflts,varargin{:}) % ok

% We always create (nparams+2) outputs:
%    one each for emsg and eid
%    nparams varargs for values corresponding to names in pnames
% If they ask for one more (nargout == nparams+3), it's for unrecognized
% names/values

%   Original Copyright 1993-2008 The MathWorks, Inc.
%   Modified by Deng Cai (dengcai@gmail.com) 2011.11.27

% Initialize some variables
emsg = '';
eid = '';
nparams = length(pnames);
varargout = dflts;
unrecog = {};
nargs = length(varargin);

% Must have name/value pairs
if mod(nargs,2)~=0
    eid = 'WrongNumberArgs';
    emsg = 'Wrong number of arguments.';
else
    % Process name/value pairs
    for j=1:2:nargs
        pname = varargin{j};
        if ~ischar(pname)
            eid = 'BadParamName';
            emsg = 'Parameter name must be text.';
            break;
        end
        i = strcmpi(pname,pnames);
        i = find(i);
        if isempty(i)
            % if they've asked to get back unrecognized names/values, add this
            % one to the list
            if nargout > nparams+2
                unrecog((end+1):(end+2)) = {varargin{j} varargin{j+1}};
                % otherwise, it's an error
            else
                eid = 'BadParamName';
                emsg = sprintf('Invalid parameter name:  %s.',pname);
                break;
            end
        elseif length(i)>1
            eid = 'BadParamName';
            emsg = sprintf('Ambiguous parameter name:  %s.',pname);
            break;
        else
            varargout{i} = varargin{j+1};
        end
    end
end

varargout{nparams+1} = unrecog;

author: ZJULearning

repo: MatlabFunc


text:
function [dateNum, dateStr] = getCurrTime()
ds = char(datetime('now','TimeZone','local','Format','yyyy-MM-dd HH:mm:ss'));
[dateNum, dateStr] = datestr2datenum(ds);

author: BUNPC


text:
%
%  Context-Aware Correlation Filters
%
%  Written by Matthias Mueller, 2016
%
%  This function takes care of setting up parameters,
%  and interfacing with the online tracking benchmark.

function results=run_MOSSE_CA(seq, res_path, bSaveImage)

%default settings
kernel.type =  'linear';

padding = 2;%1.75;  %extra area surrounding the target
lambda1 = 1e-4;     %regularization
lambda2 = 20;%0.8;
interp_factor = 0.05;%0.025;  %linear interpolation factor for adaptation
output_sigma_factor = 0.1; %0.06;  %spatial bandwidth (proportional to target)

features.gray = true;
features.hog = false;

cell_size = 1;

target_sz = seq.init_rect(1,[4,3]);
pos = seq.init_rect(1,[2,1]) + floor(target_sz/2);
img_files = seq.s_frames;
video_path = [];

%call tracker function with all the relevant parameters
[positions, time] = tracker(video_path, img_files, pos, target_sz, ...
    padding, kernel, lambda1, lambda2, output_sigma_factor, interp_factor, ...
    cell_size, features, false);

%return results to benchmark, in a workspace variable
rects = [positions(:,2) - target_sz(2)/2, positions(:,1) - target_sz(1)/2];
rects(:,3) = target_sz(2);
rects(:,4) = target_sz(1);
fps = numel(seq.s_frames) / time;
disp(['fps: ' num2str(fps)])
results.type = 'rect';
results.res = rects;
results.fps = fps;
%assignin('base', 'res', res);

end

repo: Context-Aware-CF-Tracking


text:
function isDataReal = isreal(this)
% Checks whether all data elements in image are real
%
%   Y = MrImage();
%   isDataReal = isreal(Y)
%
%
% This is a method of class MrImage.
%
% IN
%
% OUT
%   isDataReal            true, if all elements in MrImage.data are real
%                         false, otherwise (i.e. complex entries)
%
% EXAMPLE
%   isDataReal = isreal(Y)
%
%   See also MrImage

% Author:   Saskia Klein & Lars Kasper
% Created:  2014-12-01
% Copyright (C) 2014 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC 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/>.
%

isDataReal = isreal(this.data);

author: translationalneuromodeling

repo: tapas


text:
function copl = isCoplanar(x,y,z,tol)
%ISCOPLANAR Tests input points for coplanarity in 3-space.
%
% COPL = isCoplanar(PTS)
% Tests the coplanarity of the input points in array PTS. Input array must
% be 4-by-3, each row containing coordinate of one point.
%
% COPL = isCoplanar(PTS, TOLERANCE)
% Specifies the tolerance value used for checking coplanarity. Default is
% zero.
%
%
% Example:
%   iscoplanar([1 2 -2; -3 1 -14; -1 2 -6; 1 -2 -8], eps)

%
% Adapted from a function originally written by Brett Shoelson, Ph.D.
% brett.shoelson@joslin.harvard.edu
% https://fr.mathworks.com/matlabcentral/fileexchange/46-iscoplanar-m
%

if nargin == 0
	error('Requires at least one input argument.');

elseif nargin == 1
    if size(x,2) == 3
        % Matrix of all x,y,z is input
        pts = x;
        tol = 0;
    else
        error('Invalid input.')
    end

elseif nargin == 2
	if size(x,2) == 3
		% Matrix of all x,y,z is input
		pts = x;
		tol = y;
	else
		error('Invalid input.')
	end
elseif nargin == 3
	% Compile a matrix of all x,y,z
	pts = [x y z];
	tol = 0;
else
	pts = [x y z];
end

if size(x, 1) < 4
    error('Requires at least four points to compute coplanarity');
end

% replace first point at the origin and compute SVD of the matrix
sv = svd(bsxfun(@minus, pts(2:end,:), pts(1,:)));
copl = sv(3) <= tol * sv(1);

% % Alterantive version that computes the rank of the matrix
% rnk = rank(bsxfun(@minus, pts(2:end,:), pts(1,:)), tol);
% copl = rnk <= size(pts, 2) - 1;

% % Old version:
% %Compare all 4-tuples of point combinations; {P1:P4} are coplanar iff
% %det([x1 y1 z1 1;x2 y2 z2 1;x3 y3 z3 1;x4 y4 z4 1])==0
% tmp = nchoosek(1:size(pts,1),4);
% for ii = 1:size(tmp,1)
% 	copl = abs(det([pts(tmp(ii, :), :) ones(4,1)])) <= tolerance;
% 	if ~copl
% 		break
% 	end
% end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
% This script depends on
% - ex_run_rpca.m
% Please execute the dependencies before
% running this script.

close all; clear all; clc;
fprintf('Loading RPCA images.\n');
load bin/yale_rpca_cache.mat;
fprintf('Loaded RPCA images.\n');
full_width = 168;
full_height = 192;
full_image_size = full_width * full_height;
num_subjects = 38;
images_per_subject  = 50;
orig_images = rpca_images;
[s, n]  = size(orig_images);
width = 42;
height = 48;
sz = width * height;
Y = zeros(sz, n);
for i=1:n
    fprintf('Resizing: %d\n',  i);
    image = reshape(orig_images(:, i), full_height, full_width);
    resized_image = imresize(image, [height, width]);
    Y(:, i) = reshape(resized_image, sz, 1);
end
fprintf('Saving resized RPCA images.\n');
save('bin/yale_rpca_downsampled_images', 'Y');
fprintf('Saved resized RPCA images.\n');

author: indigits

repo: sparse-plex


text:
function edl_initctrlfile(filename, guidstr, n)
%EDL_INITCTRLFILE Creates an initial control file
%
% $ Syntax $
%   - edl_initctrlfile(filename, guidstr, n)
%
% $ Arguments $
%   - filename:     the destination control filename
%   - guidstr:      the GUID identifying the corresponding script
%   - n:            the number of items
%
% $ Description $
%   - edl_initctrlfile(filename, guidstr, n) writes an initial control
%     file with all status set to pending.
%
% $ History $
%   - Created by Dahua Lin, on Aug 14th, 2006
%

%% parse and verify input

if nargin < 3
    raise_lackinput('edl_initctrlfile', 3);
end

%% Write

doctag = 'ExpControl';
attribs.guid = guidstr;
nodetag = 'Entry';

props = struct(...
    'internal_index', mat2cell((1:n)', ones(n,1)), ...
    'status', repmat({'pending'}, [n, 1]) ...
    );

edl_writeprops(doctag, attribs, nodetag, props, filename)

author: lmthang


text:
function obj = runICPTransformFinal(obj, p, g)

msg('S', {g.proc{:} 'TRANSFORMATION'}, 'LogLevel', 'basic');

for i = 1:g.nPC

    % Find new path
    [~, file] = fileparts(obj.PC{i});
    p2mat = fullfile(obj.OutputFolder, [file '_POSTICP.mat']);

    if ~ismember(i, p.IdxFixedPointClouds) % trafo only if point cloud is not fixed, i.e. loose

        % Load point cloud
        PC = obj.loadPC(i);

        % Trafo
        PC.transform(1, obj.D.H{1,i}(1:3,1:3), obj.D.H{1,i}(1:3,4));

        % Update mat file
        PC.save(p2mat);

    else

        % Copy original mat file
        copyfile(obj.PC{i}, p2mat);

    end

    % Set new path
    obj.PC{i} = p2mat;

end

msg('E', {g.proc{:} 'TRANSFORMATION'}, 'LogLevel', 'basic');

end

author: pglira


text:
function checkroot(a,b)
% CHECKROOT checks that the root members of a&b are the same

if isempty(a.root)|isempty(b.root), return, end
if (length(a.root)~=length(b.root))|any(a.root~=b.root)
   error('adiff objects must come from the same root')
end

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
function [C, N] = spm_mesh_clusters(M,T)
% Label connected components of surface mesh data
% FORMAT [C, N] = spm_mesh_clusters(M,T)
% M        - a [mx3] faces array or a patch structure
% T        - a [nx1] data vector (using NaNs or logicals), n = #vertices
%
% C        - a [nx1] vector of cluster indices
% N        - a [px1] size of connected components {in vertices}
%__________________________________________________________________________
% Copyright (C) 2010-2012 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin
% $Id: spm_mesh_clusters.m 5065 2012-11-16 20:00:21Z guillaume $

%-Input parameters
%--------------------------------------------------------------------------
if ~islogical(T)
    T   = ~isnan(T);
end

%-Compute the (reduced) adjacency matrix
%--------------------------------------------------------------------------
A       = spm_mesh_adjacency(M);
A       = A + speye(size(A));
A(~T,:) = [];
A(:,~T) = [];

%-And perform Dulmage-Mendelsohn decomposition to find connected components
%--------------------------------------------------------------------------
[p,q,r] = dmperm(A);
N       = diff(r);
CC      = zeros(size(A,1),1);
for i=1:length(r)-1
    CC(p(r(i):r(i+1)-1)) = i;
end
C       = NaN(numel(T),1);
C(T)    = CC;

%-Sort connected component labels according to their size
%--------------------------------------------------------------------------
[N,ni]  = sort(N(:), 1, 'descend');
[ni,ni] = sort(ni);
C(T)    = ni(C(T));

author: spm


text:
function W = getPCAWhite( fv_data, targetDim )
%GETPCAWHITE Compute PCA-Whitening matrix
%   Dependency on pca() function of MATLAB Statistics Toolbox

    % pca() expects data to be row-wise, hence transposed fv_data
    [pca_proj, ~, pca_eigvals] = ...
                   pca(fv_data', 'NumComponents', targetDim, ...
                    'Centered',false);

    whiteMat =  diag(1./sqrt(pca_eigvals(1:targetDim) + 1e-5));
    W = single(whiteMat * pca_proj');

end

author: suhangpro

repo: mvcnn

save_path: github-repos/MATLAB/suhangpro-mvcnn


text:
function handles = configSettingsGUI(varargin)
handles = [];

% Parse args
[filenames, nParamsPerCol, lastpos, options] = ParseArgs(varargin);

InitializeGuiStruct(filenames, options);
hf = CreateGui();
ResetGui(hf);
ResizeGui(hf, nParamsPerCol, lastpos);
hBttnSave = DrawBttns(hf);
DrawConfigParams(hf, hBttnSave);
handles.figure = hf;

% ----------------------------------------------------------
function [filenames, nParamsPerCol, lastpos, options] = ParseArgs(args)
filenames = {};
nParamsPerCol = [];
lastpos = [];
options = '';
if ~isempty(args) && isnumeric(args{end}) && length(args{end})==4
    lastpos = args{end};
    args(end) = [];
end
if length(args)==1
    if iscell(args{1}) || ischar(args{1})
        filenames = args{1};
    else
        nParamsPerCol = args{1};
    end
elseif length(args)==2
    if iscell(args{1}) || ischar(args{1})
        filenames = args{1};
        nParamsPerCol = args{2};
    else
        filenames = args{2};
        nParamsPerCol = args{1};
    end
elseif length(args)==3
    if iscell(args{1}) || ischar(args{1})
        filenames = args{1};
        nParamsPerCol = args{2};
    else
        filenames = args{2};
        nParamsPerCol = args{1};
    end
    options = args{2};
end
if ~exist('filenames','var') || isempty(filenames)
    filenames = {};
end
if ~exist('nParamsPerCol','var') || isempty(nParamsPerCol)
    nParamsPerCol = 6;
end
if ~exist('options','var')
    options = '';
end
if nParamsPerCol<1
    nParamsPerCol = 1;
end
if nParamsPerCol>12
    nParamsPerCol = 12;
end

% -------------------------------------------------------------
function InitializeGuiStruct(filenames, options)
global cfgGui

if ~isempty(cfgGui)
    if ishandles(cfgGui.handle)
        return;
    end
end

cfgGui = struct(...
    'filedata',[], ...
    'ysizeParam',0, ...
    'xsizeParam',0, ...
    'ysizeBttn',0, ...
    'xsizeBttn',0, ...
    'ysizeGap',0, ...
    'xsizeGap',0, ...
    'nrows',0, ...
    'ncols',0, ...
    'ysizeTotal',0, ...
    'xsizeTotal',0, ...
    'ysizeParamsAll',0, ...
    'xsizeParamsAll',0, ...
    'nParamsPerCol',8, ...
    'handle',[], ...
    'pos',[] ...
    );

cfgGui.filedata = ConfigFileClass(filenames);

% char to pixel conversion
cfgGui.units = 'pixels';
[fx, fy] = guiUnitConversion('characters', cfgGui.units);

% Hardcode size of each parameter panel in char units
cfgGui.ysizeParam = 5*fy;
cfgGui.xsizeParam = 50*fx;

% Hardcode size of each buttons
cfgGui.ysizeBttn = 2.4*fy;
cfgGui.xsizeBttn = 25*fx;

% Gaps sizes between controls
cfgGui.ysizeGap = 1*fy;
cfgGui.xsizeGap = 2*fx;

cfgGui.fontsizes = [15, 11, 10, 9];
if ismac()
    cfgGui.fontsizes = cfgGui.fontsizes+4;
end
cfgGui.posParam     = [.10,.10,.80,.80];

cfgGui.options = options;

% -------------------------------------------------------------
function hf = CreateGui()
global cfgGui

if ~ishandles(cfgGui.handle)
    hf = figure('name', 'App Setting Config GUI', 'NumberTitle','off', 'MenuBar','none', 'ToolBar','none', ...
        'units',cfgGui.units);
else
    hf = cfgGui.handle;
end
cfgGui.handle = hf;

% -------------------------------------------------------------
function ResetGui(hf)
hc = get(hf, 'children');
for ii = 1:length(hc)
    if strcmpi(get(hc(ii), 'type'), 'uimenu')
        continue;
    end
    delete(hc(ii));
end

% -------------------------------------------------------------
function ResizeGui(hf, nParamsPerCol, ~)
global cfgGui

cfgGui.nParamsPerCol = nParamsPerCol;

p0 = get(hf, 'position');

% Calculate number of columns and rows needed to accomodate all the
% parameters
cfgGui.np = cfgGui.filedata.GetParamNum();
if floor(cfgGui.np/cfgGui.nParamsPerCol) == 0
    k = 1;
elseif floor(cfgGui.np/cfgGui.nParamsPerCol) == cfgGui.np/cfgGui.nParamsPerCol
    k = 0;
else
    k = 1;
end
cfgGui.ncols = floor(cfgGui.np/cfgGui.nParamsPerCol)+k;
cfgGui.nrows = cfgGui.nParamsPerCol;
cfgGui.ysizeParamsAll = cfgGui.nrows * (cfgGui.ysizeParam + cfgGui.ysizeGap) + 2*cfgGui.ysizeGap;
cfgGui.xsizeParamsAll = cfgGui.ncols * (cfgGui.xsizeParam + cfgGui.xsizeGap) + 2*cfgGui.xsizeGap;
cfgGui.ysizeTotal = cfgGui.ysizeParamsAll+cfgGui.ysizeBttn+4*cfgGui.ysizeGap;
cfgGui.xsizeTotal = cfgGui.xsizeParamsAll;
set(hf, 'position', [p0(1), p0(2), cfgGui.xsizeTotal, cfgGui.ysizeTotal])
rePositionGuiWithinScreen(hf);

% -------------------------------------------------------------
function hv = DrawConfigParams(hf, hBttnSave)
global cfgGui

np = cfgGui.filedata.GetParamNum();
hp = zeros(np,1);
hcm = setMouseClickAction();

for i = 1:cfgGui.ncols
    for j = 1:cfgGui.nrows
        % Figure out param panel position
        xpos    = (cfgGui.xsizeParam+cfgGui.xsizeGap)*(i-1) + cfgGui.xsizeGap;
        ypos    = cfgGui.ysizeTotal - 2*cfgGui.ysizeGap - (cfgGui.ysizeParam+cfgGui.ysizeGap)*j;
        posPanel = [xpos, ypos, cfgGui.xsizeParam, cfgGui.ysizeParam];

        ip = cfgGui.nParamsPerCol*(i-1) + j;
        if ip>np
            if np==0
                uicontrol(hf, 'Style','text', 'string','CONFIG FILE IS EMPTY', 'FontSize',cfgGui.fontsizes(2), ...
                          'fontweight','bold', 'units',cfgGui.units, 'Position',posPanel, 'foregroundcolor',[.6,.3,.1]);
            end
            break;
        end

        % Draw param panel
        hp(ip) = uipanel('parent',hf, 'Title',cfgGui.filedata.GetParamName(ip), 'FontSize',cfgGui.fontsizes(3), 'fontweight','bold', 'foregroundcolor',[.6,.3,.1], ...
            'units',cfgGui.units, 'Position',posPanel);

        % Draw param values control within panel. Note all controls have same relative position within panel
        pval = cfgGui.filedata.GetParamValue(ip);
        if isempty(pval)
            pval = '';
        end
        if isempty(cfgGui.filedata.GetParamValueOptions(ip))
            hv = uicontrol(hp(ip), 'Style','edit', 'string',pval, 'FontSize',cfgGui.fontsizes(4), 'fontweight','bold', 'Tag',cfgGui.filedata.GetParamName(ip), ...
                           'units','normalized', 'position',cfgGui.posParam);
        else
            hv = uicontrol(hp(ip), 'Style','popupmenu', 'string',cfgGui.filedata.GetParamValueOptions(ip), ...
                           'FontSize',cfgGui.fontsizes(4), 'fontweight','bold', 'Tag',cfgGui.filedata.GetParamName(ip), ...
                           'units','normalized', 'position',cfgGui.posParam);
            k = find(strcmp(cfgGui.filedata.GetParamValueOptions(ip), pval));
            if isempty(k)
                set(hv, 'string',[{''}; cfgGui.filedata.GetParamValueOptions(ip)]);
            else
                hv.Value = k;
            end
        end
        hv.Callback = {@setVal, hBttnSave};
    end

end

if verGreaterThanOrEqual('matlab','9.8')
    set(hp, 'ContextMenu',setMouseClickAction(hcm,hp));
else
    set(hp, 'ButtonDownFcn',{@mouseClickFcn_Callback,hp});
end
set(hf, 'ButtonDownFcn',{@mouseClickFcn_Callback,hp});

% -------------------------------------------------------------
function [hBttnSave, hBttnExit] = DrawBttns(hf)
global cfgGui

if cfgGui.ncols == 1
    k = 10;
else
    k = 5;
end
xoffset = cfgGui.xsizeTotal/k;
hBttnSave = uicontrol(hf, 'Style','pushbutton', 'FontSize',cfgGui.fontsizes(1), 'Units',cfgGui.units, 'String','SAVE', ...
    'Position', [xoffset, cfgGui.ysizeTotal-(cfgGui.ysizeParamsAll+cfgGui.ysizeParam), cfgGui.xsizeBttn, cfgGui.ysizeBttn]);
hBttnSave.Callback = @cfgSave;
hBttnExit = uicontrol(hf, 'Style','pushbutton', 'FontSize',cfgGui.fontsizes(1), 'Units',cfgGui.units, 'String','EXIT', ...
    'Position', [cfgGui.xsizeTotal-(cfgGui.xsizeBttn+xoffset), cfgGui.ysizeTotal-(cfgGui.ysizeParamsAll+cfgGui.ysizeParam), cfgGui.xsizeBttn, cfgGui.ysizeBttn]);
hBttnExit.Callback = @cfgExit;
setappdata(hBttnSave, 'backgroundcolororiginal',hBttnSave.BackgroundColor);
setappdata(hBttnSave, 'foregroundcolororiginal',hBttnSave.ForegroundColor);

% -------------------------------------------------------------
function setVal(hObject, ~, hBttnSave)
global cfgGui

if strcmp(hObject.Style, 'popupmenu')
    if hObject.Value>0
        s = hObject.String{hObject.Value};
    else
        s = {};
    end
else
    s = hObject.String;
end
if iscell(s) && ~isempty(s)
    s = s{1};
elseif isempty(s)
    s = '';
end

% Check if param value has changed
if cfgGui.filedata.ChangedValue(hObject.Tag, s)
    hBttnSave.BackgroundColor = [.90, .10, .05];
    hBttnSave.ForegroundColor = [.90, .80, .75];
end
cfgGui.filedata.SetValue(hObject.Tag, s);

% -------------------------------------------------------------
function cfgSave(hObject, ~) %#ok<*DEFNU>
global cfgGui
global cfg
cfgGui.filedata.Save();

% This is the only place in configSettingsGUI that we access global cfg.
% We only use it to update the global variable when we to save changes
if isa(cfg, 'ConfigFileClass')
    cfg.Update();
end

hObject.BackgroundColor = getappdata(hObject, 'backgroundcolororiginal');
hObject.ForegroundColor = getappdata(hObject, 'foregroundcolororiginal');
if optionExists(cfgGui.options, {'keepopen','stayopen'})
    return
end
close;

% -------------------------------------------------------------
function cfgExit(~,~)
close;

% -------------------------------------------------------------
function mouseClickFcn_Callback(hObject, ~, handles)
type = get(hObject, 'type');
if strcmp(type, 'figure')
    return;
end

hf = [];
while ~strcmp(type, 'root')
    hObject = get(hObject, 'parent');
    type = get(hObject, 'type');
    if strcmp(type, 'figure')
        hf = hObject;
        break;
    end
end
if isempty(hf)
    return;
end

me = get(hf,'selectiontype');
if ~strcmp(me, 'alt')
    return
end

mp = get(hf,'currentpoint');
if length(mp)<2
    return;
end
% fprintf('Mouse click position: [%0.1f, %0.1f]:\n\n', mp(1), mp(2));
paramNameClicked = '';
for ii = 1:length(handles)
    p = get(handles(ii), 'position');
    paramName = get(handles(ii), 'title');
    if (mp(1)>=p(1) && mp(1)<=p(1)+p(3)) && (mp(2)>=p(2) && mp(2)<=p(2)+p(4))
        % fprintf('**** Clicked on ''%s'': [%0.1f, %0.1f] ****\n', paramName, p(1), p(2));
        paramNameClicked = paramName;
    else
        % fprintf('Param ''%s'' position: [%0.1f, %0.1f]\n', paramName, p(1), p(2));
    end
end
if isempty(paramNameClicked)
    return;
end
clipboard('copy',paramNameClicked)
msg = sprintf('''%s''   copied to clipboard',paramNameClicked);
try
    MessageBox(msg, sprintf('Parameter: ''%s''', paramNameClicked), 'timelimit');
catch
    msgbox(msg);
end

% -------------------------------------------------------------
function hcm = setMouseClickAction(hcm, hp)
if nargin<2
    hcm = uicontextmenu();
    uimenu(hcm, 'text','Copy Param Name');
    return
end
hm = get(hcm, 'children');
hm.MenuSelectedFcn = {@mouseClickFcn_Callback,hp};


text:
%% TENSOR t-SVD and inverse_t-svd
close all; clear all; clc;

%% LIBRARIES
addpath('libs/poblano_toolbox_1.1');
addpath('libs/tensor_toolbox_2.5');
addpath('libs/nway331');

%% LOAD DATASET
load('dataset/trafficdb/traffic_patches.mat');
A = double(imgdb{100});

%% Tensor t-SVD decomposition
[U,S,V] = tensor_t_svd(A);
% for k = 1:size(S,3)
%   Slr = zeros(size(S(:,:,k)));
%   for s = 1:48
%     Slr(s,s) = 1;
%   end
%   S(:,:,k) = S(:,:,k) .* Slr;
% end
[C] = tensor_product(U,S);
[A_hat] = tensor_product(C,tensor_transpose(V));

%% ERROR
norm(tensor(A)-tensor(A_hat))

%% SHOW RESULTS
show_3dtensors(A,A_hat);

author: andrewssobral

repo: mtt

save_path: github-repos/MATLAB/andrewssobral-mtt


text:
function check_accept_value(type,value,cls) %#ok<INUSD>
% Internal function for GUI parameter assignment checking.

if isstruct(type)
    type = PropertyType(type.PrimitiveType,type.Shape,type.Domain); end

assert(type.CanAccept(value), ...
    'PropertyGridField:InvalidArgumentValue', ...
    'This value does not conform to property type restrictions.');

repo: REST


text:
%% Project: 1-D Finite Difference Method
%
% The purpose of this project is to introduce the finite difference. We use
% 1-D Poisson equation in (0,1) with Dirichlet boundary condition
%
% $$ - u'' = f \, (0,1), \quad u(0) = a, u(1) = b. $$

%% Step 1: Generate a grid
%
% Generate a vector representing a uniform grid with size h of (0,1).
N = 10;
x = linspace(0,1,N);
plot(x,0,'b.','Markersize',16)

%% Step 2: Generate a matrix equation
%
% Based on the grid, the function $u$ is discretized by a vector |u|. The
% derivative $u', u''$ are approximated by centeral finite difference:
%
% $$ u'(x_i) \approx \frac{u(i+1) - u(i-1)}{2h} $$
%
% $$ u''(x_i) \approx \frac{u(i-1) - 2*u(i) + u(i-1)}{h^2} $$
%
% The equation $-u''(x) = f(x)$ is discretized at $x_i, i=1,...,N$ as
%
% $$ \frac{-u(i-1) + 2*u(i) - u(i-1)}{h^2} \quad = f(i) $$
%
% where $f(i) = f(x_i)$. These linear equations can be written as a matrix
% equation |A*u = f|, where |A| is a tri-diagonal matrix |(-1,2,-1)/h^2|.
n = 5;
e = ones(n,1);
A = spdiags([e -2*e e], -1:1, n, n);
display(full(A));
%%
% We use spdiags to speed up the generation of the matrix. If using diag,
% ....

%% Stpe 3: Modify the matrix and right hand side to impose boundary condition
%
% The discretization fails at boundary vertices since no nodes outside the
% interval. Howevery the boundary value is given by the problem: |u(1) = a,
% u(N) = b|.
%
% These two equations can be included in the matrix by changing |A(1,:) =
% [1, 0 ..., 0] and A(:,N) = [0, 0, ..., 1] and |f(1) = a/h^2, f(N) =
% b/h^2|.
A(1,1) = 1;
A(1,2) = 0;
A(n,n) = 1;
A(n,n-1) = 0;
display(full(A));

%% Step 4: Test of code
[u,x] = poisson1D(0,1,5);
plot(x,sin(x),x,u,'r*');
legend('exact solution','approximate solution')
%%
% We test ... The result seems correct since the computed solution fits
% well on the curve of the true solution.

%% Step 5: Check the Convergence Rate
err = zeros(4,1);
h = zeros(4,1);
for k = 1:4
    [u,x] = poisson1D(0,1,2^k+1);
    uI = sin(x);
    err(k) = max(abs(u-uI));
    h(k) = 1/2^k;
end
display(err)
loglog(h,err,h,h.^2);
legend('error','h^2');
axis tight;
%%
% Since these two lines have the same lope, the err decays like h^2.

repo: Aero-matlab


text:
function desc = calAvghsv(im, seg, segnum)
end

author: kittenish

repo: Image-Shadow-Detection-and-Removal


text:
classdef TestMergeDebevec
    %TestMergeDebevec

    methods (Static)
        function test_1
            N = 3; % use first N images only
            fpath = fullfile(mexopencv.root(),'test');
            files = dir(fullfile(fpath,'memorial*.png'));
            files = files(1:N);
            imgs = cell(1,numel(files));
            for i=1:numel(files)
                imgs{i} = cv.imread(fullfile(fpath,files(i).name), 'ReduceScale',2);
            end
            etimes = 2.^(5:-1:-10);
            etimes = etimes(1:N);
            assert(numel(imgs) == numel(etimes));

            obj = cv.MergeDebevec();
            hdr = obj.process(imgs, etimes);
            validateattributes(hdr, {'single'}, ...
                {'size',size(imgs{1}), 'nonnegative'});

            calibrate = cv.CalibrateDebevec();
            response = calibrate.process(imgs, etimes);
            hdr = obj.process(imgs, etimes, response);
            validateattributes(hdr, {'single'}, ...
                {'size',size(imgs{1}), 'nonnegative'});
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function [ a, b ] = p06_lim ( )

%*****************************************************************************80
%
%% P06_LIM returns the integration limits for problem 6.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real A, B, the limits of integration.
%
  a = -1.0;
  b = 1.0;

  return
end


text:
%
% Clear tiny coefficients, tiny real parts, and tiny imaginary parts
% from a polynomial or a cell array of polynomials
%
% Syntax:  (pclear is the shortened alias of PolynomialClear)
%          >> g = PolynomialClear(f)
%          >> g = PolynomialClear(f,tol)
%
%   Input:   f --- (string/numeric/cell array) polynomial (array)
%          tol --- (numeric, optional)         threshold for being tiny
%
%  Output:   g --- (string/numeric/cell array) cleared polynomial (array)
%
%  Example:
%
%   >> PolynomialClear('(3+2e-13*i) + 2.1e-15*x*y+(1e-14+2*i)*x^3',1e-10)
%
%   ans =
%
%   3 + (0+2i)*x^3

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
function z = minus( x, y )
    %MINUS Substraction of two TT/MPS tensors.
    %   Z = MINUS(X,Y) substracts two TT/MPS tensors. The rank of the resulting
    %   tensor is the sum of the individual ranks.
    %
    %   See also PLUS, UMINUS.

    %   TTeMPS Toolbox.
    %   Michael Steinlechner, 2013-2016
    %   Questions and contact: michael.steinlechner@epfl.ch
    %   BSD 2-clause license, see LICENSE.txt

    z = plus(x, uminus(y));

end

author: NicolasBoumal

repo: manopt


text:
function TS_Init(INP_ts,whatFeatureSet,beVocal,outputFile)
% TS_Init  Produces a formatted HCTSA .mat file from input files
%
% This function is used instead to run hctsa analysis without a linked mySQL database.
%
%---EXAMPLE USAGE:
% Initiate an HCTSA.mat file on a custom time-series dataset using the hctsa
% feature library, using a formatted input file, 'my_TS_INP_file.mat'
% >> TS_Init('my_TS_INP_file.mat','hctsa');
%
%---INPUTS:
% INP_ts: A time-series input file
% whatFeatureSet: EITHER a feature-set name (like 'hctsa' or 'catch22')
%             OR a 1x2 cell of filenames for INP_mops (master operations input file)
%                   and INP_ops (an operations input file)
% beVocal: Whether to display details of the progress of the script to screen.
%           a 3-vector, specifying for 1. time series, 2. master operations,
%           and 3. operations.
% outputFile: Specify an output filename
%
%---OUTPUTS:
% Writes output to HCTSA.mat (or specified custom filename: outputFile)

% ------------------------------------------------------------------------------
% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This work is licensed under the Creative Commons
% Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of
% this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or send
% a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View,
% California, 94041, USA.
% ------------------------------------------------------------------------------

% ------------------------------------------------------------------------------
% Check Inputs:
% ------------------------------------------------------------------------------
if nargin < 1 || isempty(INP_ts)
    error('Please supply a formatted time-series input file (see documentation for details).');
end
if nargin < 2
    whatFeatureSet = 'hctsa';
end
if nargin < 3
    if iscell(whatFeatureSet)
        beVocal = [true,true,true]; % Provided all custom input files--walks you through all of them
    else
        beVocal = [true,false,false]; % by default helps you just for the time series input file you provided
    end
end
if length(beVocal)==1
    beVocal = repmat(beVocal,1,3);
end
if nargin < 4
    outputFile = 'HCTSA.mat';
end

% ------------------------------------------------------------------------------
% First check if you're about to overwrite an existing file
% ------------------------------------------------------------------------------
if exist(['./',outputFile],'file')
    reply = input(sprintf(['Warning: %s already exists -- if you continue, this ' ...
        'file will be overwritten.\n[press ''y'' to continue] '],outputFile),'s');
    if ~strcmp(reply,'y')
        return
    end
end

%-------------------------------------------------------------------------------
% Convert a feature-set name to a set of input files
%-------------------------------------------------------------------------------
if ischar(whatFeatureSet)
    [INP_mops,INP_ops] = TS_GiveMeInputFiles(whatFeatureSet);
elseif iscell(whatFeatureSet)
    INP_mops = whatFeatureSet{1};
    fprintf(1,'Information about master operations taken from ''%s''\n',INP_mops);
    INP_ops = whatFeatureSet{2};
    fprintf(1,'Information about operations taken from ''%s''\n',INP_ops);
else
    error('Unknown format for setting the feature set')
end

%-------------------------------------------------------------------------------
% First check that all input files provided exist:
%-------------------------------------------------------------------------------
checkFiles = {INP_ts,INP_mops,INP_ops};
for i = 1:3
    if ~exist(checkFiles{i},'file')
        error('Unknown file: ''%s''',checkFiles{i});
    end
end

% ------------------------------------------------------------------------------
% Get time series, operations, master operations into structure arrays
% ------------------------------------------------------------------------------
TimeSeries = SQL_Add('ts',INP_ts,false,beVocal(1));
numTS = height(TimeSeries);
if numTS==0
    return; % The user did not approve of the set of inputs
end

MasterOperations = SQL_Add('mops',INP_mops,false,beVocal(2));
numMops = height(MasterOperations);
if numMops==0
    return; % The user did not approve of the set of inputs
end

Operations = SQL_Add('ops',INP_ops,false,beVocal(3));
numOps = height(Operations);
if numOps==0
    return; % The user did not approve of the set of inputs
end

%-------------------------------------------------------------------------------
% Link operations to their masters using label matching
% and update the structure arrays using the TS_LinkOperationsWithMasters function
%-------------------------------------------------------------------------------
[Operations,MasterOperations] = TS_LinkOperationsWithMasters(Operations,MasterOperations);
% MasterOperations may have been trimmed by TS_LinkOperationsWithMasters:
numMops = height(MasterOperations);

% ------------------------------------------------------------------------------
% Generate the TS_DataMat, TS_Quality, and TS_CalcTime matrices
% ------------------------------------------------------------------------------
% All NaNs -> NULL (haven't yet been calculated)
TS_DataMat = nan(numTS,numOps);
TS_Quality = nan(numTS,numOps);
TS_CalcTime = nan(numTS,numOps);

%-------------------------------------------------------------------------------
% Get git information to keep track of the version of code used at the time of TS_Init
%-------------------------------------------------------------------------------
gitInfo = TS_AddGitInfo();

% ------------------------------------------------------------------------------
% Save to file
% ------------------------------------------------------------------------------
% Set a flag, fromDatabase, that tells you that you that this was generated by
% TS_Init and shouldn't be written back to a database
fromDatabase = false;
save(outputFile,'TimeSeries','Operations','MasterOperations',...
            'TS_DataMat','TS_Quality','TS_CalcTime','fromDatabase','gitInfo','-v7.3');

fprintf(1,'Successfully initialized file ''%s'' with %u time series, %u master operations, and %u operations.\n',...
                        outputFile,numTS,numMops,numOps);

end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function y = any(x)

% ANY    True if any element of a vector is a nonzero number or is
%    logical 1 (TRUE).  ANY ignores entries that are NaN (Not a Number).
%
%    For vectors, ANY(V) returns logical 1 (TRUE) if any of the
%    elements of the vector is a nonzero number or is logical 1 (TRUE).
%    Otherwise it returns logical 0 (FALSE).  For matrices, ANY(X)
%    operates on the columns of X, returning a row vector of logical 1's
%    and 0's.

if nargin>1
  error('this implementation is only supported with one input argument');
end

siz = size(x);
if numel(siz)>2
  error('this implementation is only supported with vector or matrix input');
end

if siz(1)==1 || siz(2)==1
  y = false;
  for i=1:prod(siz)
    if x(i)
      y = true;
      break
    end
  end

else
  y = false(1,siz(2));
  for j=1:siz(2)
    for i=1:siz(1)
      if x(i,j)
        y(1,j) = true;
        break
      end
    end
  end

end

author: PatternRecognition

repo: OpenBMI