text:
function de00 = deltaE2000(Labstd,Labsample)
% Based on the article:
% "The CIEDE2000 Color-Difference Formula: Implementation Notes,
% Supplementary Test Data, and Mathematical Observations,", G. Sharma,
% W. Wu, E. N. Dalal, Color Research and Application, vol. 30. No. 1, pp.
% 21-30, February 2005.
% available at http://www.ece.rochester.edu/~/gsharma/ciede2000/
kl = 1; kc=1; kh =1;
Lstd = Labstd(:,1)';
astd = Labstd(:,2)';
bstd = Labstd(:,3)';
Cabstd = sqrt(astd.^2+bstd.^2);
Lsample = Labsample(:,1)';
asample = Labsample(:,2)';
bsample = Labsample(:,3)';
Cabsample = sqrt(asample.^2+bsample.^2);
Cabarithmean = (Cabstd + Cabsample)/2;
G = 0.5* (1 - sqrt( (Cabarithmean.^7)./(Cabarithmean.^7 + 25^7)));
apstd = (1+G).*astd;
apsample = (1+G).*asample;
Cpsample = sqrt(apsample.^2+bsample.^2);
Cpstd = sqrt(apstd.^2+bstd.^2);
Cpprod = (Cpsample.*Cpstd);
zcidx = find(Cpprod == 0);
hpstd = atan2(bstd,apstd);
hpstd = hpstd+2*pi*(hpstd < 0);
hpstd((abs(apstd)+abs(bstd))== 0) = 0;
hpsample = atan2(bsample,apsample);
hpsample = hpsample+2*pi*(hpsample < 0);
hpsample((abs(apsample)+abs(bsample))==0) = 0;
dL = (Lsample-Lstd);
dC = (Cpsample-Cpstd);
dhp = (hpsample-hpstd);
dhp = dhp - 2*pi* (dhp > pi );
dhp = dhp + 2*pi* (dhp < (-pi) );
dhp(zcidx ) = 0;
dH = 2*sqrt(Cpprod).*sin(dhp/2);
Lp = (Lsample+Lstd)/2;
Cp = (Cpstd+Cpsample)/2;
hp = (hpstd+hpsample)/2;
hp = hp - ( abs(hpstd-hpsample)  > pi ) *pi;
hp = hp+ (hp < 0) *2*pi;
hp(zcidx) = hpsample(zcidx)+hpstd(zcidx);
Lpm502 = (Lp-50).^2;
Sl = 1 + 0.015*Lpm502./sqrt(20+Lpm502);
Sc = 1+0.045*Cp;
T = 1 - 0.17*cos(hp - pi/6 ) + 0.24*cos(2*hp) + 0.32*cos(3*hp+pi/30) ...
    -0.20*cos(4*hp-63*pi/180);
Sh = 1 + 0.015*Cp.*T;
delthetarad = (30*pi/180)*exp(- ( (180/pi*hp-275)/25).^2);
Rc =  2*sqrt((Cp.^7)./(Cp.^7 + 25^7));
RT =  - sin(2*delthetarad).*Rc;
klSl = kl*Sl;
kcSc = kc*Sc;
khSh = kh*Sh;
de00 = sqrt( (dL./klSl).^2 + (dC./kcSc).^2 + (dH./khSh).^2 + ...
    RT.*(dC./kcSc).*(dH./khSh) );
return

author: mahmoudnafifi


text:
function  [ output_image, meta ]= read_gff( filename, varargin )
%READ_GFF Sandia GSAT Image File Format
%   complexdata = read_gff( filename, rowrange, colrange, subsample, decimationfun )
%
%   INPUTS:
%      FILENAME:      Input file to read.
%      ROWRANGE:      1x2 array [first row, last row], row #1 is top.
%         Default is entire image range.  Can also use an empty array ([])
%         to specify entire row range.
%      COLRANGE:      1x2 array [first column, last column], column #1 is
%         left side.   Default is entire image range.  Can also use an
%         empty array ([]) to specify entire column range.
%      SUBSAMPLE:     1x2 array [subsample rate in first dimension,
%         subsample ratein second dimension].  Default is [1 1] (no
%         subsampling).
%      DECIMATIONFUN: Decimation function, used if SUBSAMPLE is defined to
%         be greater than 1.  Options include 'none' (default)', 'max',
%         'mean', or any other function defined in Matlab.
%
%   OUTPUTS:
%      COMPLEXDATA:   Array of complex data values of data type single
%         complex.
%      META:          Structure containing metadata
%
%   Author: Wade Schwartzkopf (NGA/IDT)
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

% Read metadata
native_meta = read_gff_meta(filename);
meta=meta2sicd_gff(native_meta);
meta.native.gff=native_meta;
if native_meta.RowMajor
   datasize = [native_meta.RgCnt native_meta.AzCnt];
else
   datasize = [native_meta.AzCnt native_meta.RgCnt];
end
switch native_meta.ImageType
    case 0
        datatype='uchar';
    case 1
        if native_meta.BytesPerPixel == 4 % 2 bytes phase, 2 bytes magnitude
            datatype='uint16';
        else % 8 bytes total, 4 bytes phase, 2 bytes magnitude
            datatype='uint32';
        end
    case 2
        datatype='float32';
end
if native_meta.Endian
    endian='b';
else
    endian='l';
end

% Parse input parameters; reverse indices since image 180 degrees rotated
% from shadows down orientations
newvarargin=varargin;
if nargin>1
    rowrange=datasize(1)-varargin{1}(end:-1:1)+1;
    if native_meta.RowMajor
        newvarargin{2}=rowrange;
        newvarargin{1}=[];
    else
        newvarargin{1}=rowrange;
    end
end
if nargin>2
    colrange=datasize(2)-varargin{2}(end:-1:1)+1;
    if native_meta.RowMajor
        newvarargin{1}=colrange;
    else
        newvarargin{2}=colrange;
    end
end
if nargin>3
    if native_meta.RowMajor
        newvarargin{3}=varargin{3}(end:-1:1);
    end
end

% Read complex data
fid = fopen(filename,'r',endian);
output_image = read_complex(fid,datasize,native_meta.Length,...
    datatype,logical(native_meta.ImageType),newvarargin{:});
fclose(fid);

if native_meta.ImageType==1 % Int types are phase-magnitude, rather than real-imag, which read_complex expects
    output_image=double(imag(output_image)).*exp(1i * double(real(output_image)) * 2*pi/(2^16));
end
if native_meta.RowMajor
    output_image=output_image.';
end
output_image=rot90(output_image,2); % GFF stored shadows up; switch to shadows down

end

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

author: ngageoint


text:
function [dynpcm2] = MPa2dynpcm2(MPa)
% Convert pressure from megapascals to dyn per sq-cm
% Chad Greene 2012
dynpcm2 = MPa*1.00000e+7;

author: Sable

repo: mcbench-benchmarks


text:
function [] = plot_road_network(ax, connectivity_matrix, parsed_osm)
% plot the nodes and edges connecting them
%
% usage
%   PLOT_ROAD_NETWORK(ax, connectivity_matrix, parsed_osm)
%
% input
%   ax = axes object handle.
%   connectivity_matrix = matrix representing the road network
%                         connectivity, as returned by the function
%                         extract_connectivity.
%   parsed_osm = MATLAB structure containing the OpenStreetMap XML data
%                after parsing, as returned by function
%                parse_openstreetmap.
%
%
%
% 2012.04.24 (c) Ioannis Filippidis, jfilippidis@gmail.com
%
% See also EXTRACT_CONNECTIVITY, PARSE_OPENSTREETMAP, ROUTE_PLANNER.

nodes = parsed_osm.node;
node_ids = nodes.id;
node_xys = nodes.xy;

n = size(connectivity_matrix, 2);

held = takehold(ax);
nodelist = [];
for curnode=1:n
    curxy = node_xys(:, curnode);

    % find neighbors
    curadj = connectivity_matrix(curnode, :);
    neighbors = find(curadj == 1);
    neighbor_xy = node_xys(:, neighbors);

    % plot edges to each neighbor
    for j=1:size(neighbor_xy, 2)
        otherxy = neighbor_xy(:, j);
        xy = [curxy, otherxy];
        plotmd(ax, xy)
    end

    % is node connected ?
    if ~isempty(neighbor_xy)
        nodelist = [nodelist, curnode];
    end
end

%plot_nodes(ax, parsed_osm, nodelist)

givehold(ax, held)

author: johnyf

repo: openstreetmap


