text:
function [a,b,c,d]=getplanefrom3pt(plane)
%
% [a,b,c,d]=getplanefrom3pt(plane)
%
% define a plane equation ax+by+cz+d=0 from three 3D points
%
% author: Qianqian Fang, <q.fang at neu.edu>
%
% input:
%    plane: a 3x3 matrix with each row specifying a 3D point (x,y,z)
%
% output:
%    a,b,c,d: the coefficient for plane equation ax+by+cz+d=0
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

x=plane(:,1);
y=plane(:,2);
z=plane(:,3);

% compute the plane equation a*x + b*y +c*z +d=0

a=y(1)*(z(2)-z(3))+y(2)*(z(3)-z(1))+y(3)*(z(1)-z(2));
b=z(1)*(x(2)-x(3))+z(2)*(x(3)-x(1))+z(3)*(x(1)-x(2));
c=x(1)*(y(2)-y(3))+x(2)*(y(3)-y(1))+x(3)*(y(1)-y(2));
d=-det(plane);

author: fieldtrip


text:
function [val] = filetype_check_extension(filename, ext)

% FILETYPE_CHECK_EXTENSION helper function to determine the file type
% by performing a case insensitive string comparison of the extension.

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

% these are for speeding up subsequent calls with the same input arguments
persistent previous_argin previous_argout

current_argin = {filename, ext};
if isequal(current_argin, previous_argin)
  % don't do the detection again, but return the previous value from cache
  val = previous_argout;
  return
end

if iscell(filename)
  % compare the extension of multiple files
  val = zeros(size(filename));
  for i=1:length(filename)
    val(i) = filetype_check_extension(filename{i}, ext);
  end
elseif iscell(ext)
  val = zeros(size(ext));
  for i=1:length(ext)
    val(i) = filetype_check_extension(filename, ext{i});
  end
else
  % compare the extension of a single file
  if numel(filename)<numel(ext)
    val = false;
  else
    val = strcmpi(filename((end-length(ext)+1):end), ext);
  end
end

% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout  = val;
previous_argin  = current_argin;
previous_argout = current_argout;