text:
function [pca_samples,params]=cosmo_pca(samples,retain)
% Principal Component Analysis
%
% [pca_samples,params]=cosmo_pca(samples[,retain])
%
% Input:
%   samples                 M x N  numeric matrix
%   retain                  (optional) number of components to retain;
%                           must be less than or equal to N. Default: N
%
% Output:
%   pca_samples             M x retain samples in Principal Component
%                           space, after samples have been centered
%   params                  struct with fields:
%     .coef                 M x retain Principal Component coefficients
%     .mu                   M x 1 column-wise average of samples
%                           It holds that:
%                             samples=bsxfun(@plus,params.mu,...
%                                                 pca_samples*params.coef')
%     .explained            1 x N Percentage of explained variance
%
%
% Examples:
%     samples=[      2.0317   -0.8918   -0.8258;...
%                    0.5838    1.8439    1.1656;...
%                   -1.4437   -0.2617   -1.9207;...
%                   -0.5177    2.3387    0.4412;...
%                    1.1908   -0.2040   -0.2088;...
%                   -1.3265    2.7235    0.1476];
%     %
%     % apply PCA, keeping two dimensions
%     [pca_samples,params]=cosmo_pca(samples,2);
%     %
%     % show samples in PC space
%     cosmo_disp(pca_samples);
%     %|| [  -2.64     0.654
%     %||    0.923      1.43
%     %||   -0.723     -2.48
%     %||     1.64     0.265
%     %||    -1.46     0.569
%     %||     2.27    -0.438 ]
%     %
%     % show parameters
%     cosmo_disp(params);
%     %|| .coef
%     %||   [ -0.512     0.744
%     %||      0.794     0.219
%     %||      0.328     0.632 ]
%     %|| .mu
%     %||   [ 0.0864     0.925      -0.2 ]
%     %|| .explained
%     %||   [    66
%     %||      33.3
%     %||     0.676 ]
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #

    if nargin<2
        retain=[];
    end

    verify_parameters(samples,retain)
    ndim=get_number_of_components(samples,retain);

    % subtract mean
    mu=mean(samples,1);
    samples_demu=bsxfun(@minus, samples, mu);

    % singular value decomposition
    [u,s,w]=svd(samples_demu,'econ');

    % extract eigen values
    [nrow,ncol]=size(samples);
    samples_is_vector=nrow==1 || ncol==1;
    if samples_is_vector
        % single eigen value
        eigvals=s(1);
    else
        % take diagonal
        eigvals=diag(s);
    end

    if ndim==0
        % seperate case for zero dimensions
        pca_samples=zeros(1,0);
        coef=zeros(ncol,0);
    else
        pca_samples_rand_sign=bsxfun(@times,u(:,1:ndim),eigvals(1:ndim)');
        [coef,sgn]=max_abs_positive_columnwise(w(:,1:ndim));
        pca_samples=bsxfun(@times,pca_samples_rand_sign,sgn);
    end

    % store coefficients
    params=struct();
    params.coef=coef;
    params.mu=mu;

    nexpl=min([nrow-1,ncol]);
    if nrow==1 || ncol==0
        % special case for empty vecto with explained variance
        params.explained=zeros(1,0);
    else
        explained_ratio=eigvals'.^2;
        params.explained=100*explained_ratio(1:nexpl)/sum(explained_ratio);
    end

function ncomp=get_number_of_components(samples,retain)
    max_retain=size(samples,2);

    if isempty(retain)
        retain=max_retain;
    end

    if retain>max_retain
        error('retain argument %d must be less than %d',...
                                retain,max_retain);
    end

    [nrow,ncol]=size(samples);
    ncomp=min([nrow-1,ncol,retain]);

function [coef_pos,sgn]=max_abs_positive_columnwise(coef)
    % swap sign for each column in which the maximum absolute value is
    % negative. sgn contains the sign used in each column (-1 or 1)
    [unused,i]=max(abs(coef),[],1);
    [nrows,ncols]=size(coef);
    mx_idx=(0:(ncols-1))*nrows+i;
    mx=coef(mx_idx);

    sgn=(mx>0)*2-1;
    coef_pos=bsxfun(@times,coef,sgn);

function verify_parameters(samples,retain)
    if ~isnumeric(samples)
        error('samples argument must be numeric');
    end

    if numel(size(samples))>2
        error('samples argument must be a matrix');
    end

    if ~(isempty(retain) || ...
                    (isscalar(retain) && ...
                     retain>0 && ...
                     isequal(round(retain),retain)))
        error('retain argument must be positive integer');
    end

author: CoSMoMVPA

repo: CoSMoMVPA

save_path: github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA


text:
function [ind,ind2,stats] = Gaussian_mix(x,niter,basepts,verbose,doplot, doplot2)
% Two-Gaussian mixture model
%
% :Usage:
% ::
%
%     [ind,ind2,stats] = Gaussian_mix(x,niter,basepts,verbose,doplot, doplot2)
%
% :Inputs:
%
%   **x:**
%        data
%
%   **iter:**
%        number of iterations
%
%   **basepts:**
%        number of baseline pts at start of run. The modal class in the
%        baseline period is defined as the 0-class
%
% :Outputs:
%
%   **ind:**
%        indicator function of class belonging
%
%   **ind2:**
%        indicator function of class belonging where 3 consecutive points
%        are needed to switch states
%
%   **mu:**
%        mean vector
%
%   **sigma:**
%        standard deviation
%
%   **p:**
%        probability that latent class random variable (delta) is equal
%        to [0,1]
%
% :Examples:
% ::
%
%    [ind,ind2,stats] = Gaussian_mix(linear_detrending(dat),20);
%    % dat is n subjects by t time points
%    % plotting is on
%
%    % Simulated data
%    r = normrnd(1, 1, 200, 1); r(1:50) = r(1:50) + normrnd(3, 1, 50, 1);
%    [ind, ind2, stats] = Gaussian_mix(r, 50, [], 0, 1);
%
% We recommend 50 iterations

% ..
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    % Set up inputs
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ..

    if ~(exist('doplot')==1) || isempty(doplot), doplot = 1; end
    if ~(exist('doplot2')==1) || isempty(doplot2), doplot2 = 1; end
    if ~(exist('verbose')==1) || isempty(verbose), verbose = 1; end
    if ~(exist('basepts')==1) || isempty(basepts), basepts = 1:length(x); end

    % make sure it's a column vector or vectors
    if size(x,1) ~= length(x), x = x'; end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    % Iterative mode
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if size(x,2) > 1
        % multiple data vectors, run this function iteratively

        IND = []; IND2 = [];
        verbose = 0;
        if doplot, nrows = ceil(sqrt(size(x,2))); tor_fig(nrows,nrows); end

        for datavec = 1:size(x,2)
            if doplot, subplot(nrows,nrows,datavec);  end

            [IND(:,datavec),IND2(:,datavec),stats(datavec)] = Gaussian_mix(x(:,datavec),niter,basepts,verbose,doplot);
        end

        % save group stats/output

        ind = IND; ind2 = IND2;
        S.cp = cat(1,stats.cp);
        S.cnt = cat(1,stats.cnt);
        S.tot = cat(1,stats.tot);
        S.longest = cat(1,stats.longest);
        S.firstlen = cat(1,stats.firstlen);
        S.totaldur = cat(1,stats.totaldur);
        S.mu = cat(2,stats.mu);
        S.sigma = cat(2,stats.sigma);
        S.p = cat(1,stats.p);
        S.ind2 = IND2;
        S.ind = ind;

        S.cpmean = nanmean(S.cp);
        S.meancnt = mean(S.cnt);
        S.meantot = mean(S.tot);
        S.meantotaldur =  mean(S.totaldur);
        S.meanlongest = mean(S.longest);
        S.meanfirst = mean(S.firstlen);

        ind = mean(IND2')';     % group prob. of activation state
        stats = S;

        if doplot
            % group plot
            tor_fig; plot(ind,'k','LineWidth',2);
            hold on; plot(S.cpmean,ind(round(S.cpmean)),'ko','MarkerSize',12,'MarkerFaceColor',[.5 .5 .5]);
            xlabel('Time (images)'); ylabel('Probability of active state.');
        end

        return
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %

    % Initial values for EM-algorithm

    %

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    n = length(x);

    gam =zeros(n,2);

    p = [0.5 0.5];                      % probability that delta is [0,1]

    %mu = normrnd(0,1,1,2);              % means of Gaussian

    mu = zeros(1,2);
    mu(1) = min(x);
    mu(2) =max(x);

    sigma = zeros(1,1,2);               % covariance matrices

    for i=1:2,

        sigma(:,:,i) = std(x);

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %

    % EM -algorithm - repeat niter times

    %

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if verbose,  fprintf(1,'iteration %03d',0); end

    for t=1:niter,

        if verbose, fprintf(1,'\b\b\b%03d',t); end

        % E-step

        for i=1:2,

            gam(:,i) = p(i)*det(sigma(:,:,i))^(-0.5)*exp(-0.5*sum((x'-repmat(mu(:,i),1,n))'*inv(sigma(:,:,i)).*(x'-repmat(mu(:,i),1,n))',2));

        end

        gam = gam./repmat(sum(gam,2),1,2);            % Normalize

        % M-step

        for i=1:2,

            mu(:,i) = (x'*gam(:,i))./sum(gam(:,i));                                                               % Update mean

            ind = (gam>0.5);
            dev = x-repmat(mu(:,i),n,1);

            sigma(:,:,i) = dev' *(gam(:,i).* dev) ./ sum(gam(:,i));           % Update covariance

            p(i) = mean(gam(:,i));                                                                                % Update probability

        end

        pooleds = sigma(:,:,1).*p(1) + sigma(:,:,2).*p(2);
        sigma(:,:,1:2) = pooleds;

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %

    % Classify points

    %

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    ind = (gam>0.5);

    [a,b]=max(mu);

    % Classify points using 3 consecutive alternate states in order to

    % switch states

    ind2 = zeros(n,1);

    state = 0;

    len = 3;

    for i=1:(length(ind(:,b))-(len-1)),

        if (state == 0),

            if(sum(ind(i:(i+(len-1)),b)) == len),

                state = 1;

            end;

        elseif (state == 1),

            if(sum(ind(i:(i+(len-1)),b)) == 0),

                state = 0;

            end;

        end;

        ind2(i) = state;

    end;

    ind2((length(ind(:,b))-(len-1)):end) = state;

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    % re-format output and do baseline pts.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    ind = ind(:,1) - ind(:,2);
    %ind2 = ind2(:,1) - ind2(:,2);

    % wh is the class number (0 = class #1, 1 = class #2) of the most frequent
    % baseline class
    classes = [0 1];
    wh = [sum(ind2(1:basepts) == 0) sum(ind2(1:basepts) == 1)]; wh = find(wh==max(wh)); wh = wh(1);
    baseclass = classes(wh);    % 0 or 1

    whbase = find(ind2 == baseclass);
    whactive = find(ind2 ~= baseclass);

    % define so that base class is 0, active class is 1
    ind2(whbase) = 0; ind2(whactive) = 1;

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    % output stats and stats on runs
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    stats.cp = find(ind2);  % first point in active state -- CP estimate
    if isempty(stats.cp), stats.cp = NaN;
    else
        stats.cp = stats.cp(1);
    end

    [stats.cnt,stats.tot,lenmat] = cnt_runs(ind2);
    stats.longest = max(lenmat); stats.firstlen = lenmat(1);
    stats.totaldur = find(ind2);
    if isempty(stats.totaldur) || length(stats.totaldur) < 2, stats.totaldur = 0;
    else
        stats.totaldur = stats.totaldur(end) - stats.totaldur(1);
    end
    stats.mu = mu'; stats.sigma = squeeze(sigma); stats.p = p; stats.gam = gam;

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %

    % Plot results

    %

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if doplot

        xx = 1:length(x);

        hold off;
        plot(xx,x,'k','LineWidth',1);
        hold on;

        wh = find(~ind2); xtmp = x; xtmp(wh) = NaN;
        plot(xx,xtmp,'b','LineWidth',2);

        wh = find(ind2);xtmp = x; xtmp(wh) = NaN;
        plot(xx,xtmp,'g','LineWidth',2);

        %plot(ind2,'r','LineWidth',2);

        %axis([0 length(ind) -0.1 1.1])

    end

    if doplot2

        [h, x] = hist(x, ceil(length(x) ./ 5));
        h1 = normpdf(x, stats.mu(1), stats.sigma(1));
        h2 = normpdf(x, stats.mu(2), stats.sigma(2));

        stats.cnt1 = sum(ind > 0);
        stats.cnt2 = sum(ind < 0);

        try
            h1 = moving_average('gaussian', h1', 8)';
            h2 = moving_average('gaussian', h2', 8)';
        catch
            disp('problem with moving average')
        end

        h1 = stats.cnt1 .* h1 ./ sum(h1);
        h2 = stats.cnt2 .* h2 ./ sum(h2);

        create_figure('Gaussian mixture plot');
        plot(x, h, 'k', 'LineWidth', 2);
        hold on;
        plot(x, h1, 'r', 'LineWidth', 2);
        plot(x, h2, 'b', 'LineWidth', 2);

    end

    return

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function [ node_num, tree, tree_data ] = r8btree_node_add ( node_num, tree, ...
  data_num, tree_data, node_data )

%*****************************************************************************80
%
%% R8BTREE_NODE_ADD adds one node to a BTREE.
%
%  Discussion:
%
%    A BTREE is a binary tree.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes in the tree.
%
%    Input, integer TREE(4,NODE_NUM).
%    TREE(1,I), the index in TREE_DATA(1,*) of the coordinate of node I.
%    TREE(2,I), the left child of node I.
%    TREE(3,I), the right child of node I.
%    TREE(4,I), the parent of node I.
%
%    Input, integer DATA_NUM, the number of data items per node.
%
%    Input, real TREE_DATA(DATA_NUM,NODE_NUM), node data.
%
%    Input, real NODE_DATA(DATA_NUM), data associated with the new node.
%
%    Output, integer NODE_NUM, the updated value.
%
%    Output, integer TREE(4,NODE_NUM), the updated value.
%
%    Output, integer TREE_DATA(DATA_NUM,NODE_NUM), the updated value.
%
  if ( node_num <= 0 )
    tree(1:4,1) = [ 1, -1, -1, -1 ];
    tree_data(1:data_num,1) = node_data(1:data_num);
    node_num = 1;
    return
  end

  l = -1;
  m = 1;
  r = -1;
%
%  Divide the current interval [L,R] by the midpoint M.
%  X falls either into [L,M] or [M,R].
%
  x = node_data(1);

  while ( 1 )

    xm = tree_data(1,tree(1,m));
    m_old = m;

    if ( x < xm )
      r = m;
      m = tree(2,m);
      if ( m == - 1 )
        tree(2,m_old) = node_num + 1;
        tree(1,node_num+1) = node_num + 1;
        tree(2,node_num+1) = -1;
        tree(3,node_num+1) = -1;
        tree(4,node_num+1) = m_old;
        tree_data(1:data_num,node_num+1) = node_data(1:data_num);
        node_num = node_num + 1;
        break
      end
    elseif ( xm < x )
      l = m;
      m = tree(3,m);
      if ( m == -1 )
        tree(3,m_old) = node_num + 1;
        tree(1,node_num+1) = node_num + 1;
        tree(2,node_num+1) = -1;
        tree(3,node_num+1) = -1;
        tree(4,node_num+1) = m_old;
        tree_data(1:data_num,node_num+1) = node_data(1:data_num);
        node_num = node_num + 1;
        break
      end
    else
      r = m;
      l = m;
      break
    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text: error('Automatic updates are currently disabled. Please see: https://github.com/plotly/MATLAB-Online for updates.');

author: plotly


text:
function sc = ssd(I,J,SII,SJJ)

% SSD  Sum of Squared Differences coefficient
%   SSD(I,J) computes the SSD score of matrices I and J:
%
%     SSD = 1/N*sum((I-J).^2)
%
%   where N = prod(size(I))
%   and   size(I) = size(J)
%
%   SSD(I,J,SII,SJJ) accepts useful intermediate results
%   that permit to speed up the calculations. These are:
%
%     SII = sum(sum(I.*I))
%     SJJ = sum(sum(J.*J))
%
%   See also PATCHCORR, ZNCC, CENSUS

% (c) 2005 Joan Sola

if size(I) ~= size(J)
    error ('Matrices must be the same size.')
else
    switch nargin
        case {1,2}
            SII = sum(sum(I.*I));
            SJJ = sum(sum(J.*J));
        case 3
            SJJ = sum(sum(J.*J));
    end

    SIJ = sum(sum(I.*J));

    N   = numel(I);

    sc  = sqrt((SII+SJJ-2*SIJ)/(N+eps));

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

%   # START GPL LICENSE

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

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

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
function ppg_filt(up)
%PPG_FILT extracts respiratory signals using various filtering techniques
% from the PPG signal as specified in PC's literature review.
%	            ppg_filt(option, up)
%
%	Inputs:
%		option          the option which has led to this function being used
%       up              universal parameters structure
%
%	Outputs:
%       ...
%

fprintf('\n--- Extracting Respiratory Signals using Filtering Techniques ');
log_int_respSig = 0;             % Has value 1 unless this is a final respiratory signal

for subj = up.paramSet.subj_list

    %% Cycle through each method
    for filt_no = 1 : length(up.al.options.ppg_filt)

        %% Skip if this processing has been done previously
        eval(['save_name = ''ppg', up.paths.filenames.filt '_' up.al.options.ppg_filt{filt_no} ''';']);
        iden_resp_sig_file_ending
        savepath = [up.paths.data_save_folder, num2str(subj), ending];
        exist_log = check_exists(savepath, save_name);
        if exist_log
            continue
        end

        %% Load relevant data
        if ~exist('data', 'var')
            load([up.paths.data_load_folder, up.paths.data_load_filename]);
        end
        % Extract PPG data
        rel_data = data(subj).ppg;
        rel_data.fs = data(subj).ppg.fs;

        %% Filter the raw signal using this method
        respWave = feval(up.al.options.ppg_filt{filt_no}, rel_data, up);

        %% Band-pass filter
        filtered_data = bpf_signal_to_remove_non_resp_freqs(respWave, respWave.fs, up);
        eval([save_name ' = filtered_data;']);

        %% Save processed data
        save_or_append_data

    end

end

end

author: peterhcharlton

repo: RRest


text:
%Naive fanout
%define function from w to x
w=[];
x = tracer(w,'w -> x','dx -> dw','dw -> dx');

%define function from x to s
y = tracer(x,'x -> y','dy -> dx','dx -> dy');  % this does function composition
z = tracer(x,'x -> z','dz -> dx','dx -> dz');  % this does another composition
s = sum_of_functions(w,[1,1],y,z); % this does not do composition

fprintf('naive case: function value:\n');
[v,deriv] = s(1);

fprintf('naive case: gradient:\n');
[g,hess] = deriv(v);
fprintf('naive case: jacobian:\n');
hess(1);
fprintf('\n');

%Correct fanout
w=[];
x = tracer(w,'w -> x','dx -> dw','dw -> dx');

xx=[];
y = tracer(xx,'x -> y','dy -> dx','dx -> dy'); %no composition
z = tracer(xx,'x -> z','dz -> dx','dx -> dz'); %no composition
s = sum_of_functions(x,[1,1],y,z); %this does the composition once

fprintf('corrected: function value:\n');
[v,deriv] = s(1);

fprintf('corrected: gradient:\n');
[g,hess] = deriv(v);
fprintf('corrected: jacobian:\n');
hess(1);
fprintf('\n');

author: nesl


text:
function [At,b,c,K]=fromsdpa(fname)
% readsdpa Reads SDP problem from sparse SDPA-formatted input file.
%    [At,b,c,K] = readsdpa(fname) produces conic optimization problem
%    data, as can be used by sedumi. "fname" contains a full pathname
%    to the SDPA 4.10-formatted file. (SDPA is a stand-alone solver for
%    semidefinite programming, by Fujisawa, Kojima and Nakata.  It is
%    used as a standard format in the collection SDPLIB by Borchers.)
%
%    To read and solve the problem "arch0", you may type
%
%    [At,b,c,K] = readsdpa('arch0.dat-s');
%    [x,y,info] = sedumi(At,b,c,K);
%
%    The above 2 lines assume that arch0.dat-s is somewhere in your MATLAB
%    search path, that it is not compressed, and that you know the extension
%    'dat-s'.  To alleviate these conditions, you may like to use the script
%    GETPROBLEM.
%
% SEE ALSO SeDuMi, getproblem, frompack, prelp.

%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%

fid = fopen(fname, 'r');
if fid == -1
    error('File not found.')
end
%The number of equality constraints is the first number in the file
m='';
while(isempty(m))
    m = fscanf(fid,'%d',1);
    if fgetl(fid) == -1;
        fclose(fid);
        error('Invalid SDPA file. Number of equality constraints not found.')
    end
end
%The number of semidefinite blocks
nblocks = fscanf(fid, '%d', 1);
if isempty(nblocks)
    fclose(fid);
    error('Invalid SDPA file. Number of semidefinite blocks not found.')
end
fgetl(fid);
%The dimension of the blocks
%Negative means diagonal block, we convert that to nonnegative variables
%.,(){} are omitted
dims = sscanf(regexprep(fgetl(fid), '[\.\,(){}]', ' '), '%d', nblocks)';
%Dimensions cannot be 0, and their number must be nblocks
if any(dims == 0) || length(dims) ~= nblocks
    fclose(fid);
    error('Invalid SDPA file. Invalid semidefinite block dimensions.')
end
nblocks = length(dims);
N = -sum(dims(dims<0)) + sum(dims(dims>0).^2);
%Create a vector with the offsets of the blocks.
%Starting with the first component, how many positions later do SDP blocks
%start
%This is one less than K.blkstart (inside sedumi)
%Diagonal and one dimensional blocks are coming first
loffset = 0;
sdpoffset = sum(abs(dims(dims <= 1) ));
offset = zeros(1, nblocks);
for i = 1:nblocks
    if dims(i) <= 1
        offset(i) = loffset;
        loffset = loffset+abs(dims(i));
    else
        offset(i) = sdpoffset;
        sdpoffset = sdpoffset+dims(i)^2;
    end
end
%This is needed so that we can compute where the subsequent columns start
%in a block
stride = dims;
stride(stride<0) = 0;

%Vector b
%,(){} are omitted
b = sscanf(regexprep(fgetl(fid),'[\,(){}]',' '),'%f',m);
if length(b) ~= m
    fclose(fid);
    error('Invalid SDPA file. The right-hand side vector is not of the right dimension.')
end
%If b is very sparse then we store it as sparse
if nnz(b)/m < 0.1
    b=sparse(b);
end

%Coefficients
%It is much faster to get all the numbers at once than to read the file
%line by line
try
    E = fscanf(fid,'%d %d %d %d %f',[5. inf]);
catch
    fclose(fid);
    error('Invalid SDPA file. Error reading the coefficients.')
end
fclose(fid);
%We are done with the file

%Extract the objective
cE = E(:,E(1,:)==0);

%Repeating indices in the sparse matrix structure create the sum of
%elements, we need to clear one for the diagonals
data2 = cE(5,:);
data2(cE(3,:)==cE(4,:)) = 0;
%we need the minus sign because the SDPA format assumes maximization while
%SeDuMi uses minimization by default
%This magic reshuffles the coefficients to the right place
c = -sparse([offset(cE(2,:))+(cE(3,:)-1).*stride(cE(2,:))+cE(4,:),offset(cE(2,:))+(cE(4,:)-1).*stride(cE(2,:))+cE(3,:)],...
    1,...
    [cE(5,:),data2],...
    N,1);
clear cE data2

%Get rid of the objective coefficients from E
AtE = E(:,E(1,:)~=0);
clear E
%Take all the coefficients
data2 = AtE(5,:);
%The coefficients for the diagonal elements in the blocks
data2(AtE(3,:)==AtE(4,:)) = 0;
At = sparse([offset(AtE(2,:))+(AtE(3,:)-1).*stride(AtE(2,:))+AtE(4,:),offset(AtE(2,:))+(AtE(4,:)-1).*stride(AtE(2,:))+AtE(3,:)],...
    [AtE(1,:),AtE(1,:)],...
    [AtE(5,:),data2],...
    N,m);
clear AtE data2

K.l = -sum(dims(dims<0)) + sum(dims==1);
K.s = dims(dims>1);

%Finally, let us correct the sparsity
%c and At are always stored as sparse
[i,j,v] = find(c);
c = sparse(i,1,v,N,1);
[i,j,v] = find(At);
At = sparse(i,j,v,N,m);

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
% vectdata() - vector data interpolation with optional moving
%              average.
%
% Usage:
%   >> [interparray timesout] = vectdata( array, timesin, 'key', 'val', ... );
%
% Inputs:
%   array      - 1-D or 2-D float array. If 2-D, the second dimension
%                only is interpolated.
%   timesin    - [float vector] time point indices. Same dimension as
%                the interpolated dimension in array.
%
% Optional inputs
%   'timesout' - [float vector] time point indices for interpolating
%                data.
%   'method'   - method for interpolation
%        'linear'    -> Triangle-based linear interpolation (default).
%        'cubic'     -> Triangle-based cubic interpolation.
%        'nearest'   -> Nearest neighbor interpolation.
%        'v4'        -> MATLAB 4 griddata method.
%   'average'  - [real] moving average in the dimension of timesin
%                note that extreme values might be inacurate (see 'borders').
%                Default none or [].
%   'avgtype'  - ['const'|'gauss'] use a const value when averaging (array of
%                ones) or a gaussian window. Default is 'const'.
%   'border'   - ['on'|'off'] correct border effect when smoothing.
%                default is 'off'.
%
% Outputs:
%   interparray - interpolated array
%   timesout    - output time points
%
% Author: Arnaud Delorme, CNL / Salk Institute, 20 Oct 2002
%
% See also: griddata()

% Copyright (C) 2002 Arnaud Delorme, Salk Institute, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [interparray, timesout] = vectdata( array, timevect, varargin );

if nargin < 3
    help vectdata;
    return;
end;

g = finputcheck( varargin, { 'timesout'   'real'  []           [];
                             'average'    'real'  []           [];
                             'gauss'      'real'  []           [];
                             'border'     'string' { 'on' 'off' } 'off';
                             'avgtype'    'string' { 'const' 'gauss' } 'const';
                             'method'     'string' { 'linear' 'cubic' 'nearest' 'v4' } 'linear'});
if isstr(g), error(g); end;

if size(array,2) == 1
    array = transpose(array);
end;

if ~isempty(g.average)
    timediff = timevect(2:end) -timevect(1:end-1);
    if any( (timediff - mean(timediff)) > 1e-8 ) % not uniform values
        fprintf('Data has to be interpolated uniformly for moving average\n');
        minspace = mean(timediff);
        newtimevect = linspace(timevect(1), timevect(end), ceil((timevect(end)-timevect(1))/minspace));
        array = interpolate( array, timevect, newtimevect, g.method);
        timevect = newtimevect;
    end;
    oldavg = g.average;
    g.average = round(g.average/(timevect(2)-timevect(1)));
    if oldavg ~= g.average
        fprintf('Moving average updated from %3.2f to %3.2f (=%d points)\n', ...
                oldavg, g.average*(timevect(2)-timevect(1)), g.average);
    end;
    if strcmpi(g.border, 'on')
        if strcmpi(g.avgtype, 'const')
            array = convolve(array, ones(1, g.average));
        else
            convolution = gauss2d(1,g.average,1,round(0.15*g.average));
            array = convolve(array, convolution);
        end;
    else
        if strcmpi(g.avgtype, 'const')
            array = conv2(array, ones(1, g.average)/g.average, 'same');
        else
            convolution = gauss2d(1,g.average,1,round(0.15*g.average));
            array = conv2(array, convolution/sum(convolution), 'same');
        end;
    end;
end;

interparray = interpolate( array, timevect, g.timesout, g.method);
timesout = g.timesout;

% interpolation function
% ----------------------
function [interparray] = interpolate( array, timesin, timesout, method);
    interparray = zeros(size(array,1), length(timesout));
    for index = 1:size(array,1)
        tmpa = [array(index,:) ; array(index,:)];

        [Xi,Yi,Zi] = griddata(timesin, [1 2]', tmpa, timesout, [1 2]', method); % Interpolate data
        interparray(index,:) = Zi(1,:);
    end;

author: PatternRecognition

repo: OpenBMI


text:
% Scipt: view_fast.m
[mCat1 mCat2 fPer1e fPer2e fPer1,  fPer2] = ex_SplitCatalog(a, 1983.33, 1, 1, 1, 1);
[mLMagsig mHMagsig fLZmax fLZmean fLZmin fHZmax fHZmean,  fHZmin] = plot_Magsig(mCat1, mCat2 , fPer1, fPer2, 0.1);

author: CelsoReyes


text:
function pass = test_BartelsStewart( pref )
% Test generalized Sylvester matrix equation solver

if ( nargin < 1 )
    pref = chebfunpref();
end
tol = 1e4*pref.cheb2Prefs.chebfun2eps;

n = 10;
rng(0)
A = rand(n);
B = rand(n);
C = rand(n);
D = rand(n);
X = rand(n);

E = A * X * B.' + C * X * D.';

Y = chebop2.bartelsStewart(A, B, C, D, E, 0, 0);
pass(1) = norm( Y - X ) < tol;

A = rand(n) + 1i*rand(n);
B = rand(n) + 1i*rand(n);
C = rand(n) + 1i*rand(n);
D = rand(n) + 1i*rand(n);
X = rand(n) + 1i*rand(n);

E = A * X * B.' + C * X * D.';

Y = chebop2.bartelsStewart(A, B, C, D, E, 0, 0);
pass(2) = norm( Y - X ) < 10*tol;

tol = 1000*tol;
n = 100;
rng(0)
A = rand(n);
B = rand(n);
C = rand(n);
D = rand(n);
X = rand(n);

E = A * X * B.' + C * X * D.';

Y = chebop2.bartelsStewart(A, B, C, D, E, 0, 0);
pass(3) = norm( Y - X ) < 10*tol;

A = rand(n) + 1i*rand(n);
B = rand(n) + 1i*rand(n);
C = rand(n) + 1i*rand(n);
D = rand(n) + 1i*rand(n);
X = rand(n) + 1i*rand(n);

E = A * X * B.' + C * X * D.';

Y = chebop2.bartelsStewart(A, B, C, D, E, 0, 0);
pass(4) = norm( Y - X ) < 10*tol;

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
AU_dir = 'D:/Databases/DISFA/ActionUnit_Labels/';

aus = [1,2,4,5,6,9,12,15,17,20,25,26];

subjects = dir([AU_dir, 'SN*']);

% Store all of the AU directories in a cell
input_label_dirs = cell(numel(subjects), 1);
for i=1:numel(subjects)
    input_label_dirs{i} = [AU_dir, subjects(i).name, '/', subjects(i).name];
end

for user=1:numel(subjects)

    testing_label_files = input_label_dirs(user);

    training_label_files = setdiff(input_label_dirs, testing_label_files);

    training_labels_all = [];

    testing_labels_all = [];

    % First extract AU information
    for au=aus

        % Extract all of the AUs from the current user
        [training_labels, training_vid_inds_all, training_frame_inds_all] = extract_au_labels(training_label_files, au);
        [testing_labels, testing_vid_inds_all, testing_frame_inds_all] = extract_au_labels(testing_label_files, au);

        training_labels_all = cat(2, training_labels_all, training_labels);
        testing_labels_all = cat(2, testing_labels_all, testing_labels);

    end

    % File lists for each of the AUs
    for au_ind=1:numel(aus)

        % extract the interesting frames for training, the interesting ones
        % are the AU

        positive_samples = training_labels_all(:,au_ind) > 0;

        active_samples = sum(training_labels_all,2) > 10;

        % Remove neighboring images as they are not very informative
        negative_samples = sum(training_labels_all,2) == 0;
        neg_inds = find(negative_samples);
        neg_to_use = randperm(numel(neg_inds));
        % taking a number of neutral samples that bring the positive and
        % negative samples to a balanced level
        neg_to_use = neg_inds(neg_to_use(1:(2*sum(positive_samples) - sum(active_samples | positive_samples))));
        negative_samples(:) = false;
        negative_samples(neg_to_use) = true;

        % Collect all the data for training now
        training_samples = positive_samples | active_samples | negative_samples;

        % Create a training file list file
        f_train_file_list = fopen(sprintf('%s/%s_au%02d_filelist_train.txt', 'single_au_class', subjects(user).name, aus(au_ind)), 'w');

        sample_inds_train = find(training_samples);

        for sample_ind = sample_inds_train'

            img_file_l = sprintf('../../LeftVideo%s_comp/frame_det_%06d.png', training_vid_inds_all{sample_ind}, training_frame_inds_all(sample_ind));
            img_file_r = sprintf('../../RightVideo%s_comp/frame_det_%06d.png', training_vid_inds_all{sample_ind}, training_frame_inds_all(sample_ind));

            au_class = training_labels_all(sample_ind, au_ind) > 1;

            fprintf(f_train_file_list, '%s %d\r\n', img_file_l, au_class);
            fprintf(f_train_file_list, '%s %d\r\n', img_file_r, au_class);

        end
        fclose(f_train_file_list);

         % Create a testing file list file
        f_train_file_list = fopen(sprintf('%s/%s_au%02d_filelist_test.txt', 'single_au_class', subjects(user).name, aus(au_ind)), 'w');

        testing_samples = true(size(testing_labels_all,1),1);
        sample_inds_test = find(testing_samples);

        for sample_ind = sample_inds_test'

            img_file_l = sprintf('../../LeftVideo%s_comp/frame_det_%06d.png', testing_vid_inds_all{sample_ind}, testing_frame_inds_all(sample_ind));
            img_file_r = sprintf('../../RightVideo%s_comp/frame_det_%06d.png', testing_vid_inds_all{sample_ind}, testing_frame_inds_all(sample_ind));

            au_class = testing_labels_all(sample_ind, au_ind) > 1;

            fprintf(f_train_file_list, '%s %d\r\n', img_file_l, au_class);
            fprintf(f_train_file_list, '%s %d\r\n', img_file_r, au_class);

        end
        fclose(f_train_file_list);

    end

end

author: TadasBaltrusaitis

repo: OpenFace


text:
% fir_filterdcpadded() - Pad data with DC constant and filter
%
% Usage:
%   >> data = fir_filterdcpadded(b, a, data, causal);
%
% Inputs:
%   b             - vector of filter coefficients
%   a             - 1
%   data          - raw data (times x chans)
%   causal        - boolean perform causal filtering {default 0}
%   usefftfilt    - boolean use fftfilt instead of filter
%
% Outputs:
%   data      - smoothed data
%
% Note:
%   firfiltdcpadded always operates (pads, filters) along first dimension.
%   Not memory optimized.
%
% Author: Andreas Widmann, University of Leipzig, 2014

%123456789012345678901234567890123456789012345678901234567890123456789012

% Copyright (C) 2013 Andreas Widmann, University of Leipzig, widmann@uni-leipzig.de
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
%
% $Id$

function [ data ] = fir_filterdcpadded(b, a, data, causal, usefftfilt)

% Defaults
if nargin <= 4 || isempty(usefftfilt)
  usefftfilt = 0;
end
if nargin <= 3 || isempty(causal)
  causal = 0;
end

% Check arguments
if nargin < 3
  ft_error('Not enough input arguments.');
end

% Is FIR?
if ~isscalar(a) || a ~= 1
  ft_error('Not a FIR filter. onepass-zerophase and onepass-minphase filtering is available for FIR filters only.')
end

% Group delay
if mod(length(b), 2) ~= 1
  ft_error('Filter order must be a real, even, positive integer.');
end
groupDelay = (length(b) - 1) / 2;

if causal == 0
  % Filter symmetry, add a check with some numeric tolerance, needed if the
  % filter coefficients are computed using the compat functions
  isSym     = all(b(1:groupDelay)  ==  b(end:-1:groupDelay + 2));
  isAntisym = all([b(1:groupDelay) == -b(end:-1:groupDelay + 2) b(groupDelay + 1) == 0]);

  % the filter should be either symmetric or antisymmetric: the check above
  % requires exact numeric anti-/symmetry. The compat drop in replacements
  % have some numeric inaccuracies, close to eps, so we might be a bit
  % lenient here
  if ~isSym && isalmostequal(b(1:groupDelay), b(end:-1:groupDelay + 2), 'abstol', eps*10)
    ft_warning('Filter coefficients are nearly symmetric, making them explicitly symmetric');
    bold = b;
    b(1:groupDelay)          = ( bold(1:groupDelay) + bold(end:-1:groupDelay + 2) )./2;
    b(end:-1:groupDelay + 2) = ( bold(1:groupDelay) + bold(end:-1:groupDelay + 2) )./2;
  end
  isSym     = all(b(1:groupDelay)  ==  b(end:-1:groupDelay + 2));

  if ~isAntisym && isalmostequal(b(1:groupDelay), -b(end:-1:groupDelay + 2), 'abstol', eps*10) && isalmostequal(b(groupDelay + 1), 0, 'abstol', eps*10)
    ft_warning('Filter coefficients are nearly antisymmetric, making them explicitly antisymmetric');
    bold = b;
    b(1:groupDelay)          =  ( bold(1:groupDelay) - bold(end:-1:groupDelay + 2) )./2;
    b(end:-1:groupDelay + 2) = -( bold(1:groupDelay) - bold(end:-1:groupDelay + 2) )./2;
  end
  isAntisym = all([b(1:groupDelay) == -b(end:-1:groupDelay + 2) b(groupDelay + 1) == 0]);

  if ~(isSym || isAntisym)
    ft_error('Filter is not anti-/symmetric. For onepass-zerophase filtering the filter must be anti-/symmetric.')
  end
end

% Padding
if causal
  startPad = repmat(data(1, :), [2 * groupDelay 1]);
  endPad = [];
else
  startPad = repmat(data(1, :), [groupDelay 1]);
  endPad = repmat(data(end, :), [groupDelay 1]);
end

% Filter data (with double precision)
isSingle = isa(data, 'single');

if usefftfilt
  data = fftfilt(double(b), double([startPad; data; endPad]));
else
  data = filter(double(b), 1, double([startPad; data; endPad])); % Pad and filter with double precision
end

% Convert to single
if isSingle
  data = single(data);
end

% Remove padded data
data = data(2 * groupDelay + 1:end, :);

end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
%SerialLink.issym Test if SerialLink object is a symbolic model
%
% res = R.issym() is true if the SerialLink manipulator R has symbolic parameters
%
%
% Authors::
%  Joern Malzahn, (joern.malzahn@tu-dortmund.de)

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

	res = issym(l.links(1));

end

author: petercorke

repo: robotics-toolbox-matlab


text:
function X = not(X)
% Internal class for constraint list

superiorto('sdpvar');
superiorto('double');

% Try to evaluate

if length(X.List)>3
    error('Negation can only be applied to BINARY relations')
else
    switch X.List{2}
        case '<'
            X.List{2} = '>';
            X.Evaluated{1} = -X.Evaluated{1};
        case '>'
            X.List{2} = '<';
            X.Evaluated{1} = -X.Evaluated{1};
        case '=='
            % A simple inequality has to be converted to an expression which
            % most likely will be a mixed-integer model....
            X = X.List{1} ~= X.List{3};
        otherwise
            error('Negation cannot be applied on this operator')
    end
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
filename='Cantilever_hexahedra_coarse';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance';'perimeter'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
optimizer = 'PROJECTED GRADIENT';
incrementFactor = 1;
designVariable = 'Density';
filterType = 'P1';

nsteps = 5;
Vfrac_final = 0.1;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-2;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
    camera = AxisWebCamera('http://wc2.dartmouth.edu');
    im = camera.grab();
    idisp(im)
    clear camera

repo: machinevision-toolbox-matlab


text:
%%*************************************************************************
%% sqlparameters.m: set OPTIONS structure to specify default
%%                  parameters for sqlp.m
%%
%% OPTIONS.vers        : version of direction to use.
%%                       1 for HKM direction
%%                       2 for NT direction
%%                       0 for the default (which uses the HKM direction if
%%                       semidefinite blocks exist; and NT direction of SOCP problms)
%% OPTIONS.gam         : step-length parameter,
%% OPTIONS.predcorr    : whether to use Mehrotra predictor-corrector.
%% OPTIONS.expon       : exponent in decrease of centering parameter sigma.
%% OPTIONS.gaptol      : tolerance for duality gap as a fraction of the
%%                       value of the objective functions.
%% OPTIONS.inftol      : tolerance for stopping due to suspicion of
%%                       infeasibility.
%% OPTIONS.steptol     : toloerance for stopping due to small steps.
%% OPTIONS.maxit       : maximum number of iteration allowed
%% OPTIONS.printlevel  : 3, if want to display result in each iteration,
%%                       2, if want to display only summary,
%%                       1, if want to display warning message,
%%                       0, no display at all.
%% OPTIONS.stoplevel   : 2, if want to automatically detect termination;
%%                       1, if want to automatically detect termination, but
%%                          restart automatically with a new iterate
%%                          when the algorithm stagnants because of tiny step-lengths.
%%                       0, if want the algorithm to continue forever except for
%%                          successful completion, maximum number of iterations, or
%%                          numerical failures. Note, do not change this field unless
%%                          you very sure.
%% OPTIONS.scale_data  : 1, if want to scale the data before solving the problem,
%%                          else = 0
%% OPTIONS.rmdepconstr : 1, if want to remove nearly dependent constraints,
%%                          else = 0.
%% OPTIONS.smallblkdim : block-size threshold determining what method to compute the
%%                       schur complement matrix corresponding to semidefintie block.
%%                       NOTE: this number should be small, say less than 20.
%% OPTIONS.parbarrier  : parameter values of the log-barrier terms in the SQLP problem.
%%                       Default = [],  meaning that the parameter values are all 0.
%% OPTIONS.schurfun    : [], if no user supplied routine to compute the Schur matrix,
%%                       else, it is a cell array where each cell is either [],
%%                       or contains a string that is the file name where the Schur matrix
%%                       of the associated block data is computed.
%%                       For example, if the SQLP data has the block structure
%%                       blk{1,1} = '1'; blk{1,2} = 10;
%%                       blk{2,1} = 's'; blk{2,2} = 50;
%%                       and
%%                       OPTIONS.schurfun{1} = [];
%%                       OPTIONS.schurfun{2} = 'myownschur', where
%%                             'myownschur' is a function with the calling sequence:
%%                              function   schur = myownschur(X2,Z2inv,schurfun_par(2,:));
%%                       This means that for the first block, the Schur
%%                       matrix is computed by the default method in SDPT3,
%%                       and for the second block, the user supplies the
%%                       routine to compute the associated Schur matrix.
%% OPTIONS.schurfun_par: [], if no user supplied routine to compute the Schur matrix,
%%                       else, it is a cell array where the p-th row is either [],
%%                       or is a cell array containing the parameters needed in
%%                       the user supplied Schur routine OPTIONS.schurfun{p}.
%%                       For example, for the block structure described
%%                       above, we may have:
%%                       OPTIONS.schurfun_par{1} = [];
%%                       OPTIONS.schurfun_par{2,1} = par1;
%%                       OPTIONS.schurfun_par{2,2} = par2;
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

   function OPTIONS = sqlparameters

   OPTIONS.vers           = 0;
   OPTIONS.gam            = 0;
   OPTIONS.predcorr       = 1;
   OPTIONS.expon          = 1;
   OPTIONS.gaptol         = 1e-8;
   OPTIONS.inftol         = 1e-8;
   OPTIONS.steptol        = 1e-6;
   OPTIONS.maxit          = 100;
   OPTIONS.printlevel     = 3;
   OPTIONS.stoplevel      = 1; %% do not change this field unless you very sure.
   OPTIONS.scale_data     = 0;
   OPTIONS.spdensity      = 0.4;
   OPTIONS.rmdepconstr    = 0;
   OPTIONS.smallblkdim    = 50;
   OPTIONS.parbarrier     = [];
   OPTIONS.schurfun       = [];
   OPTIONS.schurfun_par   = [];
%%*************************************************************************

author: shamilmamedov


text:
function y=comb(x)

% This function is used to create all possible combinations
% of Input Term Nodes Outputs to be fed into the Rule Nodes.
% Each combination is fed to a single rule neuron responsible
% for the processing of this specific combination.

[rows columns] = size(x);

y = zeros(columns^rows,rows);

for i=1:rows

    if i<=rows-1

      j=1;

      for m=0:columns^(rows-i):(columns^rows - columns^(rows-i))

        if j<=columns

             for l=1:columns^(rows-i)
                      y(m+l,i) = x(i,j);
             end

         else

            j=1;
             for l=1:columns^(rows-i)
                     y(m+l,i) = x(i,j);
             end

         end

         j = j + 1;

      end

    elseif i==rows

        for m=0:columns:(columns^rows - columns)

            j=1;
            for l=1:columns
                y(m+l,i) = x(i,j);
                j=j+1;
            end
        end

    end    % end of "if i" loop.

end      % end of " for i" loop.

author: Sable


text:
function [B, L] = greedyExtremePoolBasis(model)
% Computes a non-negative basis for the left nullspace of the stoichiometric
% matrix using optimization to pick random extreme rays, then test a
% posteriori if each is linearly independent from the existing stored
% extreme rays.
%
% USAGE:
%
%    [B, L] = greedyExtremePoolBasis(model)
%
% INPUT:
%    model:    model structure
%
% OUTPUTS:
%    B, L:     non-negative basus fi the left nullspace

[inform,molecularVector]=checkStoichiometricConsistency(model,0); %check stoichiometric consistency
if inform~=1 %check if positive vector in left nullspace
    B=[];
    L=[]; % Returning empty vector for left nullspace so if it is expected matlab will keep running
    return;
end

[nMet,nRxn]=size(model.S);

%compute linear basis for left nullspace
printLevelL=0;
[L,rankS]=getNullSpace(model.S',printLevelL);
L=L';

B=sparse(nMet-rankS,nMet);

nPools=0;
nTry=0;
tic;
while nPools < (nMet-rankS)
    [x, output] = findExtremePool(model);
    B(nPools+1,:)=x';
    if nPools==0
        rankB=1;
    else
        nonZeroColumns=(B~=0);
        nonZeroColumns=sum(nonZeroColumns,1);
        rankB = getRankLUSOL(B(1:nPools+1,nonZeroColumns~=0));
        % %error as reports wrong rank if zero columns
        % rankB = getRankLUSOL(B(1:nPools+1,:));
    end
    if rankB==(nPools+1)
        nPools=nPools+1;
        fprintf('%s\n',[int2str(nPools) ' of ' int2str(nMet-rankS) ' linearly independent pool vectors, at time ' num2str(toc)]);
    else
        % fprintf('%s\n','Linearly dependent pool vector discarded');
    end
    nTry=nTry+1;
    if toc > 100
        B=B(end-1,:);
        fprintf('%s%u%s\n','Only ',nPools, ' computed.');
        break
    end
end
fprintf('%s%g\n','Hit fraction ',(nMet-rankS)/nTry);

author: opencobra

repo: cobratoolbox


text:
function connectSparse = Graph2Connection(UNFOLD)
%
%   connectSparse = Graph2Connection(UNFOLD)
%
% AUTHOR:  Wandell
% DATE:   09.06.99
% PURPOSE:
%    Create a sparse matrix of the connections in a gray graph.
%
%

nodes = UNFOLD.nodes;
edges = UNFOLD.edges;

numNodes = size(nodes,2);
connectSparse = sparse(numNodes,numNodes);

for ii=1:numNodes
  l1 = mrUGetNeighbors(UNFOLD,ii);
  connectSparse(ii,l1) = 1;
end

return;

% Debug
%

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [mu sigma2] = estimateGaussian(X)
%ESTIMATEGAUSSIAN This function estimates the parameters of a
%Gaussian distribution using the data in X
%   [mu sigma2] = estimateGaussian(X),
%   The input X is the dataset with each n-dimensional data point in one row
%   The output is an n-dimensional vector mu, the mean of the data set
%   and the variances sigma^2, an n x 1 vector
%

% Useful variables
[m, n] = size(X);

% You should return these values correctly
mu = zeros(n, 1);
sigma2 = zeros(n, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the mean of the data and the variances
%               In particular, mu(i) should contain the mean of
%               the data for the i-th feature and sigma2(i)
%               should contain variance of the i-th feature.
%

mu = 1/m * sum(X);

sigma2 = 1/m * sum((X - repmat(mu, m, 1)).^2);

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

end

author: Borye

path: github-repos/MATLAB/Borye-machine-learning-coursera-1/machine-learning-coursera-1-033fdc2e6da393eeb1179a09aafe92362021effb/Week 9 Assignments/Anomaly Detection and Recommender Systems/mlclass-ex8/estimateGaussian.m


text:
function test_failed = test_libltfat_gabdual(varargin)
test_failed = 0;

fprintf(' ===============  %s ================ \n',upper(mfilename));

definput.flags.complexity={'double','single'};
[flags]=ltfatarghelper({},definput,varargin);
dataPtr = [flags.complexity, 'Ptr'];

Larr = [12  15  120  120];
aarr = [3   3    10   10];
Marr = [6   5    20   20];

for do_complex = 0:1
    complexstring = '';
    if do_complex, complexstring = 'complex'; end
    for idx = 1:numel(Larr)
        L = Larr(idx);
        a = aarr(idx);
        M = Marr(idx);

            if do_complex
                z = cast(randn(L,1)+1i*randn(L,1),flags.complexity);
                zi = complex2interleaved(z);
                zout = randn(size(zi),flags.complexity);

                ziPtr = libpointer(dataPtr,zi);
                zoutPtr = libpointer(dataPtr,zout);
            else
                z = cast(randn(L,1),flags.complexity);
                zi = z;
                zout = randn(size(zi),flags.complexity);

                ziPtr = libpointer(dataPtr,zi);
                zoutPtr = libpointer(dataPtr,zout);
            end

            trueres = gabdual(z,a,M);

            funname = makelibraryname('gabdual_long',flags.complexity,do_complex);
            status = calllib('libltfat',funname, ziPtr,L,a,M,zoutPtr);

            if do_complex
                res = norm(trueres - interleaved2complex(zoutPtr.Value));
            else
                res = norm(trueres - zoutPtr.Value);
            end

            [test_failed,fail]=ltfatdiditfail(res+status,test_failed);
            fprintf(['GABDUAL OP L:%3i, %s %s %s %s\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);

            status = calllib('libltfat',funname,ziPtr,L,a,M,ziPtr);

            if do_complex
                res = norm(trueres - interleaved2complex(ziPtr.Value));
            else
                res = norm(trueres - ziPtr.Value);
            end

            [test_failed,fail]=ltfatdiditfail(res+status,test_failed);
            fprintf(['GABDUAL IP L:%3i, %s %s %s %s\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);

            if do_complex
                z = cast(randn(M,1)+1i*randn(M,1),flags.complexity);
                zi = complex2interleaved(z);
                zout = randn(size(zi),flags.complexity);

                ziPtr = libpointer(dataPtr,zi);
                zoutPtr = libpointer(dataPtr,zout);
            else
                z = cast(randn(M,1),flags.complexity);
                zi = z;
                zout = randn(size(zi),flags.complexity);

                ziPtr = libpointer(dataPtr,zi);
                zoutPtr = libpointer(dataPtr,zout);
            end

            trueres = gabdual(z,a,M);

            funname = makelibraryname('gabdual_painless',flags.complexity,do_complex);
            status = calllib('libltfat',funname, ziPtr,M,a,M,zoutPtr);

            if do_complex
                res = norm(trueres - interleaved2complex(zoutPtr.Value));
            else
                res = norm(trueres - zoutPtr.Value);
            end

            [test_failed,fail]=ltfatdiditfail(res+status,test_failed);
            fprintf(['GABDUAL PAINLESS OP L:%3i, %s %s %s %s\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);

            status = calllib('libltfat',funname,ziPtr,M,a,M,ziPtr);

            if do_complex
                res = norm(trueres - interleaved2complex(ziPtr.Value));
            else
                res = norm(trueres - ziPtr.Value);
            end

            [test_failed,fail]=ltfatdiditfail(res+status,test_failed);
            fprintf(['GABDUAL PANLESS IP L:%3i, %s %s %s %s\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);

    end
end

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function a = gauss(i1,i2,i3)

%====================================================================
% GAUSS gauss/gaussian density estimation object
%====================================================================
% A=GAUSS([M],[S],H) returns a gauss object initialized with mean M,
% std S and hyperparameters H. Can also be called with GAUSS(H)
%
% Training will try to fit a single Gaussian to the data.
% Testing will return the probability estimate, or if passed
% an empty dataset will generate new data according to the
% density learnt.
%
% Hyperparameters:
%  l=50       -- number of data points to generate if asked to generate
%  assume=[]  -- can make assumptions: {'diag_cov','equal_cov'}
%                where the matrix is diagonal ('diag_cov'),
%                or diagonal with all elements equal ('equal_cov')
%
% Model:
%  mean=0  -- centre of gauss distbn
%  cov=1   -- cov matrix, if single value assumes diagonal
%             of matrix all has same values, if vector assumes it
%             is the diagonal of the matrix, with 0s everywhere else
%
% Methods:
%  train, test, generate
%
% Examples:
%  gen(gauss)                                   % generate data
%  gen(gauss('l=5;mean=[1 1];cov=0.01;'))       % generate data
%
%  d=test(gauss([1 5],[1 -0.4 ; -0.4 1],'l=300'));
%  [d2 a]=train(gauss('l=200'),d);
%  d2=test(a); %% train a gauss on some (gauss) data and then
%              %% try to generate similar data
%  hold off; plot(d.X(:,1),d.X(:,2),'o')
%  hold on;  plot(d2.X(:,1),d2.X(:,2),'rx')
%====================================================================
% Reference : chapter 2 (Richard O. Duda and Peter E. Hart) Bayesian Decision Theory
% Author    : Richard O. Duda , Peter E. Hart
% Link      : http://www.amazon.com/exec/obidos/tg/detail/-/0471056693/002-6279399-2828812?v=glance
%====================================================================

  a.l=50;
  a.mean=0;
  a.cov=1;
  a.assume=[];

  p=algorithm('gauss');
  a= class(a,'gauss',p);

  if nargin==1
    if ischar(i1)
      hyper=i1; eval_hyper; return;
    else
      a.mean=i1;
    end
  end;

  if nargin==2
    a.mean=i1;
    if ischar(i2)
      hyper=i2; eval_hyper; return;
    else
      a.cov=i2;
    end
  end;

  if nargin==3
    a.mean=i1;
    a.cov=i2;
    hyper=i3; eval_hyper;
  end;

author: canlab


text:
% VARGPLVMTOOLBOXES Load in the relevant toolboxes for variational gplvm.

importLatest('netlab');
importLatest('gpmat');

author: SheffieldML

repo: vargplvm


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
% ##2
%==============================================================================
%
%   - data                 MRI (head), Omega=(0,128)x(0,128), level=4:7, m=[128,128]
%   - viewer               viewImage2D
%   - interpolation        splineInter
%   - distance             MI
%   - pre-registration     rigid2D
%   - regularizer          mbElastic
%   - optimization         lBFGS
% ===============================================================================

close all, help(mfilename);

setup2DMRIData
imgModel('reset','imgModel','splineInter','regularizer','none','theta',1e-3);
distance('reset','distance','MI','nT',8,'nR',8);
trafo('reset','trafo','rigid2D');
regularizer('reset','regularizer','mfElastic','alpha',1e-4,'mu',1,'lambda',0);

PIRpara = optPara('lBFGS','solver','backslash');
NPIRpara = optPara('lBFGS','solver',regularizer('get','solver'));

[yc,wc,his] = MLIR(ML,'PIRobj',@PIRBFGSobjFctn,'PIRpara',PIRpara,...
  'NPIRobj',@NPIRBFGSobjFctn,'NPIRpara',NPIRpara,...
  'minLevel',4,'maxLevel',7,'parametric',1,'plotMLiter',0);

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


text:
% ------------------------------------------------------------------------
%  Copyright (C)
%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain
%  University of California Berkeley (UCB) - USA
%
%  Jordi Pont-Tuset <jordi.pont@upc.edu>
%  Pablo Arbelaez <arbelaez@berkeley.edu>
%  June 2014
% ------------------------------------------------------------------------
% This file is part of the MCG package presented in:
%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,
%    "Multiscale Combinatorial Grouping,"
%    Computer Vision and Pattern Recognition (CVPR) 2014.
% Please consider citing the paper if you use this code.
% ------------------------------------------------------------------------
%
% This function builds all the MEX files needed.
% Dependencies needed to build: Boost C++ libraries (http://www.boost.org)
%
% ------------------------------------------------------------------------
function build()
% Check that 'root_dir' has been set
if ~exist(root_dir,'dir')
    error('Error building MCG, try updating the value of root_dir in the file "root_dir.m"')
end

%% Include the generic paths and files to compile
include{1} = fullfile(root_dir, 'src', 'aux');  % To get matlab_multiarray.hpp
if (strcmp(computer(),'PCWIN64') || strcmp(computer(),'PCWIN32'))
    include{2} = 'C:\Program Files\boost_1_55_0';  % Boost libraries (change it if necessary)
else
    include{2} = '/opt/local/include/';  % Boost libraries (change it if necessary)
end
include{3} = fullfile(root_dir, 'src', 'external','piotr_toolbox'); % To build Piotr toolbox

include_str = '';
for ii=1:length(include)
    include_str = [include_str ' -I''' include{ii} '''']; %#ok<AGROW>
end

build_file{1}     = fullfile(root_dir, 'src', 'cands'    ,'mex_assess_one_sel.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_base_perimeters.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_fast_features.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_fast_intersections.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_fast_reduction.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_get_tree_cands.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_prune_tree_to_regions.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_max_margin.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'cands'    ,'mex_hole_filling.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_intersect_hierarchies.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_ucm2hier.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_cands2masks.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'aux'      ,'mex_cands2labels.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'benchmark','mex_eval_masks.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'benchmark','mex_eval_labels.cpp');
build_file{end+1} = fullfile(root_dir, 'src', 'external' ,'paretofront','paretofront.cpp');

%% Build everything
if ~exist(fullfile(root_dir, 'lib'),'dir')
    mkdir(fullfile(root_dir, 'lib'))
end

for ii=1:length(build_file)
    eval(['mex ''' build_file{ii} ''' -outdir ''' fullfile(root_dir, 'lib') '''' include_str])
end

%% Build random forest files
file1   = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'mex_regressionRF_train.cpp');
file2   = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'mex_regressionRF_predict.cpp');
dep1    = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'cokus.cpp');
dep2    = fullfile(root_dir, 'src', 'external', 'RF_Reg_C', 'src', 'reg_RF.cpp');
o_file1 = fullfile(root_dir, 'lib', 'mexRF_train');
o_file2 = fullfile(root_dir, 'lib', 'mexRF_predict');

eval(['mex ' file1 ' ' dep1 ' ' dep2 ' -output ' o_file1 ' -DMATLAB -O'])
eval(['mex ' file2 ' ' dep1 ' ' dep2 ' -output ' o_file2 ' -DMATLAB -O'])

%% Build structured forest files
eval(['mex ' fullfile(root_dir, 'src', 'external','structured_forest', 'edgesDetectMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])

%% Build piotr_toolbox files
eval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox',     'convConst.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])
eval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox',   'gradientMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])
eval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox',      'imPadMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])
eval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox', 'imResampleMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])
eval(['mex ' fullfile(root_dir, 'src', 'external','piotr_toolbox', 'rgbConvertMex.cpp') ' -outdir ' fullfile(root_dir, 'lib') include_str])

%% Build BSR-related files
% 'ucm_mean_pb'
eval(['mex ' fullfile(root_dir, 'src', 'bsr', 'ucm_mean_pb.cpp') ' -outdir ' fullfile(root_dir, 'lib')])

% 'buildW'
eval(['mex ' fullfile(root_dir, 'src', 'bsr', 'buildW.cpp') ' -outdir ' fullfile(root_dir, 'lib'),...
            ' -I' fullfile(root_dir,'src','external','BSR','buildW') ' -I' fullfile(root_dir,'src','external','BSR','buildW','util'),...
            '   ' fullfile(root_dir,'src','external','BSR','buildW','smatrix.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','buildW','ic.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','buildW','affinity.cc'),...
            ])

% 'mex_contour_sides'
eval(['mex ' fullfile(root_dir, 'src', 'bsr', 'mex_contour_sides.cpp') ' -outdir ' fullfile(root_dir, 'lib'),...
            ' -I' fullfile(root_dir,'src','external','BSR','include'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','child_thread.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','runnable.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','thread.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','synchronization','synchronizables','synchronizable.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','concurrent','threads','synchronization','synchronizables','unsynchronized.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_bad_cast.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_not_found.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_not_implemented.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_index_out_of_bounds.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_invalid_argument.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','ex_null_pointer_dereference.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','exception.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','exceptions','throwable.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','lang','array.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','generators','rand_gen_uniform.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','rand_source_default.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','rand_source.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','mersenne_twister_64.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','rand_source_64.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','sources','system_entropy.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','random','util','randperm.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','matrices','matrix.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','matrices','exceptions','ex_matrix_dimension_mismatch.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','libraries','lib_image.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','libraries','lib_signal.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','math.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','exact.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','point_2D.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','seg_intersect.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','triangulation.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','math','geometry','triangle_2D.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','mlearning','clustering','clusterers','abstract','clusterer.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','mlearning','clustering','clusterers','abstract','weighted_clusterer.cc'),...
            '   ' fullfile(root_dir,'src','external','BSR','src','mlearning','clustering','clusterers','kmeans','basic_clusterer.cc'),...
            ]);

%% Clear variables
clear build_file file1 file2 dep1 dep2 o_file1 o_file2 ii include include_str

%% Show message
disp('-- Successful compilation of MCG. Enjoy! --')

author: jponttuset

repo: mcg

save_path: github-repos/MATLAB/jponttuset-mcg


text:
function value = mean(SO3F, varargin)
% Calculates the mean value of a SO3Fun or calculates the mean
% along a specified dimension of a vector-valued SO3Fun
%
% Syntax
%   value = mean(SO3F)
%   SO3F = mean(SO3F, d)
%
% Input
%  SO3F - @SO3Fun
%  d - dimension to take the mean value over
%
% Output
%  SO3F  - @SO3Fun
%  value - double
%
% Description
%
% If SO3F is a 3x3 SO3Fun then
% |mean(SO3F)| returns a 3x3 matrix with the mean values of each function
% |mean(SO3F, 1)| returns a 1x3 SO3Fun which contains the pointwise mean values along the first dimension
%
% Example
%   %generate SO3Funs
%   SO3F1 = SO3Fun.dubna
%   SO3F2 = SO3FunHandle(@(rot) SO3F1.eval(rot))
%   A = ones(2,3);
%   SO3F3 = SO3F2.*A
%
%   %calculate mean values of SO3Funs
%   mean(SO3F2)
%   mean(SO3F3)
%   mean(SO3F3,2)
%   mean(SO3F3,1)
%

% mean along specific dimension
if nargin>1 && isnumeric(varargin{1})
  value = SO3FunHandle(@(rot) mean(SO3F.eval(rot),varargin{1}+1),SO3F.SRight,SO3F.SLeft);
  return
end

% mean value of a SO3Fun
res = get_option(varargin,'resolution',2.5*degree);
nodes = equispacedSO3Grid(SO3F.SRight,SO3F.SLeft,'resolution',res);
value = mean(SO3F.eval(nodes(:)));
value = reshape(value,size(SO3F));
if isalmostreal(value,'componentwise')
  value = real(value);
end

end

author: mtex-toolbox

repo: mtex

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


text:
function dists = compute( pairspath, descs, geom_noise, varargin )

% Copyright (C) 2016-2017 Karel Lenc
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

opts.metric = 'L2';
[opts, ~] = vl_argparse(opts, varargin);

pairs = readtable(pairspath);

descsA = descs.getdesc(descs, pairs.s1, geom_noise, pairs.t1 + 1, pairs.idx1 + 1);
descsB = descs.getdesc(descs, pairs.s2, geom_noise, pairs.t2 + 1, pairs.idx2 + 1);

switch opts.metric
  case 'L1'
    dists = sum(abs(descA - descB), 1);
  case 'L2'
    dists = sum((descsA - descsB).^2, 1);
  otherwise
    error('Invalid metric.');
end

end

author: hpatches

repo: hpatches-benchmark


text:
 function ir_mri_rf_spsp_plot(b, gz, d, f, z, mm, t)
%function ir_mri_rf_spsp_plot(b, gz, d, f, z, mm, t)
%|
%| plot SPSP pulses etc.
%| code extracted from compute_rf_spsp_mgh

%printm('Displaying SPSP pulse design results...')

pl = @(i) subplot(340+i);

pl(1)
plot(t*1000,gz)
axis tight
grid
xlabel('Time (ms)')
ylabel('g/cm')
title('z gradient')

pl(5)
plot(t*1000,real(b),'b-', t*1000,imag(b),'r-')
axis tight
grid
xlabel('Time (ms)')
ylabel('g')
title('SPSP pulse')
legend('Real','Imaginary')

%Display desired pattern of the SPSP recovery pulse.
pl(2)
imagesc(f,z,abs(d))
colormap default;colorbar
xlabel('Frequency offset (Hz)')
ylabel('z (cm)')
title('Desired SPSP pattern (magnitude)')

pl(6)
imagesc(f,z,angle(d).*abs(d),[-pi,pi]);colorbar
colormap(gca, hsv)
xlabel('Frequency offset (Hz)')
ylabel('z (cm)')
title('Desired SPSP pattern (phase)')

pl(3)
imagesc(f,z,abs(mm))
xlabel('frequency (Hz)')
ylabel('z (cm)')
title('Resulting pattern (linear regime prediction)')

pl(7)
imagesc(f,z,angle(mm))
colormap(gca, hsv)
xlabel('frequency (Hz)')
ylabel('z (cm)')
title('Resulting phase pattern (linear regime prediction)')

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
% GAUSSIAN_DLOGPDF - The log pdf of a multivariate normal distribution.
%
% Computes the logarithm of the multivariate normal probability density
% function N(Y|MU,COV), where Y is the random variable, MU is the mean
% and COV is the covariance.
%
% The function is called as:
%
% L = GAUSSIAN_LOGPDF(Y_INVCOV_Y, Y_INVCOV_MU, MU_INVCOV_MU, LOGDET_COV, D)
%
% where
%
% Y_INVCOV_Y   : Y'*INV(COV)*Y
% Y_INVCOV_MU  : Y'*INV(COV)*MU
% MU_INVCOV_MU : MU'*INV(COV)*MU
% LOGDET_COV   : LOG(DET(COV))
% D            : the dimensionality of the distribution
%
% However, these terms should be computed more efficiently than using INV
% and LOG(DET(..)).
%
% Letting the user to compute the terms allows greater efficiency and
% flexibility.
%
% Also note that the function is linear with respect to its arguments. Thus,
% some efficiency may be obtained for a large set of pdfs by summing the
% terms and calling this function only once with scalar arguments.
%
% Usage:
%
% X = GAUSSIAN_DLOGPDF(Y, MU, L)
%
% X = GAUSSIAN_DLOGPDF(INVCOV_Y, INVCOV_MU)
%
% X = GAUSSIAN_DLOGPDF(D_Y_INVCOV_Y, D_Y_INVCOV_MU, D_MU_INVCOV_MU, ...
%                      D_LOGDET_COV)

% Last modified 2011-02-09
% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)

function dx = gaussian_dlogpdf(p1, p2, p3, p4)

if nargin == 3

  y = p1;
  mu = p2;
  L = p3;

  dx = -linsolve_lchol(L,y-mu);

elseif nargin == 2

  invCov_y = p1;
  invCov_mu = p2;

  dx = invCov_mu - invCov_y;

elseif nargin == 4

  dx = -0.5*(p1-2*p2+p3) - 0.5*p4;

end

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


text:
function histogram_old_95(vari1,stri2)
    %histogram_old_95.m                               A.Allmann
    %plots histogram in cumulative number window
    %vari1 depends on input parameter
    %
    %Last modification 6/95
    global mess  ccum freq_field histo hisvar strii1 strii2
    stri1='Histogram';
    strii1=stri1;
    strii2=stri2;
    hisvar=vari1;
    tm1=[];
    % Find out of figure already exists
    %
    [existFlag,figNumber]=figure_exists('Histogram',1);
    newHistoFlag=existFlag;
    if newHistoFlag
        figure_w_normalized_uicontrolunits(histo)
        cla
        cla
        delete(gca)
    else
        histo= figure_w_normalized_uicontrolunits( ...
            'NumberTitle','off','Name',stri1,...
            'MenuBar','none', ...
            'NextPlot','new', ...
            'Visible','off')

        %Menuline for options
        %
        %matdraw

        op1 = uimenu('Label','Display');
        uimenu(op1,'Label','Bin Number','Callback','inpubin(1);');
        uimenu(op1,'Label','Bin Vector','Callback','inpubin(2);');
        uimenu(op1,'Label','Default','Callback','histogram(hisvar);');

        callbackStr= ...
            ['newcat=a;f1=gcf; f2=gpf; set(f1,''Visible'',''off'');', ...
            'if f1~=f2, figure_w_normalized_uicontrolunits(f2); end'];

        uicontrol('Units','normal',...
            'Position',[.0  .83 .08 .06],'String','Close ',...
             'Callback','close;done')

        uicontrol('Units','normal',...
            'Position',[.0  .93 .08 .06],'String','Print ',...
             'Callback','myprint')

    end

    orient tall
    rect = [0.25,  0.18, 0.60, 0.70];
    axes('position',rect)
    hold on

    histogram(vari1,50);
    title2([stri2,stri1],'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')
    set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,'Box','on')

    xlabel(stri2,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
    ylabel('  Number ','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
    set(gcf,'Visible','on')

author: CelsoReyes


text:
function varargout = lvd_OptimizerSelectionGUI(varargin)
    % LVD_OPTIMIZERSELECTIONGUI MATLAB code for lvd_OptimizerSelectionGUI.fig
    %      LVD_OPTIMIZERSELECTIONGUI, by itself, creates a new LVD_OPTIMIZERSELECTIONGUI or raises the existing
    %      singleton*.
    %
    %      H = LVD_OPTIMIZERSELECTIONGUI returns the handle to a new LVD_OPTIMIZERSELECTIONGUI or the handle to
    %      the existing singleton*.
    %
    %      LVD_OPTIMIZERSELECTIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local
    %      function named CALLBACK in LVD_OPTIMIZERSELECTIONGUI.M with the given input arguments.
    %
    %      LVD_OPTIMIZERSELECTIONGUI('Property','Value',...) creates a new LVD_OPTIMIZERSELECTIONGUI or raises the
    %      existing singleton*.  Starting from the left, property value pairs are
    %      applied to the GUI before lvd_OptimizerSelectionGUI_OpeningFcn gets called.  An
    %      unrecognized property name or invalid value makes property application
    %      stop.  All inputs are passed to lvd_OptimizerSelectionGUI_OpeningFcn via varargin.
    %
    %      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
    %      instance to run (singleton)".
    %
    % See also: GUIDE, GUIDATA, GUIHANDLES

    % Edit the above text to modify the response to help lvd_OptimizerSelectionGUI

    % Last Modified by GUIDE v2.5 25-Jan-2020 16:16:14

    % Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct('gui_Name',       mfilename, ...
        'gui_Singleton',  gui_Singleton, ...
        'gui_OpeningFcn', @lvd_OptimizerSelectionGUI_OpeningFcn, ...
        'gui_OutputFcn',  @lvd_OptimizerSelectionGUI_OutputFcn, ...
        'gui_LayoutFcn',  [] , ...
        'gui_Callback',   []);
    if nargin && ischar(varargin{1})
        gui_State.gui_Callback = str2func(varargin{1});
    end

    if nargout
        [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
    else
        gui_mainfcn(gui_State, varargin{:});
    end
    % End initialization code - DO NOT EDIT

    % --- Executes just before lvd_OptimizerSelectionGUI is made visible.
function lvd_OptimizerSelectionGUI_OpeningFcn(hObject, eventdata, handles, varargin)
    % This function has no output args, see OutputFcn.
    % hObject    handle to figure
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    % varargin   command line arguments to lvd_OptimizerSelectionGUI (see VARARGIN)

    % Choose default command line output for lvd_OptimizerSelectionGUI
    handles.output = hObject;

    centerUIFigure(hObject);

    lvdData = varargin{1};
    setappdata(hObject, 'lvdData', lvdData);

    handles = populateGUI(lvdData, handles);

    % Update handles structure
    guidata(hObject, handles);

    % UIWAIT makes lvd_OptimizerSelectionGUI wait for user response (see UIRESUME)
    uiwait(handles.lvd_OptimizerSelectionGUI);

function handles = populateGUI(lvdData, handles)
    lvdOpt = lvdData.optimizer;
    optAlgoStrs = LvdOptimizerAlgoEnum.getListBoxStr();
    gradAlgoStrs = LvdOptimizerGradientCalculationAlgoEnum.getListBoxStr();

    handles.gradientSelCombo.String = gradAlgoStrs;
    handles.gradientSelCombo.Value = LvdOptimizerGradientCalculationAlgoEnum.getIndForName(lvdOpt.gradAlgo.name);
    gradientSelCombo_Callback(handles.gradientSelCombo, [], handles);

    handles.optimizerSelectionCombo.String = optAlgoStrs;
    handles.optimizerSelectionCombo.Value = LvdOptimizerAlgoEnum.getIndForName(lvdOpt.optAlgo.name);
    optimizerSelectionCombo_Callback(handles.optimizerSelectionCombo, [], handles);

    % --- Outputs from this function are returned to the command line.
function varargout = lvd_OptimizerSelectionGUI_OutputFcn(hObject, eventdata, handles)
    % varargout  cell array for returning output args (see VARARGOUT);
    % hObject    handle to figure
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)

    % Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = [];
    else
        lvdData = getappdata(handles.lvd_OptimizerSelectionGUI, 'lvdData');
        lvdOpt = lvdData.optimizer;

        gradAlgoStrs = LvdOptimizerGradientCalculationAlgoEnum.getListBoxStr();
        optGradInd = handles.gradientSelCombo.Value;
        gradAlgoEnum = LvdOptimizerGradientCalculationAlgoEnum.getEnumForListboxStr(gradAlgoStrs{optGradInd});
        lvdOpt.gradAlgo = gradAlgoEnum;

        optAlgoStrs = LvdOptimizerAlgoEnum.getListBoxStr();
        optAlgoInd = handles.optimizerSelectionCombo.Value;
        optAlgoEnum = LvdOptimizerAlgoEnum.getEnumForListboxStr(optAlgoStrs{optAlgoInd});
        lvdOpt.optAlgo = optAlgoEnum;

        varargout{1} = [];
        close(handles.lvd_OptimizerSelectionGUI);
    end

    % --- Executes on selection change in optimizerSelectionCombo.
function optimizerSelectionCombo_Callback(hObject, eventdata, handles)
    % hObject    handle to optimizerSelectionCombo (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)

    % Hints: contents = cellstr(get(hObject,'String')) returns optimizerSelectionCombo contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from optimizerSelectionCombo
    optAlgoStrs = LvdOptimizerAlgoEnum.getListBoxStr();
    enum = LvdOptimizerAlgoEnum.getEnumForListboxStr(optAlgoStrs{get(hObject,'Value')});
    handles.optimAlgDescTextLbl.String = enum.desc;

    if(enum.reqGrad)
        handles.gradientSelCombo.Enable = 'on';
        handles.editSelectedGradAlgoOptions.Enable = 'on';
        gradientSelCombo_Callback(handles.gradientSelCombo, [], handles);
    else
        handles.gradientSelCombo.Enable = 'off';
        handles.editSelectedGradAlgoOptions.Enable = 'off';
    end

    % --- Executes during object creation, after setting all properties.
function optimizerSelectionCombo_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to optimizerSelectionCombo (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    empty - handles not created until after all CreateFcns called

    % Hint: popupmenu controls usually have a white background on Windows.
    %       See ISPC and COMPUTER.
    if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
        set(hObject,'BackgroundColor','white');
    end

    % --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
    % hObject    handle to saveAndCloseButton (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    uiresume(handles.lvd_OptimizerSelectionGUI);

    % --- Executes on selection change in gradientSelCombo.
function gradientSelCombo_Callback(hObject, eventdata, handles)
    % hObject    handle to gradientSelCombo (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)

    % Hints: contents = cellstr(get(hObject,'String')) returns gradientSelCombo contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from gradientSelCombo
    gradAlgoStrs = LvdOptimizerGradientCalculationAlgoEnum.getListBoxStr();
    enum = LvdOptimizerGradientCalculationAlgoEnum.getEnumForListboxStr(gradAlgoStrs{get(hObject,'Value')});
    handles.optimGradAlgDescTextLbl.String = enum.desc;

    if(enum.disableOptions)
        handles.editSelectedGradAlgoOptions.Enable = 'off';
    else
        handles.editSelectedGradAlgoOptions.Enable = 'on';
    end

    % --- Executes during object creation, after setting all properties.
function gradientSelCombo_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to gradientSelCombo (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    empty - handles not created until after all CreateFcns called

    % Hint: popupmenu controls usually have a white background on Windows.
    %       See ISPC and COMPUTER.
    if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
        set(hObject,'BackgroundColor','white');
    end

    % --- Executes on button press in editSelectedGradAlgoOptions.
function editSelectedGradAlgoOptions_Callback(hObject, eventdata, handles)
    % hObject    handle to editSelectedGradAlgoOptions (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_OptimizerSelectionGUI, 'lvdData');

    gradAlgoStrs = LvdOptimizerGradientCalculationAlgoEnum.getListBoxStr();
    gradAlgoInd = handles.gradientSelCombo.Value;
    gradAlgoEnum = LvdOptimizerGradientCalculationAlgoEnum.getEnumForListboxStr(gradAlgoStrs{gradAlgoInd});

    lvdOpt = lvdData.optimizer;
    gradAlgo = lvdOpt.getGradAlgoForEnum(gradAlgoEnum);
    gradAlgo.openOptionsDialog();

    % --- Executes on button press in editSelectedOptimizerOptionsButton.
function editSelectedOptimizerOptionsButton_Callback(hObject, eventdata, handles)
    % hObject    handle to editSelectedOptimizerOptionsButton (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_OptimizerSelectionGUI, 'lvdData');

    optAlgoStrs = LvdOptimizerAlgoEnum.getListBoxStr();
    optAlgoInd = handles.optimizerSelectionCombo.Value;
    optAlgoEnum = LvdOptimizerAlgoEnum.getEnumForListboxStr(optAlgoStrs{optAlgoInd});

    lvdOpt = lvdData.optimizer;
    optimizer = lvdOpt.getOptimizerForEnum(optAlgoEnum);
    optimizer.openOptionsDialog();

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function varargout = drawLabels(varargin)
%DRAWLABELS Draw labels at specified positions
%
%   DRAWLABELS(X, Y, LBL) draw labels LBL at position X and Y.
%   LBL can be either a string array, or a number array. In this case,
%   string are created by using sprintf function, with '%.2f' mask.
%
%   DRAWLABELS(POS, LBL) draw labels LBL at position specified by POS,
%   where POS is a N*2 int array.
%
%   DRAWLABELS(..., NUMBERS, FORMAT) create labels using sprintf function,
%   with the mask given by FORMAT (e. g. '%03d' or '5.3f'), and the
%   corresponding values.
%
%   ---------
%
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 15/12/2003.
%

%   HISTORY
%   09/03/2007: (re)implement it...
%   2011-10-11 add management of axes handle

% check if enough inputs are given
if isempty(varargin)
    error('wrong number of arguments in drawLabels');
end

% extract handle of axis to draw on
if isscalar(varargin{1}) && ishandle(varargin{1})
    ax = varargin{1};
    varargin(1) = [];
else
    ax = gca;
end

% process input parameters
var = varargin{1};
if size(var, 2) == 1
    % coordinates given as separate arguments
    if length(varargin) < 3
        error('wrong number of arguments in drawLabels');
    end
    px  = var;
    py  = varargin{2};
    lbl = varargin{3};
    varargin(1:3) = [];
else
    % parameters given as a packed array
    if length(varargin) < 2
        error('wrong number of arguments in drawLabels');
    end
    px  = var(:,1);
    py  = var(:,2);
    lbl = varargin{2};
    varargin(1:2) = [];
end

% format for displaying numeric values
format = '%.2f';
if ~isempty(varargin)
    format = varargin{1};
end
if size(format, 1) == 1 && size(px, 1) > 1
    format = repmat(format, size(px, 1), 1);
end

% compute the strings that have to be displayed
labels = cell(length(px), 1);
if isnumeric(lbl)
    for i = 1:length(px)
        labels{i} = sprintf(format(i,:), lbl(i));
    end
elseif ischar(lbl)
    for i = 1:length(px)
        labels{i} = lbl(i,:);
    end
elseif iscell(lbl)
    labels = lbl;
end
labels = char(labels);

% display the text
h = text(px, py, labels, 'parent', ax);

% format output
if nargout > 0
    varargout = {h};
end

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
function [f,g] = autoGrad(x,funObj,varargin)
% [f,g] = autoGrad(x,useComplex,funObj,varargin)
%
% Numerically compute gradient of objective function from function values

p = length(x);
mu = 1e-150;

f = funObj(x,varargin{:});
mu = 2*sqrt(1e-12)*(1+norm(x))/norm(p);
for j = 1:p
  e_j = zeros(p,1);
  e_j(j) = 1;
  diff(j,1) = funObj(x + mu*e_j,varargin{:});
end
g = (diff-f)/mu;

if 0 % DEBUG CODE
    [fReal gReal] = funObj(x,varargin{:});
    [fReal f]
    [gReal g]
    pause;
end

repo: CategoryShapes


text:
function [features, superpixels, spArea] = getSPFeatures(imName, paths, param)
	count = 0;
	for j = 1:length(param.featureTyp),
		typ = param.featureTyp{j};

		fileName = fullfile(paths.featuresDir, typ, strcat(imName, '.mat'));

		dt = load(fileName);
		selThresh = param.selThresh{j};

		for i = 1:length(selThresh),
			count = count+1;
			F{count} = dt.features{selThresh(i)}(:,dt.clusters(:,selThresh(i)));
		end
	end
	features = cat(1,F{:});
	superpixels = dt.superpixels;
	spArea = accumarray(superpixels(:), 1)';
end

author: s-gupta

repo: rgbd

save_path: github-repos/MATLAB/s-gupta-rgbd