return % main()

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function varargout = printsize(varargin)
% VL_PRINTSIZE  Set the printing size of a figure
%   VL_PRINTSIZE(R) adjusts the PaperPosition property of the current
%   figure to make the figure paper width equal to R times the width
%   of a 'uslsetter' page, while preserving the aspect ratio of the
%   figure. Then, it sets the PaperSize property to match tightly the
%   size of the figure.
%
%   VL_PRINTSIZE(FIG,R) operates on the specified figure FIG. The
%   function accepts the following optional arguments:
%
%   AspectRatio:: []
%     Change the figure aspect ratio (width/height) to the specified
%     value.
%
%   Reference:: 'horizontal'
%     If set to 'horizontal', VL_PRINTSIZE(R) makes the width of the
%     figure equal to a fraction R of the width of the page. If set to
%     'vertical', the height is used instead.
%
%   PaperType:: 'usletter'
%     Set the type of the reference page to the specified type. Any of
%     the paper types supported by MATLAB can be used (see
%     PRINT()).
%
%   Margin:: 0
%     If greater than zero, VL_PRINTSIZE(R) leaves the specified
%     margin around the figure rather than fitting the paper size
%     tightly around it. The margin is expressed as a fraction of the
%     figure paper width (or height if Reference is set to
%     'vertical').
%
%   PRINTING FIGURES IN MATLAB
%
%   The standard procedure to include a MATLAB figure in a publication
%   consists in printing the figure to an EPS or PDF file (by using
%   the PRINT() function) and then rescaling it to the desired size in
%   the publication. PDF printing has the additional inconvenience
%   that large white margins are generated, and requires cropping the
%   figure too.
%
%   Unfortunately, rescalign a figure in this manner has the usually
%   unwanted effect of rescaling elements of the graphics such as font
%   sizes and line thicknesses. For example, a font which is 12pt in
%   the original MATLAB figure may become too large or too small after
%   rescaling.
%
%   The `proper' way of printing a figure is to specify its desired
%   size on paper before calling the PRINT() function. VL_PRINTSIZE()
%   helps doing so.
%
%   Margins are an additional nuances. When printing to certain
%   formats such as PDF, MATLAB prints in fact entire page (e.g. a
%   whole US Letter sheet), resulting in wide white margin all around
%   the figure. VL_PRINTSIZE() alleviates this problem by setting the
%   paper size to match the figure size tightly. This does not
%   eliminate margins completely, especially if the figure has
%   multiple subplots, but it is certainly a large improvement.
%
%   See also: VL_HELP().
[varargout{1:nargout}] = vl_printsize(varargin{:});

author: yihui-he

repo: panorama

save_path: github-repos/MATLAB/yihui-he-panorama


text:
function out = ICC(cse,typ,dat)
% Function to work out ICCs according to shrout & fleiss' schema (Shrout PE,
% Fleiss JL. Intraclass correlations: uses in assessing rater reliability.
% Psychol Bull. 1979;86:420-428).
%
% :Usage:
% ::
%
%     iccvalue = ICC([1 to 6],['single' or 'k'], data matrix)
%
% :Inputs:
%
%   **'dat':**
%        is data whose *columns* represent k different raters (judges) & whose
%        *rows* represent n different cases or targets being measured. Each target
%        is assumed to be a random sample from a population of targets.
%
%   **'cse':**
%        is either 1,2,3. 'cse' is: 1 if each target is measured by a
%        different set of raters from a population of raters, 2 if each target is
%        measured by the same raters, but that these raters are sampled from a
%        population of raters, 3 if each target is measured by the same raters and
%        these raters are the only raters of interest.
%
%   **'typ':**
%        is either 'single' or 'k' & denotes whether the ICC is based on a
%        single measurement or on an average of k measurements, where k = the
%        number of ratings/raters.
%
% This has been tested using the example data in the paper by shrout & fleiss.
%
% Example: out = ICC(3,'k',S_Fdata)
% returns ICC(3,k) of data 'S_Fdata' to double 'out'.
%
% Kevin Brownhill, Imaging Sciences, KCL, London kevin.brownhill@kcl.ac.uk
%
% :Additional documentation:
%
% iccvalue = ICC([1 to 6],['single' or 'k'], data matrix)
%
% Here, columns are 'judges', or more generally, 'measures' that are
% usually ideally intercorrelated.  Rows are items being assessed.
% The ICC assesses the proportion of variance attributed to the items,
%  shared across measures.
% As the correlation between the measures grows, the icc grows.
% Another way of saying this is that if the rows are consistently different
% across measures, the icc will be high.
%
% Think of rows as criminals, and columns as judges. The data values are 'guilt scores',
% where higher is more guilty.  If all the judges agree, the most guilty
% cases will be rated as most guilty by all judges, and the icc will be
% high. This is actually consistent with Case 2 or 3 in Shrout and Fleiss.
%
% In Case 1, the columns don't have any real meaning, as there are
% different 'judges' for each row, and variance components due to judge
% cannot be separated from error and the judge x target interaction.
% In Case 2 and 3, they are crossed. Case 2 treats judge as a random
% effect, whereas Case 3 treats judge as a fixed effect.
%
% If the data were an individual differences study of cognitive performance,
% then the rows would be subjects, and the columns would be tests.
% A high icc would indicate a high correlation across the tests, which
% indicates that subjects are reliably different from one another, i.e.,
% that a large proportion of the total variance is related to subject.
% In such a case, as tests are fixed entities, then Case 3 might be
% appropriate.
%
% Cronbach's alpha is equal to ICC(3, k) - case 3, k
% This assumes no target x rater interaction
%
% :Examples:
% ::
%
%    dat = mvnrnd([1 1 1], [1 .5 .5; .5 1 .5; .5 .5 1], 50); whos dat
%    corrcoef(dat)
%    ri = ICC(2, 'k', dat)
%    dat = mvnrnd([1 1 1], [1 .9 .9; .9 1 .9; .9 .9 1], 50); whos dat
%    corrcoef(dat)
%    ri = ICC(2, 'k', dat)
%
% In the example below, judges (measures) have systematically different
% means, and the ICC values are different.  ICC(1, 1) is low because judge
% is not considered as a source of variance.  ICC(2, 1) is higher, but
% intermediate, because judge is considered as a random effect and modeled,
% but we want to generalize to new judges.  ICC(3, 1) is highest, because
% judge is modeled
%    dat = mvnrnd([1 2 3], [1 .5 .5; .5 1 .5; .5 .5 1], 50); whos dat
%    ri = ICC(1, 'single', dat)
%    ri = ICC(2, 'single', dat)
%    ri = ICC(3, 'single', dat)
%
% ..
%    Modified 10/09 by Tor Wager; minor bug fix and changes to documentation
% ..

%number of raters/ratings
k = size(dat,2);
%number of targets
n = size(dat,1);
%mean per target
mpt = mean(dat,2);
%mean per rater/rating
mpr = mean(dat);
%get total mean
tm = mean(mpt);
%within target sum sqrs
WSS = sum(sum(bsxfun(@minus,dat,mpt).^2));
%within target mean sqrs
WMS = WSS / (n * (k - 1));
%between rater sum sqrs
RSS = sum((mpr - tm).^2) * n;
%between rater mean sqrs
RMS = RSS / (k - 1);
% %get total sum sqrs
% TSS = sum(sum((dat - tm).^2));
%between target sum sqrs
BSS = sum((mpt - tm).^2) * k;
%between targets mean squares
BMS = BSS / (n - 1);
%residual sum of squares
ESS = WSS - RSS;
%residual mean sqrs
EMS = ESS / ((k - 1) * (n - 1));
switch cse
    case 1
        switch typ
            case 'single'
                out = (BMS - WMS) / (BMS + (k - 1) * WMS);
            case 'k'
                out = (BMS - WMS) / BMS;
            otherwise
               error('Wrong value for input typ')
        end
    case 2
        switch typ
            case 'single'
                out = (BMS - EMS) / (BMS + (k - 1) * EMS + k * (RMS - EMS) / n);
            case 'k'
                out = (BMS - EMS) / (BMS + (RMS - EMS) / n);
            otherwise
               error('Wrong value for input typ')
        end
    case 3
        switch typ
            case 'single'
                out = (BMS - EMS) / (BMS + (k - 1) * EMS);
            case 'k'
                out = (BMS - EMS) / BMS;
            otherwise
               error('Wrong value for input typ')
        end
    otherwise
        error('Wrong value for input cse')
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function z = polyval2(p,x,y)
% POLYVAL2
% ---------
%
% Evaluate a 2D polynomial
% By SS Rogers (2006)
%
% Usage
% ------
% Z = POLYVAL2(P,X,Y) returns the value of a 2D polynomial P evaluated at (X,Y). P
% is a vector of length (N+1)*(N+2)/2 containing the polynomial coefficients in
% ascending powers:
%
%   P = [p00 p10 p01 p20 p11 p02 p30 p21 p12 p03...]
%
% e.g. For a 3rd order fit, polyval2.m evaluates the matrix equation:
%
%    Z = V*P    or
%
%                   2      2  3  2      2   3
%    Z = [1  x  y  x  xy  y  x  x y  x y   y ]  [p00
%                                                p10
%                                                p01
%                                                p20
%                                                p11
%                                                p02
%                                                p30
%                                                p21
%                                                p12
%                                                p03]
%
% *Note:* P is not in the format of standard Matlab 1D polynomials.
%
% X and Y should be vectors; the polynomial is evaluated at all
% points (X,Y).
%
% Class support for inputs P,X,Y:
%    float: double, single

x=x(:);
y=y(:);
lx=length(x);
ly=length(y);
lp=length(p);
pts=lx*ly;

y=y*ones(1,lx);
x=ones(ly,1)*x';
x = x(:);
y = y(:);

n=(sqrt(1+8*length(p))-3)/2;
% Check input is a vector
if ~(isvector(p) || mod(n,1)==0 || lx==ly)
    error('MATLAB:polyval2:InvalidP',...
            'P must be a vector of length (N+1)*(N+2)/2, where N is order. X and Y must be same size.');
end

% Construct weighted Vandermonde matrix.
V=zeros(pts,lp);
V(:,1) = ones(pts,1);
ordercolumn=1;
for order = 1:n
    for ordercolumn=ordercolumn+(1:order)
        V(:,ordercolumn) = x.*V(:,ordercolumn-order);
    end
    ordercolumn=ordercolumn+1;
    V(:,ordercolumn) = y.*V(:,ordercolumn-order-1);
end

z=V*p';
z=reshape(z,ly,lx);

author: Sable

repo: mcbench-benchmarks


text:
function [ n_data, mu, sigma, x, fx ] = cauchy_cdf_values ( n_data )

%*****************************************************************************80
%
%% CAUCHY_CDF_VALUES returns some values of the Cauchy CDF.
%
%  Discussion:
%
%    In Mathematica, the function can be evaluated by:
%
%      Needs["Statistics`ContinuousDistributions`"]
%      dist = CauchyDistribution [ mu, sigma ]
%      CDF [ dist, x ]
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Milton Abramowitz and Irene Stegun,
%    Handbook of Mathematical Functions,
%    US Department of Commerce, 1964.
%
%    Stephen Wolfram,
%    The Mathematica Book,
%    Fourth Edition,
%    Wolfram Media / Cambridge University Press, 1999.
%
%  Parameters:
%
%    Input/output, integer N_DATA.  The user sets N_DATA to 0 before the
%    first call.  On each call, the routine increments N_DATA by 1, and
%    returns the corresponding data; when there is no more data, the
%    output value of N_DATA will be 0 again.
%
%    Output, real MU, the mean of the distribution.
%
%    Output, real SIGMA, the variance of the distribution.
%
%    Output, real X, the argument of the function.
%
%    Output, real FX, the value of the function.
%
  n_max = 12;

  fx_vec = [ ...
     0.5000000000000000E+00, ...
     0.8524163823495667E+00, ...
     0.9220208696226307E+00, ...
     0.9474315432887466E+00, ...
     0.6475836176504333E+00, ...
     0.6024163823495667E+00, ...
     0.5779791303773693E+00, ...
     0.5628329581890012E+00, ...
     0.6475836176504333E+00, ...
     0.5000000000000000E+00, ...
     0.3524163823495667E+00, ...
     0.2500000000000000E+00 ];

  mu_vec = [ ...
     0.1000000000000000E+01, ...
     0.1000000000000000E+01, ...
     0.1000000000000000E+01, ...
     0.1000000000000000E+01, ...
     0.1000000000000000E+01, ...
     0.1000000000000000E+01, ...
     0.1000000000000000E+01, ...
     0.1000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.3000000000000000E+01, ...
     0.4000000000000000E+01, ...
     0.5000000000000000E+01 ];

  sigma_vec = [ ...
     0.5000000000000000E+00, ...
     0.5000000000000000E+00, ...
     0.5000000000000000E+00, ...
     0.5000000000000000E+00, ...
     0.2000000000000000E+01, ...
     0.3000000000000000E+01, ...
     0.4000000000000000E+01, ...
     0.5000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.2000000000000000E+01 ];

  x_vec = [ ...
     0.1000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.3000000000000000E+01, ...
     0.4000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.2000000000000000E+01, ...
     0.3000000000000000E+01, ...
     0.3000000000000000E+01, ...
     0.3000000000000000E+01, ...
     0.3000000000000000E+01 ];

  if ( n_data < 0 )
    n_data = 0;
  end

  n_data = n_data + 1;

  if ( n_max < n_data )
    n_data = 0;
    mu = 0.0;
    sigma = 0.0;
    x = 0.0;
    fx = 0.0;
  else
    mu = mu_vec(n_data);
    sigma = sigma_vec(n_data);
    x = x_vec(n_data);
    fx = fx_vec(n_data);
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
classdef RVEAiGNG < ALGORITHM
% <multi/many> <real/integer/label/binary/permutation>
% RVEA based on improved growing neural gas
% alpha --- 2 --- The parameter controlling the rate of change of penalty

%------------------------------- Reference --------------------------------
% Q. Liu, Y. Jin, M. Heiderich, T. Rodemann, and G. Yu, An adaptive
% reference vector-guided evolutionary algorithm using growing neural gas
% for many-objective optimization of irregular problems, IEEE Transactions
% on Cybernetics, 2022, 52(5): 2698-2711.
%--------------------------------------------------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

% This function is written by Qiqi Liu

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            params.N = Problem.N;
            params.MaxIt = 50;
            params.L = 50;
            params.epsilon_b = 0.2;
            params.epsilon_n = 0.006;
            params.alpha = 0.5;
            params.delta = 0.995;
            params.T = 50;

            %% Parameter setting
            alpha = Algorithm.ParameterSet(2);
            [V,Problem.N] = UniformPoint(Problem.N,Problem.M);
            Population    = Problem.Initialization();
            net = InitilizeGrowingGasNet(V,Population,params);
            Archive = UpdateArchive(Population,[],Problem.N);
            scale = ones(1,Problem.M);
            zmin = min(Population.objs,[],1);
            genFlag = [];

            while Algorithm.NotTerminated(Population)
                MatingPool = randi(length(Population),1,Problem.N);
                Offspring  = OperatorGA(Problem,Population(MatingPool));
                zmin       = min([zmin;Offspring.objs],[],1);
                [Population,net,V,Archive,scale,genFlag] = EnvironmentalSelection([Population,Offspring],V,(Problem.FE/Problem.maxFE)^alpha,net,params,Archive,Problem,scale,zmin,genFlag);
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function [matVar] = jsonRead(inputVar,varargin)
	% Decode a json string.
	% Biafra Ahanonu
	% started: 2020.06.09 [12:19:01]
	% inputs
		% inputVar - JSON string or path to a HDF5 file containing dataset that is a JSON string.
	% outputs
		%

	% changelog
		% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
        % 2022.01.25 [15:52:31] - Edge case where the end of the imported string is a space, causing jsondecode to fail.
	% TODO
		%

	import ciapkg.api.* % import CIAtah functions in ciapkg package API.

	%========================
	% Str: hierarchy name in hdf5 where JSON data is located.
	options.inputDatasetName = '/movie/preprocessingSettingsAll';
	% get options
	options = getOptions(options,varargin);
	% display(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	%========================

	try
		if ischar(inputVar)
			% Determine if it is a file
			if exist(inputVar,'file')==2
				% Read in the JSON string
				inputVar = h5read(inputVar,options.inputDatasetName);
				if iscell(inputVar)
					inputVar = inputVar{1};
				end
				try
					jsondecode(inputVar);
                catch
                    % Edge case where the end of the imported string is a space, causing jsondecode to fail.
                    inputVar = char(inputVar);
					inputVar = inputVar(1:end-1);
				end
				if ~ischar(inputVar)
					fprintf('HDF5 dataset %s does NOT contain a json string.\n',options.inputDatasetName);
				end
			else
			end

			% Encode the input variable as a JSON string
			matVar = jsondecode(inputVar);
		end

		if nargout==0
			disp(matVar)
		end

	catch err
		disp(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		disp(repmat('@',1,7))
	end
end
function [jsonStr] = subfxnHumanReadable(jsonStr)
	% Make human readable
	jsonStr = strrep(jsonStr, ',', sprintf(',\r'));
	jsonStr = strrep(jsonStr, '[{', sprintf('[\r{\r'));
	jsonStr = strrep(jsonStr, '}]', sprintf('\r}\r]'));
end

author: bahanonu

repo: ciatah

save_path: github-repos/MATLAB/bahanonu-ciatah


text:
function ExecFlag=DoGradChk

global VSeq
global VCtl

ExecFlag = 1;
GradTolerance = abs(VCtl.MaxGrad * 0.005);
SRTolerance = abs(VCtl.MaxSlewRate * 0.005);
% check Gz
Flags = VSeq.flagsLine(2,:);
t = VSeq.tsLine(Flags~=0);
dt =  diff(t);
dG =  diff(VSeq.GzAmpLine);

SlewRate = dG./dt;

if ~isempty(find((abs(SlewRate)-VCtl.MaxSlewRate)>SRTolerance, 1))

    disp(['GzSS Max SlewRate ' num2str(max(abs(SlewRate)))]);

    errordlg('GzSS exceeds maximum allowed gradient slew rate!');
    ExecFlag = 0;
end

if ~isempty(find((abs(VSeq.GzAmpLine)-VCtl.MaxGrad)>GradTolerance, 1))

    disp(['GzSS Max Gradient ' num2str(max(abs(VSeq.GzAmpLine)))]);

    errordlg('GzSS exceeds maximum allowed gradient amplitude!');
    ExecFlag = 0;
end

% check Gy
Flags = VSeq.flagsLine(3,:);
t = VSeq.tsLine(Flags~=0);
dt =  diff(t);
dG =  diff(VSeq.GyAmpLine);

SlewRate = dG./dt;

if ~isempty(find((abs(SlewRate)-VCtl.MaxSlewRate)>SRTolerance, 1))

    disp(['GyP Max SlewRate ' num2str(max(abs(SlewRate)))]);

    errordlg('GyP exceeds maximum allowed gradient slew rate!');
    ExecFlag = 0;
end

if ~isempty(find((abs(VSeq.GyAmpLine)-VCtl.MaxGrad)>GradTolerance, 1))

    disp(['GyP Max Gradient ' num2str(max(abs(VSeq.GyAmpLine)))]);

    errordlg('GyP exceeds maximum allowed gradient amplitude!');
    ExecFlag = 0;
end

% check Gx
Flags = VSeq.flagsLine(4,:);
t = VSeq.tsLine(Flags~=0);
dt =  diff(t);
dG =  diff(VSeq.GxAmpLine);

SlewRate = dG./dt;

if ~isempty(find((abs(SlewRate)-VCtl.MaxSlewRate)>SRTolerance, 1))

    disp(['GxR Max SlewRate ' num2str(max(abs(SlewRate)))]);

    errordlg('GxR exceeds maximum allowed gradient slew rate!');
    ExecFlag = 0;

end

if ~isempty(find((abs(VSeq.GxAmpLine)-VCtl.MaxGrad)>GradTolerance, 1))

    disp(['GxR Max Gradient ' num2str(max(abs(VSeq.GxAmpLine)))]);

    errordlg('GxR exceeds maximum allowed gradient amplitude!');
    ExecFlag = 0;
end

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function [sumRes, resJ, H]=fobj_rician_fix(x, meas, protocol, model, sig, constants, fix, x0)
% Wrapper for fobj_rician for use with fmincon_fix.
%
% x is the encoded model parameter values
%
% meas is the measurements
%
% protocol is the measurement protocol
%
% model is a string encoding the model
%
% sig is the standard deviation of the Gaussian distributions underlying
% the Rician noise
%
% constants contains values required to compute the model signals.
%
% fix is a binary array specifying which parameters are fixed and which
% vary.
%
% x0 is the full starting point including the fixed parameters.
%
% author: Daniel C Alexander (d.alexander@ucl.ac.uk)
%

% Construct the full parameter list including fixed values.
xf = fix.*x0;
xf(find(fix==0)) = x;

% Now call the full objective function.
if(nargout == 1)
    sumRes = fobj_rician(xf, meas, protocol, model, sig, constants);
elseif(nargout == 2)
    [sumRes resJ] = fobj_rician(xf, meas, protocol, model, sig, constants);
else
    [sumRes, resJ, H] = fobj_rician(xf, meas, protocol, model, sig, constants);
end

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function res = project_t(pts, H)
%% apply projective transformation H on points pts
%% pts, n x 2
%% H, 3 x 3
%% res, n x 2

pts = [pts, ones(size(pts, 1), 1)];
res = H * pts';
res = [ res(1,:)./res(3,:); res(2,:)./res(3,:) ];
res = res';

author: flyers

repo: drone-tracking


text:
function [C, sigma] = dataset3Params(X, y, Xval, yval)
%DATASET3PARAMS returns your choice of C and sigma for Part 3 of the exercise
%where you select the optimal (C, sigma) learning parameters to use for SVM
%with RBF kernel
%   [C, sigma] = DATASET3PARAMS(X, y, Xval, yval) returns your choice of C and
%   sigma. You should complete this function to return the optimal C and
%   sigma based on a cross-validation set.
%

% You need to return the following variables correctly.
C = 1;
sigma = 0.3;

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return the optimal C and sigma
%               learning parameters found using the cross validation set.
%               You can use svmPredict to predict the labels on the cross
%               validation set. For example,
%                   predictions = svmPredict(model, Xval);
%               will return the predictions on the cross validation set.
%
%  Note: You can compute the prediction error using
%        mean(double(predictions ~= yval))
%

C_s = [0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30];
sigma_s = C_s ;
l = length(C_s);
scores = zeros(l);
for i = 1:l
    for j = 1:l
        C = C_s(i);
        sigma = sigma_s(j);
        model= svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma));
        predictions = svmPredict(model, Xval);
        scores(i, j) = mean(double(predictions ~= yval));
    end
end

s = scores;
[~, j] = min(min(s));
[~, temp] = min(s);
i = temp(j);
C = C_s(i);
sigma = sigma_s(j);
% =========================================================================

end

repo: machine-learning


text:
function l = dim2deg(dim)
% dimension to harmonic degree of Wiegner D functions

l = 0;
while deg2dim(l+2) <= dim, l = l + 1;end

author: mtex-toolbox

repo: mtex

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


text:
%function lines%
%function letter_in_a_line
function [fl re space]=letter_crop(im_texto)
% Divide letters in lines

im_texto=clip(im_texto);
num_filas=size(im_texto,2);

%figure,imshow(im_texto);
%title('line sent in the function letter');
for s=1:num_filas
    s;
    sum_col = sum(im_texto(:,s));
    if sum_col==0
        k = 'true';
        nm=im_texto(:,1:s-1); % First letter matrix
        %figure,imshow(nm);
        %title('first letter in the function letter_in_a_line');
        %pause(1);
        rm=im_texto(:,s:end);% Remaining line matrix
        %figure,imshow(rm);
        %title('remaining letters in the function letter_in_a_line');
        %pause(1);
        fl = clip(nm);
        %pause(1);
        re=clip(rm);
        space = size(rm,2)-size(re,2);
        %*-*-*Uncomment lines below to see the result*-*-*-*-
               %subplot(2,1,1);imshow(fl);
               %subplot(2,1,2);imshow(re);
       break
    else
        fl=im_texto;%Only one line.
        re=[ ];
        space = 0;
    end
end

function img_out=clip(img_in)
[f c]=find(img_in);
img_out=img_in(min(f):max(f),min(c):max(c));


text:
classdef ShiftColor < handle

  properties (Access = public)

  end

  methods (Access = public, Static = true)

    function newColor = shiftColorFwd(oldColor)
      oldSize = size(oldColor);
      oldColor = reshape(oldColor,[1 1 3]);
      hh = rgb2hsv(oldColor);
      hh(1) = mod(hh(1)+0.085,1);
      newColor = hsv2rgb(hh);
      newColor = reshape(newColor,oldSize);
    end

    function newColor = shiftColorBkwd(oldColor)
      oldSize = size(oldColor);
      oldColor = reshape(oldColor,[1 1 3]);
      hh = rgb2hsv(oldColor);
      hh(1) = mod(hh(1)-0.065,1);
      newColor = hsv2rgb(hh);
      newColor = reshape(newColor,oldSize);

    end

    function newColor = increaseIntensity(oldColor)
      oldSize = size(oldColor);
      oldColor = reshape(oldColor,[1 1 3]);
      hh = rgb2hsv(oldColor);
      hh(3) = min(hh(3)+0.2,1);
      newColor = hsv2rgb(hh);
      newColor = reshape(newColor,oldSize);

    end

    function newColor = decreaseIntensity(oldColor)
      oldSize = size(oldColor);
      oldColor = reshape(oldColor,[1 1 3]);
      hh = rgb2hsv(oldColor);
      hh(3) = min(hh(3)-0.2,1);
      newColor = hsv2rgb(hh);
      newColor = reshape(newColor,oldSize);
    end

  end
end

author: kristinbranson

repo: JAABA


text:
% Concatenates a cell array of strings.
%
% Input arguments:
% adjoiner:
%    string separating each neighboring element
% strings:
%    a cell array of strings to join
%
% See also: strsplit2, cell2mat

% Copyright 2008-2009 Levente Hunyadi
function string = strjoin2(adjoiner, strings)

validateattributes(adjoiner, {'char'}, {'vector'});
validateattributes(strings, {'cell'}, {'vector'});
assert(iscellstr(strings), ...
    'strjoin2:ArgumentTypeMismatch', ...
    'The elements to join should be stored in a cell vector of strings (character arrays).');
if isempty(strings)
    string = '';
    return;
end

% arrange substrings into cell array of strings
concat = cell(1, 2 * numel(strings) - 1);  % must be row vector
j = 1;
concat{j} = strings{1};
for i = 2 : length(strings)
    j = j + 1;
    concat{j} = adjoiner;
    j = j + 1;
    concat{j} = strings{i};
end

% concatenate substrings preserving spaces
string = cell2mat(concat);

repo: REST


text:
classdef AnnotationLoader < Algorithm
    properties (Access = public)
        fileName;
    end

    properties (Access = private)
        annotationsMap;
    end

    properties (Dependent)
        annotations;
    end

    methods
        function set.annotations(obj,annotations)
            obj.createAnnotationsMap(annotations);
        end
    end

    methods (Access = public)
        function obj = AnnotationLoader(fileName,annotations)
            if nargin > 0
                obj.fileName = fileName;
                if nargin > 1
                    obj.createAnnotationsMap(annotations);
                end
            end

            obj.name = 'annotationsLoader';
            obj.inputPort = DataType.kNull;
            obj.outputPort = DataType.kAnnotation;
        end

        function annotation = compute(obj,~)
            annotationFileName = Helper.RemoveFileExtension(obj.fileName);
            if isempty(obj.annotationsMap)
                defaultLabeling = DataLoader.LoadDefaultLabeling();
                annotation = DataLoader.LoadAnnotationSetFullPath(obj.fileName,defaultLabeling);
            else
                annotation = obj.annotationsMap(annotationFileName);
            end
        end

        function str = toString(obj)
            str = sprintf('%s_%s',obj.name, obj.fileName);
        end

        function fileNameProperty = getEditableProperties(obj)
            fileNameProperty = Property('fileName',obj.fileName);
        end
    end

    methods (Access = private)
        function createAnnotationsMap(obj,annotations)
            nAnnotations = length(annotations);

            annotationCells = cell(1,nAnnotations);
            annotationNames = cell(1,nAnnotations);

            for i = 1 : nAnnotations
                annotation = annotations(i);
                annotationName = annotation.fileName;
                annotationNames{i} = Helper.RemoveAnnotationsExtension(annotationName);
                annotationCells{i} = AnnotationSet(annotation.eventAnnotations,annotation.rangeAnnotations);
            end
            obj.annotationsMap = containers.Map(annotationNames,annotationCells);
        end
    end
end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function chi = RoadInclination_Arkussinus(z_I_Ground_m,l_WheelbaseFB_m,w_TrackFB_m,phiz_IK_rad)
%% Computation of Road Angles from Street Profile in Inertial Frame
% Input parameters:
% phiz_IK_rad     [rad]    Euler-Angle around z-Axis from Inertial Reference Frame I to Vehicle Fixed Reference Frame K [Psi]
% w_TrackFB_m     [m]      Track width at Front and Rear Axle [w_TrackF_m w_TrackR_m]
% l_WheelbaseFB_m [m]      Wheelbase from Cog to Front and Rear Axle [l_WheelbaseF_m l_WheelbaseR_m]
% z_I_Ground_m    [m]      Input Vector with z-Profile of Street in Inertial Coordinate System at the Axle Locations [x1 x2 x3 x4] [3x4]
% Output parameters:
% Y               [rad]    Approximated Cardan Angles from Inertial Reference Frame to Road Fixed Reference Frame [chi_x chi_y Psi] [3x1]

%% Computation of Road Angles
% Inclination Angle in x-direction for negative z-road-profile
chi_y = -asin( 0.5*((z_I_Ground_m(1)+z_I_Ground_m(2))-(z_I_Ground_m(3)+z_I_Ground_m(4)))/sum(abs(l_WheelbaseFB_m)) );
% Inclination Angle in y-direction for negative z-road-profile
chi_x = -asin( 0.5*((z_I_Ground_m(1)+z_I_Ground_m(3))-(z_I_Ground_m(2)+z_I_Ground_m(4)))/mean(abs(w_TrackFB_m)) );

%% Output Parameters
chi = [chi_x;chi_y;phiz_IK_rad];

author: TUMFTM


text:
syms x
b=limit((sqrt(1+x^2)-1)/(1-cos(x)))

author: Eurus-Holmes


text:
% The COBRAToolbox: testSimilarity.m
%
% Purpose:
%     - testSimilarity tests the functionality of similarity in the
%       rBioNet extension
%
% Authors:
%     - Stefania Magnusdottir April 2017
%

% save the current path
currentDir = pwd;

% initialize the test
fileDir = fileparts(which('testSimilarity'));
cd(fileDir);

% load rBioNet reaction database
load([fileDir, filesep 'rxn.mat'])

% find similar reactions, only checks metabolites
reactions = similarity('2pg[c] <=> h2o[c] + 2 pep[c]', rxn(:, 3), 0);

% test that similar reactions are found
assert(~isempty(reactions))

% try to find reacitons similar to made-up reaction
reactions = similarity('2pg[c] <=> ac[c] + 2 met-L[c]', rxn(:, 3), 0);

% test that similar reactions are found
assert(isempty(reactions))

% change the directory
cd(currentDir)

author: opencobra

repo: cobratoolbox


text:
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
classdef URDF

    properties
        joints
        links
        transmissions
        props
        attr
        jseq
    end

    methods
        function urdf = URDF(urdffile)
            if nargin == 0
                urdffile = 'katana_400_6m180.urdf.xacro';
            end

            dom = xmlread(urdffile);

            links = dom.getElementsByTagName('link');
            joints = dom.getElementsByTagName('joint');
            properties = dom.getElementsByTagName('property');
            robot = dom.getElementsByTagName('robot');
            urdf.attr = urdf.getattr(robot.item(0))

            % get the properties
            fprintf('%d properties\n', properties.getLength);

            Props = [];
            for k = 0:properties.getLength-1
                property = properties.item(k)
                if property.hasAttributes
                    attributes = property.getAttributes;

                    att = [];
                    for i=1:attributes.getLength

                        attribute = attributes.item(i-1);
                        n = char(attribute.getName);
                        v = char(attribute.getValue);
                        att.(n) = v
                    end
                    Props = [ Props; att];
                end
            end
            urdf.props = Props;

            % get the joints
            urdf.joints = URDF.get_elements(dom, 'joint', Props);

            % get the links
            urdf.links = URDF.get_elements(dom, 'link', Props);

            % get the transmissions
            urdf.transmissions = URDF.get_elements(dom, 'transmission', Props);

            p = zeros(1, length(urdf.links));

            for j=1:length(urdf.joints)
                    i = urdf.ln2i( urdf.joints{j}.parent.link);
                    p(i) = p(i) + 1;
                    i = urdf.ln2i( urdf.joints{j}.child.link);
                    p(i) = p(i) - 1;
            end

            [~,base_link] = max(p);
            base_link_name = urdf.links{base_link}.name;
            link = base_link_name;
            for j=1:length(urdf.joints)
                jj = urdf.findnextjoint(link);
                if isempty(jj)
                    break;
                end
                urdf.jseq(j) = jj;
                link = urdf.joints{jj}.child.link;
            end
        end

        function r = robot(urdf)
            for i=1:urdf.njoints
                % create link objects
                % attach the STL model to them
            end
            r = SerialLink(links, 'name', urdf.attr.name);
        end

        function n = nlinks(urdf)
            n = length(urdf.links);
        end

        function n = njoints(urdf)
            n = length(urdf.joints);
        end

        % map joint/link name to an index

        function joint = findnextjoint(urdf, link)
            joint = [];
            for j=1:length(urdf.joints)
                if strcmp(link, urdf.joints{j}.parent.link)
                    joint = j;
                    return
                end
            end
        end

        function idx = ln2i(urdf, name)
            idx = [];
            for i=1:length(urdf.links)
                if strcmp(urdf.links{i}.name, name)
                    idx = i;
                    return
                end
            end
        end

        function display(urdf)
            for j=1:length(urdf.joints)
                joint = urdf.joints{j};
                fprintf('j%d: %s -> %s (%s)\n', j, joint.parent.link, joint.child.link, joint.type);
            end
        end
    end

    methods (Static)
        function List = get_elements(doc, elname, props)
            elements  = doc.getElementsByTagName(elname);
            % get the links
            List = {};
            fprintf('%d %s\n', elements.getLength, elname);
            % step through the list of  elements found
            for k = 1:elements.getLength
                element = elements.item(k-1);

                info = URDF.descend(element, props);
                info = URDF.getattr(element, info, props);
                List{k} = info;
            end
        end

        function t = descend(node, props)
            if node.hasChildNodes
                t = [];

                nodeChildren = node.getChildNodes;
                for i=1:nodeChildren.getLength
                    child = nodeChildren.item(i-1);
                    if child.getNodeType == 3
                        continue;
                    end
                    result = URDF.descend(child, props);
                    if ~isempty(result)
                        n = char(child.getNodeName);
                        t.(n) = result;
                    end
                end
            elseif node.hasAttributes
                t = URDF.getattr(node, [], props);
            else
                t = [];
            end
        end

        function att = getattr(node, att, props)
            if nargin < 2
                att = [];
            end
            if nargin < 3
                props = [];
            end

            attributes = node.getAttributes;
            for i=1:attributes.getLength
                attribute = attributes.item(i-1);
                n = char(attribute.getName);
                v = char(attribute.getValue);

                % skip properties with colon in them
                n = strrep(n, ':', '_');

                %do simple xacro type substitution
                %xyz="0 0 ${-base_height}"
                if ~isempty(props)

                    % is there a ${...} substring
                    [s,e] = regexp(v, '\${[^}]*');
                    if ~isempty(s)
                        macro = v(s+2:e);
                        %fprintf('XACRO: %s --> ', v);
                        % if yes, then regexprep replace within it for every property in the list
                        for k=1:length(props)
                            macro = strrep(macro, props(k).name, props(k).value);
                        end
                        % stick the macro back into the original string
                        macro = strrep(macro, ' ', '');  % remove all blanks
                        v = [v(1:s-1) macro v(e+2:end)];
                        %fprintf('%s\n', v);
                    end
                end

                % attempt to convert it to a scalar or vector, fallback is a string
                att.(n) = str2num(v);
                if isempty( att.(n) )
                    att.(n) = v;
                end
            end
        end
    end
end

author: petercorke

repo: robotics-toolbox-matlab


text:
function r8sp_print_some ( m, n, nz_num, row, col, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% R8SP_PRINT_SOME prints some of a R8SP matrix.
%
%  Discussion:
%
%    This version of R8SP_PRINT_SOME has been specifically modified to allow,
%    and correctly handle, the case in which a single matrix location
%    A(I,J) is referenced more than once by the sparse matrix structure.
%    In such cases, the routine prints out the sum of all the values.
%
%    The R8SP storage format stores the row, column and value of each nonzero
%    entry of a sparse matrix.
%
%    It is possible that a pair of indices (I,J) may occur more than
%    once.  Presumably, in this case, the intent is that the actual value
%    of A(I,J) is the sum of all such entries.  This is not a good thing
%    to do, but I seem to have come across this in MATLAB.
%
%    The R8SP format is used by CSPARSE ("sparse triplet"), DLAP/SLAP
%    ("nonsymmetric SLAP triad"), by MATLAB, and by SPARSEKIT ("COO" format).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns of the matrix.
%
%    Input, integer NZ_NUM, the number of nonzero elements in the matrix.
%
%    Input, integer ROW(NZ_NUM), COL(NZ_NUM), the row and column indices
%    of the nonzero elements.
%
%    Input, real A(NZ_NUM), the nonzero elements of the matrix.
%
%    Input, integer ILO, JLO, IHI, JHI, the first row and
%    column, and the last row and column to be printed.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );

  incx = 5;
%
%  Print the columns of the matrix, in strips of 5.
%
  for j2lo = jlo: incx: jhi

    j2hi = j2lo + incx - 1;
    j2hi = min ( j2hi, n );
    j2hi = min ( j2hi, jhi );

    inc = j2hi + 1 - j2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col: ' );

    for j = j2lo : j2hi
      fprintf ( 1, '%7d       ', j );
    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row\n' );
    fprintf ( 1, '  ---\n' );
%
%  Determine the range of the rows in this strip.
%
    i2lo = max ( ilo, 1 );
    i2hi = min ( ihi, m );

    for i = i2lo : i2hi
%
%  Print out (up to) 5 entries in row I, that lie in the current strip.
%
      nonzero = 0;

      aij(1:inc) = 0.0;

      for k = 1 : nz_num

        if ( i == row(k) && j2lo <= col(k) && col(k) <= j2hi )

          j2 = col(k) - j2lo + 1;

          if ( a(k) ~= 0.0 )
            nonzero = 1;
            aij(j2) = aij(j2) + a(k);
          end

        end

      end

      if ( nonzero )
        fprintf ( 1, '%4d', i );
        for j = 1 : inc
          fprintf ( 1, '  %12g', aij(j) );
        end
        fprintf ( 1, '\n' );
      end

    end

  end

  return
end


text:
function featuresS = ngtdmToScalarFeatures(s,p,numVoxels)
% function featuresS = ngtdmToScalarFeatures(s,p,numVoxels)
%
% APA, 3/15/2017

% Coarseness
featuresS.coarseness = 1/(sum(s .* p) + 1e-6);

% Contrast
Ng = sum(p > 0);
numLevels = length(p);
indV = (1:numLevels)';
term1 = 0;
term2 = 0;
for lev = 1:numLevels
    term1 = term1 + ...
        sum(p .* circshift(p,lev) .* (indV-circshift(indV,lev)).^2);
    term2 = term2 + s(lev);
end
featuresS.contrast = 1/Ng/(Ng-1) * term1 * term2 / numVoxels;

% Busyness
denom = 0;
for lev = 1:numLevels
    pShiftV = circshift(p,lev);
    indShiftV = circshift(indV,lev);
    usePv = p > 0;
    usePshiftV = pShiftV > 0;
    denom = denom + ...
        sum(usePv .* usePshiftV .* abs(p .* indV - pShiftV .* indShiftV));
end
featuresS.busyness = sum(p .* s) / denom;

% Complexity
complxty = 0;
for lev = 1:numLevels
    pShiftV = circshift(p,lev);
    sShiftV = circshift(s,lev);
    indShiftV = circshift(indV,lev);
    usePv = p > 0;
    usePshiftV = pShiftV > 0;
    term1 = abs(indV - indShiftV);
    term2 = usePv .* usePshiftV .* (p .* s + pShiftV .* sShiftV)...
        ./ (p + pShiftV + eps);
    complxty = complxty + sum(term1 .* term2);
end
featuresS.complexity = complxty / numVoxels;

% Texture strength
strength = 0;
for lev = 1:numLevels
    pShiftV = circshift(p,lev);
    indShiftV = circshift(indV,lev);
    usePv = p > 0;
    usePshiftV = pShiftV > 0;
    term = sum(usePv .* usePshiftV .* (p + pShiftV) .* (indV - indShiftV).^2);
    strength = strength + term;
end
featuresS.strength = strength / sum(s);

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function [hf] = anim8_DIC_images(ImPaths,ImSet)
%% function for plotting animated figure of all speckle images, for reviweing before selecting ROI, in step 2
% anim8_DIC_images
% [] = anim8_DIC_images(ImPaths);
%
% function for plotting the images chosen for stereo DIC (2 views)
% requirements: GIBBON toolbox
%
% INPUT:
% * ImPaths - a 2nX1 cell array containing 2n paths to grayscale images. The first n
% images are from camera A (the "reference" camera), and the last n images
% are from camera B (the "deformed" camera). The first image in the set is
% considered as the reference image, on which the reference grid of points
% is defined, and all the correlated points and consequent displacements
% and strains, are relative to this image.

%%
nCur=numel(ImPaths); % number of frames

nSteps=nCur/2; %Number of animation steps
if  rem(nSteps,1)~=0
    error('Number of images in the set should be even');
end

nImCurSet=repmat(1:nSteps,1,2);

%%
hf=cFigure;
hf.Name='Preview Images';
hf.Units='normalized'; hf.OuterPosition=[.05 .05 .9 .9]; hf.Units='pixels';

animStruct=struct; % create animation structure

% show 1st image from view 1 (Reference Camera)
subplot(1,2,1)
hp1=imagesc(repmat(ImSet{1},1,1,3)); hold on
pbaspect([size(ImSet{1},2) size(ImSet{1},1) 1]);
hs1=title(['Cur ' num2str(1) ' (Cam Ref, frame ' num2str(nImCurSet(1)) ')']);
axis off

% show 1st image from view 2 ("Deformed" Camera)
subplot(1,2,2)
hp2=imagesc(repmat(ImSet{1+nCur/2},1,1,3)); hold on
pbaspect([size(ImSet{1+nCur/2},2) size(ImSet{1+nCur/2},1) 1]);
hs2=title(['Cur ' num2str(1) ' (Cam Def, frame ' num2str(nImCurSet(1)) ')']);
axis off

%Create the "time" (frame) vector
animStruct.Time=linspace(0,1,nSteps);

%Populate the animStruct
for ii=1:1:nSteps
    TitleNow2=['Cur ' num2str(ii) ' (Cam Ref, frame ' num2str(nImCurSet(ii)) ')'];
    TitleNow3=['Cur ' num2str(ii+nCur/2) ' (Cam Def, frame ' num2str(nImCurSet(ii+nCur/2)) ')'];

    %Set entries in animation structure
    animStruct.Handles{ii}=[hp1,hp2,hs1,hs2]; %Handles of objects to animate
    animStruct.Props{ii}={'CData','CData','String','String'}; %Properties of objects to animate
    animStruct.Set{ii}={repmat(ImSet{ii},1,1,3),repmat(ImSet{ii+nCur/2},1,1,3),TitleNow2,TitleNow3}; %Property values for to set in order to animate

end

gtitle('Image set for DIC. Press the play button to preview all images, press the stop button to stop animation, and then press any key in the command window to continue',14);

% Start |anim8| gui
anim8(hf,animStruct);

end

%%
% MultiDIC: a MATLAB Toolbox for Multi-View 3D Digital Image Correlation
%
% License: <https://github.com/MultiDIC/MultiDIC/blob/master/LICENSE.txt>
%
% Copyright (C) 2018  Dana Solav
%
% If you use the toolbox/function for your research, please cite our paper:
% <https://engrxiv.org/fv47e>

author: MultiDIC

repo: MultiDIC

save_path: github-repos/MATLAB/MultiDIC-MultiDIC


text:
function [yesno,diagnostic] = isfeasible(OptimizationProblem,Options)
%FEASIBLE  Check feasibility by solving feasibility problem
%
%   YESNO = isfeasible(P[,Options])
%
%   Example
%
%    The following code creates an optimization problem, and then checks
%    feasibility
%
%    x = sdpvar(1);P = optproblem(x >= 0, x^2);isfeasible(P)

OptimizationProblem.Options.verbose = 0;
if nargin < 2
    diagnostics = solvesdp(OptimizationProblem.Constraints,[],OptimizationProblem.Options);
    yesno = diagnostics.problem ~=1;
else
    Options.verbose = 0;
    diagnostics = solvesdp(OptimizationProblem.Constraints,[],OptimizationProblem.Objective,Options);
    yesno = diagnostics.problem ~=1;
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function [f,g] = detGrad(fun,x0,xdata)
%DETGRAD  Determine whether supplied function contains gradient information

%   Copyright (C) 2011 Jonathan Currie (IPL)

%Sort out gradient (unfortunately rather inefficient)
no = nargout(fun);

if(no == 1)
    f = fun;
    g = [];
elseif(no == 2)
        f = @(x) fval(fun,x);
        g = @(x) gval(fun,x);
elseif(no < 0)
    %Either anonymous function or varargout (i.e. deal?)
    try
        if(nargin(fun) > 1)
            fun(x0,xdata);
        else
            fun(x0);
        end
        f = fun;
        g = [];
    catch me
        try
            [~,~] = fun(x0);
            f = @(x) fval(fun,x);
            g = @(x) gval(fun,x);
        catch
            error(['Unknown function / gradient format: ' me.message])
        end
    end

else
    error('Unknown function / gradient format');
end

%Dummy functions
function f = fval(fun,x)
[f,~] = fun(x);

function g = gval(fun,x)
[~,g] = fun(x);

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
% EEG_EVAL - apply eeglab function to a collection of input datasets
%
% Usage:
%   >> OUTEEG = eeg_eval(funcname, INEEG, 'key1', value1, 'key2', value2 ...);
%
% Inputs:
%   funcname      - [string] name of the function
%   INEEG         - EEGLAB input dataset(s)
%
% Optional inputs
%   'params'      - [cell array] funcname parameters.
%   'warning'     - ['on'|'off'] warning pop-up window if several dataset
%                   stored on disk that will be automatically overwritten.
%                   Default is 'on'.
%
% Outputs:
%   OUTEEG        - output dataset(s)
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2005
%
% see also: EEGLAB

% Copyright (C) 2005 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [EEG, com] = eeg_eval( funcname, EEG, varargin)

    com = '';
    if nargin < 2
        help eeg_eval;
        return;
    end

    % check input parameters
    % ----------------------
    g = finputcheck( varargin, { 'params'   'cell'    {}               {};
                                 'warning'  'string'  { 'on','off' }   'off' }, 'eeg_eval');
    if ischar(g), error(g); end

    % warning pop up
    % --------------
    eeglab_options;
    if strcmpi(g.warning, 'on')
        if ~option_storedisk
            res = questdlg2(strvcat( 'When processing multiple datasets, it is not', ...
                                 'possible to enter new names for the newly created', ...
                                 'datasets and old datasets are overwritten.', ...
                                 'You may still cancel this operation though.'), ...
                 'Multiple dataset warning', 'Cancel', 'Proceed', 'Proceed');
        else
            res = questdlg2( [ 'Data files on disk will be automatically overwritten.' 10 ...
                                'Are you sure you want to proceed with this operation?' ], ...
                            'Confirmation', 'Cancel', 'Proceed', 'Proceed');
        end
        switch lower(res)
            case 'cancel', return;
            case 'proceed'
        end
        vPar = ver('parallel');
        if option_parallel && ~isempty(vPar)
            res = questdlg2(strvcat( 'You have selected to use the parallel toolbox,', ...
                                 'to process multiple datasets. If you saturate the ', ...
                                 'memory, this could cause your computer to become.', ...
                                 'unresponsive or even crash.'), ...
                 'Multiple dataset warning', 'Cancel', 'Proceed', 'Proceed');
        end
        switch lower(res)
            case 'cancel', return;
            case 'proceed'
        end
    end

    % execute function
    % ----------------
    v = version;
    if str2num(v(1)) == '5' % Matlab 5
        command = [ 'TMPEEG = ' funcname '( TMPEEG, ' vararg2str(g.params) ');' ];
    elseif isstr(funcname)
        eval( [ 'func = @' funcname ';' ] );
    else
        func = funcname;
    end

%     notCompatibleFunc = {
%         @clean_artifacts
%     };

    NEWEEG = EEG;
    if option_parallel
        disp('Using the parallel toolbox to process multiple datasets (change in File > Preferences)');
        myPool = gcp;
        tmpoptions_store = option_storedisk;
        parfor i = 1:length(EEG)
            fprintf('Processing group dataset %d of %d named: %s ****************\n', i, length(EEG), EEG(i).setname);
            TMPEEG    = eeg_retrieve(EEG, i);
            TMPEEG = feval(func, TMPEEG, g.params{:});
            TMPEEG = eeg_checkset(TMPEEG);
            TMPEEG.saved = 'no';
            if tmpoptions_store
                TMPEEG = pop_saveset(TMPEEG, 'savemode', 'resave');
                TMPEEG = update_datafield(TMPEEG);
                NEWEEG(i) = TMPEEG;
                NEWEEG(i).saved = 'yes'; % eeg_store by default set it to no
            else
                NEWEEG(i) = TMPEEG;
                NEWEEG(i).saved = 'yes'; % eeg_store by default set it to no
            end
        end
    else
        for i = 1:length(EEG)
            fprintf('Processing group dataset %d of %d named: %s ****************\n', i, length(EEG), EEG(i).setname);
            TMPEEG    = eeg_retrieve(EEG, i);
            TMPEEG = feval(func, TMPEEG, g.params{:});
            TMPEEG = eeg_checkset(TMPEEG);
            TMPEEG.saved = 'no';
            if option_storedisk
                TMPEEG = pop_saveset(TMPEEG, 'savemode', 'resave');
                TMPEEG = update_datafield(TMPEEG);
            end
            NEWEEG = eeg_store(NEWEEG, TMPEEG, i);
            if option_storedisk
                NEWEEG(i).saved = 'yes'; % eeg_store by default set it to no
            end
        end
    end
    EEG = NEWEEG;

    % history
    % -------
    if nargout > 1
        com = sprintf('%s = %s( %s,%s);', inputname(2), char(funcname), inputname(2), vararg2str(g.params));
    end

function EEG = update_datafield(EEG)
    if ~isfield(EEG, 'datfile'), EEG.datfile = ''; end
    if ~isempty(EEG.datfile)
        EEG.data = EEG.datfile;
    else
        EEG.data = 'in set file';
    end
    EEG.icaact = [];

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
%{
Yahoo! TVSum50 Dataset.
- Function to compute a pairwise F1 score
%}

function [ out ] = pairwise_f1( score,portion )
%PAIRWISE_F1 Summary of this function goes here

    addpath('../knapsack');

    if size(score,1) < size(score,2),
        error('score must be column-wise matrix; each column is an observation');
    end

    L = size(score,1); % sequence length
    N = size(score,2); % number of annotations

    % Pre-compute knapsack solution
    y = cell(1,N);
    for i=1:N
        [~,y{i}] = knapsack(ones(L,1), score(:,i), fix(portion*L));
    end

    for i=1:N,
        val = 0; % accumulative f-measure
        for j=1:N,
            if i==j, continue; end
            cp = classperf(y{i},y{j},'Positive',1,'Negative',0);
            prec = cp.CorrectRate;
            rec = cp.Sensitivity;
            f1score = 2*(prec*rec)/(prec+rec);

            val = val+f1score;
        end
        val = val / (N-1);
        out(i) = val;
    end
end

author: kezhang-cs

repo: Video-Summarization-with-LSTM


text:
function d = grPropagateDistance(v, e, v0, l)
%GRPROPAGATEDISTANCE Propagates distances from a vertex to other vertices
%
%   DISTS = grPropagateDistance(V, E, V0, L)
%   V0 is index of initial vertex
%   E is array of source and target vertices
%   L is the vector of length of each edge. If not specified, length 1 is
%       assumed for all edges.
%   The result DISTS is a column array with as many rows as the number of
%   vertices, containing the geodesic distance of each vertex to the vertex
%   of index V0.
%
%   Example
%     nodes = [20 20;20 50;20 80;50 50;80 20;80 50;80 80];
%     edges = [1 2;2 3;2 4;4 6;5 6;6 7];
%     figure; drawGraph(nodes, edges);
%     axis([0 100 0 100]); axis equal; hold on
%     DISTS = grPropagateDistance(nodes, edges, 2)
%     DISTS =
%          1
%          0
%          1
%          1
%          3
%          2
%          3
%     drawNodeLabels(nodes+1, DISTS);
%
%   See Also
%   graphRadius, graphCenter, graphDiameter, graphPeripheralVertices
%   grVertexEccentricity
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2010-09-07,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2010 INRA - Cepia Software Platform.

% initialize empty array for result
Nv  = length(v);
d   = ones(Nv, 1)*inf;
d(v0) = 0;

% ensure there is a valid length array
if nargin < 4
    l = ones(size(e,1), 1);
end

% iterate from germ vertex until there are no more vertices to process
verticesToProcess = v0;
while ~isempty(verticesToProcess)
    % init new iteration
    newVerticesToProcess = [];

    % iterate over vertices that need to be updated
    for i = 1:length(verticesToProcess)
        vertex = verticesToProcess(i);

        % iterate over neighbor edges of current vertex
        vertexEdges = grAdjacentEdges(e, vertex);
        for j = 1:length(vertexEdges)
            iEdge = vertexEdges(j);

            % compute distance between current vertex and its neighbor
            vertex2 = grOppositeNode(e(iEdge,:), vertex);
            newDist = d(vertex) + l(iEdge);

            % update geodesic distance of neighbor node if needed
            if newDist < d(vertex2)
                d(vertex2) = newDist;
                newVerticesToProcess = [newVerticesToProcess ; vertex2]; %#ok<AGROW>
            end
        end
    end

    % update set of vertices for next tieration
    verticesToProcess = newVerticesToProcess;
end

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
function varargout = quickshift(varargin)
% VL_QUICKSHIFT Quick shift image segmentation
%   Quick shift is a mode seeking algorithm which links each pixel to
%   its nearest neighbor which has an increase in the estimate of the
%   density. These links form a tree, where the root of the tree is
%   the pixel which correspond to the highest mode in the image.
%
%   [MAP,GAPS] = VL_QUICKSHIFT(I, KERNELSIZE, MAXDIST) computes quick shift on the
%   image I. KERNELSIZE is the bandwidth of the Parzen window estimator of
%   the density. Since searching over all pixels for the nearest
%   neighbor which increases the density would be prohibitively
%   expensive, MAXDIST controls the maximum L2 distance between neighbors
%   that should be linked. MAP and GAP represent the resulting forest
%   of trees. They are array of the same size of I.  Each element
%   (pixel) of MAP is and index to the parent elemen in the forest and
%   GAP contains the corresponding branch length. Pixels which are at
%   the root of their respective tree have MAP(x) = x and GAPS(x) =
%   inf.
%
%   [MAP,GAPS,E] = VL_QUICKSHIFT(I, KERNELSIZE, MAXDIST) also returns the estimate
%   of the density E.
%
%   [MAP,GAPS] = VL_QUICKSHIFT(I, KERNELSIZE) uses a default MAXDIST of 3 * KERNELSIZE.
%
%   Notes::
%     The distance between pixels is always measured in image
%     coordinates (not normalized), so the importance of the color
%     component should be weighted accordingly before calling this
%     function.
%
%   Options:
%
%   Verbose::
%     Toggles verbose output.
%
%   Medoid::
%     Run medoid shift instead of quick shift.
%
%   See also: VL_HELP().
[varargout{1:nargout}] = vl_quickshift(varargin{:});

author: yihui-he

repo: panorama


text:
function circle_segment_test16 ( )

%*****************************************************************************80
%
%% CIRCLE_SEGMENT_TEST16 demonstrates GQCIRCSECT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 July 2013
%
%  Author:
%
%    Feifei Xu
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CIRCLE_SEGMENT_TEST17\n' );
  fprintf ( 1, '  Demonstrate GQCIRCSECT.\n' );

  close all;
  tmp = sqrt(2)/2;
%
%  Acute angle
%
  theta = -pi/4 : pi/200 : pi/4;

  for n = 9

    [x,y,w] = gqcircsect ( n, pi/4, 1 );

    figure;
    line([tmp,0,tmp],[-tmp,0,tmp]);
    hold on;
    plot(cos(theta),sin(theta));
    axis equal;
    plot(x,y,'k*');

    filename = 'test16_acute.png';
    print ( '-dpng', filename );
    fprintf ( 1, '  Created graphics image "%s".\n', filename );

  end
%
%  Obtuse angle
%
  theta = -pi/4*3 : pi/200 : pi/4*3;

  for n = 9

    [x,y,w] = gqcircsect ( n, pi/4*3, 1 );

    figure;
    line([-tmp,0,-tmp],[-tmp,0,tmp]);
    hold on;
    plot(cos(theta),sin(theta));
    axis equal;
    plot(x,y,'ko');

    filename = 'test16_obtuse.png';
    print ( '-dpng', filename );
    fprintf ( 1, '  Created graphics image "%s".\n', filename );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function T = mytoeplitz(c, r)
% function T = mytoeplitz(c, r)
% Emulate the function TOEPLITZ for fun...

if nargin<2
    r=c;
end

c=c(:);
r=r(:);
v = [flipud(c); r(2:end)];

sz= [length(c) length(r)];
[I J] = itril(sz,Inf);
K = J-I+length(c);
Ilin = sub2ind(sz, I, J);
T = zeros(sz);
T(Ilin) = v(K);

author: Sable

repo: mcbench-benchmarks


text:
%kkclipout 'Clip Data Values Outside of the Specified Range'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kclipout.pane file
%
% Parameters:
% InputFile: i 'Input ', required: 'Input file'
% OutputFile: o ' Output ', required: 'output file'
%
% Example: o = kkclipout(i, {'i','';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kclipout - Clip Data Values Outside of the Specified Range
%
%  DESCRIPTION
% The "Clip Outside" operator (kclipout) performs clipping on the Input
% data object (i) outside of the range defined by the specified Lower and Upper
% Cutoff Values (lc, uc).
% All data values in the Input object that are LESS THAN the Lower Cutoff
% are set to the Lower Cutoff in the resulting Output object, unless the
% alternate "Lower Cutoff Output Value" (fval) is explicitly provided.  If
% this value is provided, clipped data are set to that value instead of the
% Lower Cutoff.  Likewise, data values GREATER THAN the Upper Cutoff are set
% to the Upper Cutoff, unless the alternate "Upper Cutoff Output Value" is
% explicitly provided.  All other data remain the same.
%
% The following histogram defines the clipping operation.
% .KS
%
% \f(CW
%                                 |<-A->|<-B->|<-C->|
%                                 |     | :   | .   |
%                                 |    .:.:.  .:::  |
%                                 |:. .::::::.::::: |
%                                 |::::::::::::::::.|
%                                 ------|-----|------
%                                      lc     uc
%
%         A:  if value <  lc                  output = lc or fval
%         B:  if value >= lc AND value <= uc  output = input
% 	C:  if value >  uc                  output = uc or tval
% "
%
% .KE
% P "Data Type" 5
% .cI $DATAMANIP/repos/shared/man/sections/value_type_1input
%
%  "Map Data" 5
% .cI $DATAMANIP/repos/shared/man/sections/map_1input
%
%  "Validity Mask" 5
% .cI $DATAMANIP/repos/shared/man/sections/mask_1input
%
%  "Explicit Location and Time Data" 5
% .cI $DATAMANIP/repos/shared/man/sections/loc_and_time_1input
%
%  "Failure Modes"
% .cI $DATAMANIP/repos/shared/man/sections/fail_1input
%
% Executing "Clip Outside" runs the program \fIkclip\fP with the -thresh
% option set to FALSE (-thresh 0).
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% DATAMANIP::kclipabove, DATAMANIP::kclipbelow, DATAMANIP::kclipin,
% DATAMANIP::kmegaclip, DATAMANIP::kclip
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkclipout(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kkclipout(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'o', '__output'};
maxval={0,0};
minval={0,0};
istoggle=[0,0];
was_set=istoggle * 0;
paramtype={'InputFile','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'kclip"  -thresh'],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function status = test_linkwitz_riley(modus)
%TEST_LINKWITZ_RILEY tests the design of the Linkwitz-Riley Filters
%
%   Usage: status = test_linkwitz_riley(modus)
%
%   Input parameters:
%       modus   - 0: numerical
%                 1: visual
%
%   Output parameters:
%       status  - true or false

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

status = false;

%% ===== Checking of input  parameters ===================================
nargmin = 1;
nargmax = 1;
narginchk(nargmin,nargmax);

%% ===== Main ============================================================
fs = 44100;  % sampling frequency in Hz
fc = 1000;  % crossover frequency in Hz
f = logspace(-3,log10(fs/2),10000);  % frequeny-axis in Hz
omega = 2*pi*f;  % angular frequency

ftype = {'low' 'high' 'all'};  % filter types
Hs = zeros(3,length(f));  % s-domain frequency spectra
Hz = Hs;  % z-domain frequency spectra

for Nlr = [2 4 12]  % filter orders

  for tdx = 1:3
    % Laplace-Domain
    [zs,ps,ks] = linkwitz_riley(Nlr,2*pi*fc,ftype{tdx},'s');
    [soss,gs] = zp2sos(zs,ps,ks,'down','none');

    s = [-omega.^2; 1i*omega];
    s(3,:) = 1;

    if isoctave && strcmp(ftype{tdx}, 'low')
      % WORKAROUND for Octave bug (https://savannah.gnu.org/bugs/?51936)
      Hs(tdx,:) = gs.*prod( (soss(:,3:-1:1)*s)./(soss(:,4:6)*s),1);
    else
      Hs(tdx,:) = gs.*prod( (soss(:,1:3)*s)./(soss(:,4:6)*s),1);
    end

    % z-Domain
    [zz,pz,kz] = linkwitz_riley(Nlr,fc./fs*2,ftype{tdx},'z');
    [sosz,gz] = zp2sos(zz,pz,kz,'down','none');

    z = [exp(0.*omega./fs); exp(-1j.*omega./fs); exp(-2j.*omega./fs)];
    Hz(tdx,:) = gz.*prod( (sosz(:,1:3)*z)./(sosz(:,4:6)*z),1);
  end

  % plotting
  if modus
    figure;
    subplot(2,2,1);
    plot_amp(f, Hs);
    title(sprintf('Amplitude Spectrum, s-Domain, order=%d', Nlr));
    subplot(2,2,2);
    plot_phase(f, Hs);
    title(sprintf('Phase Spectrum, s-Domain, order=%d', Nlr));
    subplot(2,2,3);
    plot_amp(f, Hz);
    title(sprintf('Amplitude Spectrum, z-Domain, order=%d', Nlr));
    subplot(2,2,4);
    plot_phase(f, Hz);
    title(sprintf('Phase Spectrum, z-Domain, order=%d', Nlr));
  end
end

status = true;

end

function plot_amp(f, H)
semilogx( ...
  f, db(H(1,:)), 'b', ...
  f, db(H(2,:)), 'r', ...
  f, db(H(1,:)+H(2,:)), 'g.', ...
  f, db(H(3,:)), 'k--' ...
  );
legend('Lowpass', 'Highpass', 'Lowpass + Highpass', 'Allpass', 'Location', 'southwest');
xlabel('f / Hz');
ylabel('20 lg |H| / dB')
xlim([f(1), f(end)]);
ylim([-90, 10]);
end

function plot_phase(f, H)
semilogx( ...
  f, unwrap(angle(H(1,:))), 'b', ...
  f, unwrap(angle(H(2,:))), 'r', ...
  f, unwrap(angle(H(1,:)+H(2,:))), 'g.', ...
  f, unwrap(angle(H(3,:))), 'k--' ...
  );
legend('Lowpass', 'Highpass', 'Lowpass + Highpass', 'Allpass', 'Location', 'southwest');
xlabel('f / Hz');
ylabel('angle(H) / rad')
xlim([f(1), f(end)]);
end

author: sfstoolbox

repo: sfs-matlab


text:
function a = gk323_inverse ( n )

%*****************************************************************************80
%
%% GK323_INVERSE returns the inverse of the GK323 matrix.
%
%  Properties:
%
%    A is symmetric: A' = A.
%
%    Because A is symmetric, it is normal.
%
%    Because A is normal, it is diagonalizable.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real A(N,N), the matrix.
%
  a = zeros ( n, n );

  for i = 1 : n
    for j = 1 : n

      if ( i == j )
        if ( i == 1 | i == n )
          a(i,j) = - 0.5 * ( n - 2 ) / ( n - 1 );
        else
          a(i,j) = - 1.0;
        end
      elseif ( i == j+1 | i == j-1 )
        a(i,j) = 0.5;
      elseif ( i == 1 & j == n )
        a(i,j) = 0.5 / ( n - 1 );
      elseif ( i == n & j == 1 )
        a(i,j) = 0.5 / ( n - 1 );
      else
        a(i,j) = 0.0;
      end

    end
  end

  return
end


text:
function [J, grad] = cofiCostFunc(params, Y, R, num_users, num_movies, ...
                                  num_features, lambda)
%COFICOSTFUNC Collaborative filtering cost function
%   [J, grad] = COFICOSTFUNC(params, Y, R, num_users, num_movies, ...
%   num_features, lambda) returns the cost and gradient for the
%   collaborative filtering problem.
%

% Unfold the U and W matrices from params
X = reshape(params(1:num_movies*num_features), num_movies, num_features);
Theta = reshape(params(num_movies*num_features+1:end), ...
                num_users, num_features);

% You need to return the following values correctly
J = 0;
X_grad = zeros(size(X));
Theta_grad = zeros(size(Theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost function and gradient for collaborative
%               filtering. Concretely, you should first implement the cost
%               function (without regularization) and make sure it is
%               matches our costs. After that, you should implement the
%               gradient and use the checkCostFunction routine to check
%               that the gradient is correct. Finally, you should implement
%               regularization.
%
% Notes: X - num_movies  x num_features matrix of movie features
%        Theta - num_users  x num_features matrix of user features
%        Y - num_movies x num_users matrix of user ratings of movies
%        R - num_movies x num_users matrix, where R(i, j) = 1 if the
%            i-th movie was rated by the j-th user
%
% You should set the following variables correctly:
%
%        X_grad - num_movies x num_features matrix, containing the
%                 partial derivatives w.r.t. to each element of X
%        Theta_grad - num_users x num_features matrix, containing the
%                     partial derivatives w.r.t. to each element of Theta
%

J = 1 / 2 * sum(sum(R .* (X * Theta' - Y) .^ 2)) + lambda / 2 * (sum(sum(Theta .^ 2)) + sum(sum(X .^ 2)));

for i=1:num_movies
    idx = find(R(i, :) == 1);
    Theta_temp = Theta(idx, :);
    Y_temp = Y(i, idx);
    X_grad(i, :) = (X(i, :) * Theta_temp' - Y_temp) * Theta_temp + lambda * X(i, :);
end

for i=1:num_users
    idx = find(R(:, i) == 1);
    X_temp = X(idx, :);
    Y_temp = Y(idx, i);
    Theta_grad(i, :) = (X_temp * Theta(i, :)' - Y_temp)' * X_temp + lambda * Theta(i, :);
end

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

grad = [X_grad(:); Theta_grad(:)];

end

author: merwan

repo: ml-class

save_path: github-repos/MATLAB/merwan-ml-class


text:
%-------------------------------------------------------------------------------------------------------------------%
%
% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear
% 	fluid-structure interaction models. This version of the code is based off of
%	Peskin's Immersed Boundary Method Paper in Acta Numerica, 2002.
%
% Author: Nicholas A. Battista
% Email:  nickabattista@gmail.com
% Date Created: May 27th, 2015
% Institution: UNC-CH
%
% This code is capable of creating Lagrangian Structures using:
% 	1. Springs
% 	2. Beams (*torsional springs, non-invariant beams*)
% 	3. Target Points
%	4. Muscle-Model (combined Force-Length-Velocity model, "Hill+(Length-Tension)")
%
% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting lengths, etc
%
% There are a number of built in Examples, mostly used for teaching purposes.
%
% If you would like us to add a specific muscle model, please let Nick (nickabattista@gmail.com) know.
%
%--------------------------------------------------------------------------------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION: updates the spring attributes!
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function springs_info = update_Springs(dt,current_time,xLag,yLag,springs_info)

%springs_info: col 1: starting spring pt (by lag. discretization)
%              col 2: ending spring pt. (by lag. discretization)
%              col 3: spring stiffness
%              col 4: spring resting lengths

%RL = springs_info(:,4); % resting-length vector

% Contraction Frequency
freq = 1.0;

% CHANGE RESTING LENGTH BTWN SIDES OF JELLYFISH BELL
springs_info(119:end,4) = abs( cos(freq*current_time*pi) );

%NOTE: not 2*pi*ft b/c of abs()

author: nickabattista


text:
function Bd = getBd(phi, h, d)

% getBd: get the B-matrix as in equation (16) and Lemma 2
%
% Usage:    Bd = getBd(phi, h, d)
%
% INPUTS:
%       phi: a cell containing all the systems Phi_i(s)
%       h: the fast sampling interval
%       d: the vector of fractional delays
%
% OUTPUT:
%       Bd: matrix Bd as in equation (16)
%
% SEE ALSO: getAd, getCd

N = length(d);

% Compute for the block not containing Q0 and R0
BB = [];

for i = 1:N
    Ai = phi{i+1}{1};
    Bi = phi{i+1}{2};
    Ci = phi{i+1}{3};

    % Column i of BB
    BBi = [];

    % Concatenate Delta_ij to get row i
    for j = 1:N
        if ( i <= j)
            Aj = phi{j+1}{1};
            Bj = phi{j+1}{2};
            Cj = phi{j+1}{3};

            QQ = MVL(Ai, Bi, Aj, Bj, h);
            QR =   expm(d(j)*Aj) * MVL(Ai, Bi, Aj, Bj, h-d(j)) * Cj' ;
            RQ = ( expm(d(i)*Ai) * MVL(Aj, Bj, Ai, Bi, h-d(i)) * Ci' )' ;   % Transpose of QR above

            if (d(i) < d(j))
                RR = Ci * expm( (d(j)-d(i)) * Ai) * MVL(Ai, Bi, Aj, Bj, h-d(j)) * Cj' ;
            else
                RR = Ci * MVL(Ai, Bi, Aj, Bj, h-d(i)) * expm( (d(i)-d(j)) * Ai') * Cj' ;
            end

            BBij = [QQ, QR;
                    RQ, RR];

            BBi = [BBi BBij];
        else
            Aj = phi{j+1}{1};
            Bj = phi{j+1}{2};
            Cj = phi{j+1}{3};

            % position of this block BBij
            sc = size(BBi, 2) + 1;          % Starting column
            wc = size(Aj,1) + size(Cj,1);   % Number of column in this block
            sr = size(BB, 1) + 1;           % Starting row
            wr = size(Ai,1) + size(Ci,1);   % Number of row in this block

            % To save computation, we use Delta_ji'
            BBi = [BBi BB(sc:(sc+wc-1), sr:(sr+wr-1))'];
        end
    end

    BB = [BB; BBi];
end

% column 0 of BB, except the first block Q0*Q0'
BB0 = [];

A0 = phi{1}{1};
B0 = phi{1}{2};
C0 = phi{1}{3};

for i = 1:N
    Ai = phi{i+1}{1};
    Bi = phi{i+1}{2};
    Ci = phi{i+1}{3};

    QQ = MVL(A0, B0, Ai, Bi, h);
    QR = expm(d(i)*Ai) * MVL(A0, B0, Ai, Bi, h-d(i)) * Ci' ;

    BB0 = [BB0 QQ QR];
end

QQ0 = MVL(A0, B0, A0, B0, h);

BB = [QQ0   BB0;
      BB0'  BB];

Bd = real(sqrtm(BB));


text:
function [r, s, t] = xyztorst(X, Y, Z)

% function [r,s,t] = xyztorst(x, y, z)
% Purpose : Transfer from (x,y,z) in equilateral tetrahedron
%           to (r,s,t) coordinates in standard tetrahedron

v1 = [-1,-1/sqrt(3), -1/sqrt(6)]; v2 = [ 1,-1/sqrt(3), -1/sqrt(6)];
v3 = [ 0, 2/sqrt(3), -1/sqrt(6)]; v4 = [ 0, 0/sqrt(3),  3/sqrt(6)];

% back out right tet nodes
rhs = [X';Y';Z'] - 0.5*(v2'+v3'+v4'-v1')*ones(1,length(X));
A = [0.5*(v2-v1)',0.5*(v3-v1)',0.5*(v4-v1)'];
RST = A\[rhs];
r = RST(1,:)'; s = RST(2,:)'; t = RST(3,:)';
return;

repo: Aero-matlab


text:
%% This script builds a Ground Truth file with all the true labels assigned
%   to the "objects" structure.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% PARAMETERS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

volume_path = '/Volumes/SHARED HD/';
% volume_path = 'D:/';
% volume_path = '/media/lifelogging/';

% path_folders = [volume_path 'Video Summarization Project Data Sets/PASCAL'];
% folders = { 'VOCtrainval_06-Nov-2007\VOCdevkit\VOC2007\Annotations', ...
%             'VOCtest_06-Nov-2007\VOCdevkit\VOC2007\Annotations'};
% path_features = {[volume_path 'Video Summarization Objects/Features/Data PASCAL_07']};

% path_folders = [volume_path 'Shared SSD/Object Discovery Data/Video Summarization Project Data Sets/PASCAL_12/VOCdevkit/VOC2012/'];
path_folders = [volume_path 'Video Summarization Project Data Sets/PASCAL_12_test/VOCdevkit/VOC2012/'];
% path_folders = [volume_path '/Video Summarization Project Data Sets/MSRC'];
folders = {'Annotations'};

% path_folders = [volume_path 'Video Summarization Project Data Sets/Narrative_Dataset'];
% folders = {'Petia1/Annotations', 'Petia2/Annotations', 'Maya1/Annotations', 'Maya2/Annotations', ...
%     'Estefania1/Annotations', 'Estefania2/Annotations', 'Mariella1/Annotations', 'Mariella2/Annotations'};

% path_features = {[volume_path 'Video Summarization Objects/Features/Data PASCAL_12 Ferrari']};
path_features = {[volume_path 'Video Summarization Objects/Features/Data PASCAL_12_test']};
% path_features = {[volume_path 'Video Summarization Objects/Features/Data MSRC BING']};
% path_features = {[volume_path 'Video Summarization Objects/Features/Data Narrative_Dataset MCG']};

threshold_detection = 0.5;

% selects if the annotation files are from PASCAL or from the custom labeling
% app.
annoType = 'PASCAL'; % 'PASCAL' or 'CUSTOM' or 'MSRC' or 'LABELME'

% list of allowed GT labels
limitAllowed = false;
% allowed = {'hand', 'mobilephone', 'tvmonitor', 'person'};
allowed = {'lamp', 'aircon', 'cupboard', 'tvmonitor', 'door', 'face', ...
    'person', 'sign', 'hand', 'window', 'building', 'paper', 'bottle', ...
    'glass', 'chair', 'mobilephone', 'car'};

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% EXECUTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Load objects file
disp('# LOADING OBJECTS file...');
load([path_features{1} '/objects.mat']);
offset = 0;

nFolders = length(folders);
for i = 1:nFolders

    %% List all .xml files with annotations
    disp('# LISTING all annotations files');
    annotations = dir([path_folders '/' folders{i} '/*.xml']);

    %% Check annName and objName are the same
    lenAnn = length(annotations);
    countAnn = 1;
    disp('# READING OBJECTS...');
    for j = 1:lenAnn
        objName = regexp(objects(j+offset).imgName, '\.', 'split');
        if(strcmp(annoType, 'CUSTOM'))
            annName = {['img' num2str(str2num(objName{1})+1)]};

            %% Read xml
            xmlContent = fileread([path_folders '/' folders{i} '/' annName{1} '.xml']);
            objs = regexp(xmlContent, '<object>', 'split');
        elseif(strcmp(annoType, 'PASCAL') || strcmp(annoType, 'MSRC') || strcmp(annoType, 'LABELME'))
            annName = regexp(annotations(j).name, '\.', 'split');

            %% Read xml
            xmlContent = fileread([path_folders '/' folders{i} '/' annotations(j).name]);
            objs = regexp(xmlContent, '<object>', 'split');
        end

        % if both names are the same
        if(strcmp(objName{1}, annName{1}) || strcmp(annoType, 'CUSTOM'))
            %% Insert ground truth into object struct
            objects(j+offset).ground_truth = struct('name', [], 'pose', [], 'truncated', [], ...
                'difficult', [], 'ULx', [], 'ULy', [], 'BRx', [], 'BRy', []);

            %% Initialize object candidates
            nObjs = length(objects(j+offset).objects);
            for k = 1:nObjs
                objects(j+offset).objects(k).OS = zeros(1, length({objs{2:end}}));
                objects(j+offset).objects(k).trueLabel = 'No Object';
                objects(j+offset).objects(k).trueLabelId = [];
            end

            %% For each object
            count_obj = 1;
            for obj = {objs{2:end}}
                %% Limit allowed GT classes
                if(~limitAllowed || sum(ismember(allowed, getElementXML(obj{1}, 'name'))))
                    %% Get all attributes
                    objects(j+offset).ground_truth(count_obj).name = getElementXML(obj{1}, 'name');
                    if(strcmp(annoType, 'LABELME')) % different annotation if comes from LabelMe
                        [xmin, ymin, xmax, ymax] = getObjectData(obj{1});
                        objects(j+offset).ground_truth(count_obj).ULx = xmin;
                        objects(j+offset).ground_truth(count_obj).ULy = ymin;
                        objects(j+offset).ground_truth(count_obj).BRx = xmax;
                        objects(j+offset).ground_truth(count_obj).BRy = ymax;
                        objects(j+offset).ground_truth(count_obj).occluded = str2num(getElementXML(obj{1}, 'occluded'));
                    else
                        objects(j+offset).ground_truth(count_obj).ULx = str2num(getElementXML(obj{1}, 'xmin'));
                        objects(j+offset).ground_truth(count_obj).ULy = str2num(getElementXML(obj{1}, 'ymin'));
                        objects(j+offset).ground_truth(count_obj).BRx = str2num(getElementXML(obj{1}, 'xmax'));
                        objects(j+offset).ground_truth(count_obj).BRy = str2num(getElementXML(obj{1}, 'ymax'));
                        if(strcmp(annoType, 'PASCAL'))
                            objects(j+offset).ground_truth(count_obj).pose = getElementXML(obj{1}, 'pose');
                            objects(j+offset).ground_truth(count_obj).truncated = str2num(getElementXML(obj{1}, 'truncated'));
                            objects(j+offset).ground_truth(count_obj).difficult = str2num(getElementXML(obj{1}, 'difficult'));
                        end
                    end

                    %% Check if any object in objects(j).objects matches
                    %  with the ground_truth for assign them the true label!
                    GT = objects(j+offset).ground_truth(count_obj);
                    GT.height = (GT.BRy - GT.ULy + 1);
                    GT.width = (GT.BRx - GT.ULx + 1);
                    GT.area = GT.height * GT.width;

                    %% Check for each object candidate, if it fits the current true object
                    count_candidate = 1;
                    for w = objects(j+offset).objects

                        % Check area and intersection on current window "w"
                        w.height = (w.BRy - w.ULy + 1);
                        w.width = (w.BRx - w.ULx + 1);
                        w.area = w.height * w.width;

                        % Check intersection
                        count_intersect = rectint([GT.ULy, GT.ULx, GT.height, GT.width], [w.ULy, w.ULx, w.height, w.width]);

                        % Calculate overlap score
                        OS = count_intersect / (GT.area + w.area - count_intersect);

                        if(OS > threshold_detection) % object detected!
                            label = getElementXML(obj{1}, 'name');
                            % If OS bigger than previous, then assign this
                            if(max(w.OS) < OS)
                                w.trueLabel = label;
                                w.trueLabelId = count_obj;
                            end
                        end
                        w.OS(count_obj) = OS;

                        % Store w object
                        objects(j+offset).objects(count_candidate).OS = w.OS;
                        objects(j+offset).objects(count_candidate).trueLabel = w.trueLabel;
                        objects(j+offset).objects(count_candidate).trueLabelId = w.trueLabelId;

                        count_candidate = count_candidate + 1;
                    end
                end

                count_obj = count_obj + 1;
            end

        %% Error, objName != annName
        else
            disp(['>>> ERROR ' num2str(j) ': objName ' objName{1} ', annName ' annName{1}]);
        end

        %% Check progress of annotations readed
        if(mod(countAnn, 100) == 0 || countAnn == lenAnn)
            disp(['Annotation files read: ' num2str(countAnn) '/' num2str(lenAnn)]);
        end
        countAnn = countAnn+1;
    end
    disp(' ');

    offset = offset+lenAnn;
end

%% Save objects
save([path_features{1} '/objects.mat'], 'objects');

disp('Ground Truth building finished.');

author: zhangqianqianQQ

repo: MachineVisionAlgorithm