text:
function res = saveResTxt(bboxes_tracked)

frame_num = size(bboxes_tracked, 2);
track_bbox = zeros(1, 6);
res = [];
for frame = 1:frame_num
    bboxes = bboxes_tracked(1,frame).bbox;
    id_num = size(bboxes, 1);
    for id = 1:id_num
        track_bbox(1) = frame;
        track_bbox(2) = bboxes(id, 5);
        track_bbox(3) = bboxes(id, 1);
        track_bbox(4) = bboxes(id, 2);
        track_bbox(5) = bboxes(id, 3) - bboxes(id, 1);
        track_bbox(6) = bboxes(id, 4) - bboxes(id, 2);
        res = cat(1, res, [track_bbox, 1, -1, -1, -1]);
    end
end

if(~isempty(res))
    res = sortrows(res,1);
end

author: VisDrone

repo: DroneCrowd

save_path: github-repos/MATLAB/VisDrone-DroneCrowd


text:
function quad = fibonacci_lattice_q1 ( k, f )

%*****************************************************************************80
%
%% FIBONACCI_LATTICE_Q1 applies a Fibonacci lattice integration rule in 2D.
%
%  Discussion:
%
%    This is a modification of the algorithm in FIBONACCI_LATTICE_Q.
%    It uses a nonlinear transformation on the integrand, which makes
%    the lattice rule more suitable for nonperiodic integrands.
%
%    The transformation replaces the integration variable X by
%
%      PHI(X) = 3*X^2 - 2*X**3
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 November 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Ian Sloan, Stephen Joe,
%    Lattice Methods for Multiple Integration,
%    Oxford, 1994,
%    ISBN: 0198534728,
%    LC: QA311.S56
%
%  Parameters:
%
%    Input, integer K, the index of the Fibonacci number to be used.
%    K must be at least 3.
%
%    Input, external real F, the name of the user-supplied routine
%    which evaluates the function, of the form:
%    function f ( dim_num, x )
%    integer dim_num
%    real f
%    real x(dim_num)
%    f = ...
%
%    Output, real QUAD, the estimated integral.
%
  dim_num = 2;

  quad = 0.0;

  m = fibonacci ( k );

  z(1) = 1;
  z(2) = fibonacci ( k - 1 );

  for j = 0 : m - 1
    x(1:dim_num) = mod ( j * z(1:dim_num) / m, 1.0 );
    dphi = 1.0;
    for i = 1 : dim_num
      y(i) = ( 3.0 - 2.0 * x(i) ) * x(i) * x(i);
      dphi = dphi * 6.0 * ( 1.0 - x(i) ) * x(i);
    end
    quad = quad + f ( dim_num, y ) * dphi;
  end

  quad = quad / m;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function xyz_write ( output_filename, point_num, xyz )

%*****************************************************************************80
%
%% XY_WRITE writes an XY file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 January 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string OUTPUT_FILENAME, the name of the file
%    to which the data should be written.
%
%    Input, integer POINT_NUM, the number of points.
%
%    Input, real XYZ(3,POINT_NUM), the point coordinates.
%

%
%  Open the file.
%
  output_unit = fopen ( output_filename, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'XYZ_WRITE - Error!\n' );
    fprintf ( 1, '  Could not open the output file "%s".\n', output_filename );
    error ( 'XYZ_WRITE - Error!' );
    return;
  end
%
%  Write the header.
%
  xyz_header_write ( output_filename, output_unit, point_num );
%
%  Write the data.
%
  xyz_data_write ( output_unit, point_num, xyz );
%
%  Close the file.
%
  fclose ( output_unit );

  return
end


text:
function tests = test_ft_specest_irasa

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY ft_specest_irasa

if nargout
  % assume that this is called by RUNTESTS
  tests = functiontests(localfunctions);
else
  % assume that this is called from the command line
  fn = localfunctions;
  for i=1:numel(fn)
    feval(fn{i});
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function testOptions(testCase)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fsample = 1000;
nchan   = 2;
nsample = 1000;

dat     = randn(nchan, nsample) + 1 + linspace(0,1,nsample);
time    = (0:(nsample-1))/fsample;
freqoi  = 1:150;

result = {};
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'original');
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal');
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi(2:2:end), 'output', 'original');
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi(2:2:end), 'output', 'fractal');

% try out another padding
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'original', 'pad', 2);
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal',  'pad', 2);

% try out the various padding types, don't remove the polynomial fit
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', -1, 'pad', 2, 'padtype', 'zero');
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', -1, 'pad', 2, 'padtype', 'mean');
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', -1, 'pad', 2, 'padtype', 'localmean');
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', -1, 'pad', 2, 'padtype', 'edge');
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', -1, 'pad', 2, 'padtype', 'mirror');

% the default polyorder 1 is already covered earlier
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', 0);
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', 2);
result{end+1} = ft_specest_irasa(dat, time, 'verbose', false, 'freqoi', freqoi, 'output', 'fractal', 'polyorder', 3);

% all iterations were done with (slightly) different options, hence the results should not be equal
for i=1:numel(result)
  for j=(i+1):numel(result)
    assert(~isequaln(result{i}, result{j}), 'the results %d and %d should not be equal', i, j);
  end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
%% demo code
% reconstruction of retrospective subsampled Shepp-Logan phantom

% set paths
addpath(genpath(pwd));
addpath(genpath(['..',filesep,'CS_LAB_matlab']));

%% ------------------------------------------
% 1.) load data: phantom (2 slices, 1 channel)
% -------------------------------------------
dImg = phantom('Modified Shepp-Logan',256);
dKSpace = fftnshift(dImg,1:2);

%% --------------------------
% 2.) create subsampling mask
% ---------------------------
if(ispc), sExt = '.exe'; else sExt = ''; end
system(['.',filesep,'sampling',filesep,'Subsample',sExt,sprintf(' %d %d %d %d', 256, 1, 4, 1)]);
iMask = readSamplingMaskFromFile(['.',filesep,'samplingPattern.txt']);

%% -------------------------
% 3.) apply subsampling mask
% --------------------------
% k-Space dimensions
% cell array: NSlice x NChannels x NRepetitions x NAverages
%             each cell: 2D: yPhase x xFreq x (nTime/nPhases)
%                        3D: yPhase x xFreq x zPhase
%                        4D: yPhase x xFreq x zPhase x nTime/nPhases
dKSpaceSub = {dKSpace .* repmat(iMask,[1 256])};

%% --------------------
% 4.) reconstruct image
% ---------------------
% set some recon parameters
para.cstype = 'FOCUSS';
para.transformation = 'fft';
para.lambda = 1e-12;
para.lambdaTV = 1e-6;
para.measPara.dim = [size(dKSpaceSub{1}), 1, 1, 1];
para.measPara.LCall = ones(1,4);
para.measPara.dimension = '2D';
para.espresso.state = false;
para.espresso.direction = 'off';
para.espresso.pfn = 1;
para.flagOversampling = logical([0 0 0]);
para.postproc.turnImage = false;
para.postproc.FreqOversamplingCorr = false;
para.prop.flagPlot = false;

% CS reconstruction
dCSRecon = CS_reconstruction(dKSpaceSub, para);

% zero-padded reconstruction
dZeropadded = abs(ifftnshift(dKSpaceSub{1}));

%% ------------------
% 5.) compare results
% -------------------
figure;
subplot(1,3,1)
imagesc(dImg); colormap('gray');
axis 'equal'; set(gca,'XTick',[],'YTick',[]); axis 'off';
title('original')
subplot(1,3,2)
imagesc(dZeropadded); colormap('gray');
axis 'equal'; set(gca,'XTick',[],'YTick',[]); axis 'off';
title('zero-padded recon')
subplot(1,3,3)
imagesc(dCSRecon); colormap('gray');
axis 'equal'; set(gca,'XTick',[],'YTick',[]); axis 'off';
title('CS recon')

author: thomaskuestner


text:
filename='Cantileverbeam_Hexahedra_Linear_Structured';
ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'holes';
cost = {'compliance'};
weights = [1];
constraint = {'volumeConstraint'};
optimizer = 'HAMILTON-JACOBI';
incrementFactor = 1;
designVariable = 'LevelSet';
filterType = 'P1';
constraint_case = 'INEQUALITY';

nsteps = 10;
Vfrac_final = 0.1;
Perimeter_target=3.5;
optimality_final =1e-4;
constr_final =1e-4;

BCscale_factor = 0.3;
rotation_per_it = 20;
HJiter0 = 1;
e2 = 100;
N_holes = [12 5 5];
R_holes = 0.2;
phase_holes = [0 0 0];

Vfrac_initial = 0.7;
optimality_initial = 5e-2;
constr_initial = 5e-2;

TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;

% maxiter = 1;
TOL.nu_plus = 0.3;
TOL.nu_minus = 0.3;

plotting = 1;
printing = 0;
monitoring = 1;
monitoring_interval = 1;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function V_RF  = yuweiA1

global Vn H Nrf Nt Nk
V_RF = ones(Nt,Nrf);

for k = 1:Nk
    F(:,:,k) = H(:,:,k)'*H(:,:,k);
end
F = sum(F,3)/Nk;
g = 1/Nrf/Nt;
a = g/Vn;

for Nloop = 1:10
    for j = 1:Nrf
        VRF = V_RF;
        VRF(:,j)=[];
        C = eye(Nrf-1)+a*VRF'*F*VRF;
        G = a*F-a^2*F*VRF*C^(-1)*VRF'*F;
        for i = 1:Nt
            for l = 1:Nt
                if i~=l
                    x(l)=G(i,l)*V_RF(l,j);
                end
            end
            n = sum(x);
            if n ==0
                V_RF(i,j)=1;
            else
                V_RF(i,j)=n/abs(n);
            end
        end
    end
end

author: Zzhaoxingyu

repo: hybrid-beamforming-for-three-scenes


text:
function union2tet(surface_name,cage_name,union_name,tet_name)
  % UNION2TET Script to take 3 meshes, a surface, a partial cage that intersects the
  % surface and their volume-union's surface (probably from Blender), and use
  % tetgen to generate a tet mesh that has tets in the volume-union with faces
  % of the original surface .
  %
  % union2tet(surface_name,cage_name,union_name,tet_name)
  %
  % Inputs:
  %   surface_name  file containing original surface
  %   cage_name  file containing (partial) cage
  %   union_name  file containing union surface
  % Output:
  %   tet_name  file to be written with .mesh tet mesh
  %
  [SV,SF] = load_mesh(surface_name);
  [CV,CF] = load_mesh(cage_name);
  [UV,UF] = load_mesh(union_name);
  % combine union and surface so we have a list of faces for the union and the
  % original surface that look into the same vertex list
  [V,F] = combine(SV,SF,UV,UF);
  [T,V] = tetgen(V,F,setdiff(CV,V,'rows'),true);
  writeMESH(tet_name,V,T,SF);

  skeleton_name = strrep([tet_name '.tgf'],'.mesh','');
  % Find all edges in mesh, note internal edges are repeated
  CE = sort( ...
    [CF(:,1) CF(:,2); ...
    CF(:,2) CF(:,3); ...
    CF(:,3) CF(:,1)]')';
  % remove duplicates
  CE = unique(CE,'rows');
  writeTGF(skeleton_name,CV,CE);

end

author: alecjacobson

repo: gptoolbox


text:
function g = scd_display_qspacedata3D(data,scheme,fibredir,Marker,Linestyle,color,noise)
% scd_display_qspacedata(data,scheme,fibredir)
% data: vector OR NxM matrix. N: number of measurement (=size(scheme,1)). M: number of
%      observation (for error bars).
% EXAMPLE:
%       SCD_DISPLAY_QSPACEDATA(Smodel,Ax.scheme)
%       SCD_DISPLAY_QSPACEDATA(Smodel,Ax.scheme,0,'x','-')

if ~exist('Marker','var'), Marker='x'; end
if ~exist('Linestyle','var'), Linestyle='none'; end

Gparr=scheme(:,1:3)*fibredir(:);
absc = Gparr;
[absc,II] = sort(absc); scheme = scheme(II,:); data = data(II);
bval = scd_scheme_bvalue(scheme);

if size(scheme,2)<9
    % Find different shells
    list_G=unique(round(scheme(:,[4 5 6 7])*1e8)/1e8,'rows');
    nnn = size(list_G,1);
    for j = 1 : nnn
        for i = 1 : size(scheme,1)
            if  round(scheme(i,[4 5 6 7])*1e8)/1e8 == list_G(j,:)
                scheme(i,9) = j;
            end
        end
    end
end

seq=unique(scheme(:,9)); ND=length(seq);
if ~exist('color','var')
    color=jet(ND);
end

for iD=1:ND
    seqiD=find(scheme(:,9)==seq(iD));

    datavoxel=mean(squeeze(data),2);

    g(iD)=plot(absc(seqiD,:),datavoxel(seqiD),'LineStyle',Linestyle, 'Marker',Marker,'Color',color(min(iD,end),:),'LineWidth',2);

    if ~moxunit_util_platform_is_octave
        hold on
        set(g(iD),'DisplayName',['bvalue=' num2str(max(bval(seqiD))*1e3,'%.0f') 's/mm^2 G=' num2str(max(scheme(seqiD,4))*1e6,'%.0f') 'mT/m \Delta=' num2str(mean(scheme(seqiD,5)),'%.0f') 'ms \delta=' num2str(mean(scheme(seqiD,6)),'%.0f') 'ms TE=' num2str(mean(scheme(seqiD,7)),'%.0f') 'ms']);
    end

    if exist('noise','var')==1

        h(iD)=errorbar(absc(seqiD),datavoxel(seqiD),noise(seqiD), 'xr', 'Color', color);
    elseif size(data,2)>1
        data_stdvoxel=std(data,0,2);
        h(iD)=errorbar(absc(seqiD),datavoxel(seqiD),data_stdvoxel(seqiD), 'xr', 'Color', color);
        %         figure(3)
        %         d(iD)=plot(q(seqiD),data_stdvoxel(seqiD),'LineStyle','none', 'Marker','x','Color',color,'LineWidth',2);
        %         hold on
    end
    if exist('h','var')==1
        % don't display data legend
        if ~moxunit_util_platform_is_octave
            hAnnotation = get(h(iD),'Annotation');
            hLegendEntry = get(hAnnotation','LegendInformation');
            set(hLegendEntry,'IconDisplayStyle','off');
        end
    end
end

if ~moxunit_util_platform_is_octave
    xlabel('G_{//}/|G|','FontSize',15);
    ylabel('Signal','FontSize',15);
    legend('show','Location','Best')
    set(gca,'FontSize',15)
    %ylim([0 1.2])
    grid on, box off
    hold off
end

% Add legend about linestyle
switch Linestyle
    case 'none'
        switch Marker
            case 'o'
                txt = [Marker ' = simulated data'];
                pos = [0.25, 0.97];
            case 'x'
                txt = [Marker ' = noisy simulated data'];
                pos = [0.5, 0.97];
        end
    otherwise
        txt = [Linestyle ' = fit'];
        pos = [0.75, 0.97];
end
t = text(pos(1),pos(2),txt,'Units','normalized');

if ~moxunit_util_platform_is_octave
    set(t,'FontSize',10);
    set(t,'BackgroundColor',[0.9  0.9 0.9]);
end

end

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function PlotPoint2DLikePolarity(aedat, numPlots, distributeBy, minTime, maxTime, proportionOfPixels, transpose, flipVertical, flipHorizontal)

%{
Works like PlotPolarity, except that:
 - the values comes from point2D instead of polarity,
 - the colour shows the type of the event (a unique color is chosen for each type)
 - there's no concept of contrast.
%}

% The proportion of an array-full of events which is shown on a plot
if ~exist('proportionOfPixels', 'var')
	proportionOfPixels = 0.1;
end

if ~exist('numPlots', 'var')
	numPlots = 12;
end

if ~exist('distributeBy', 'var')
	distributeBy = 'time';
end

% Unpack

timeStamp = aedat.data.point2D.timeStamp;
x = aedat.data.point2D.x;
y = aedat.data.point2D.y;
type = aedat.data.point2D.type;

% Distribute plots in a raster with a 3:4 ratio
numPlotsX = round(sqrt(numPlots / 3 * 4));
numPlotsY = ceil(numPlots / numPlotsX);

numEvents = length(timeStamp);
if strcmpi(distributeBy, 'time')
    if ~exist('minTime', 'var') || (exist('minTime', 'var') && minTime == 0)
        minTime = min(timeStamp);
    else
        minTime = minTime * 1e6;
    end
    if ~exist('maxTime', 'var') || (exist('maxTime', 'var') && maxTime == 0)
        maxTime = max(timeStamp);
    else
        maxTime = maxTime * 1e6;
    end
	totalTime = maxTime - minTime;
	timeStep = totalTime / numPlots;
	timePoints = minTime + timeStep * 0.5 : timeStep : maxTime;
else % distribute by event number
	eventsPerStep = numEvents / numPlots;
	timePoints = timeStamp(ceil(eventsPerStep * 0.5 : eventsPerStep : numEvents));
end

if exist ('transpose', 'var') && transpose
    % Swap x and y
    y = y + x;
    x = x - y;
    y = y - x;
end

minY = double(min(y));
maxY = double(max(y));
minX = double(min(x));
maxX = double(max(x));
numPixelsInArray = (maxY - minY) * (maxX - minX);
numPixelsToSelectEachWay = ceil(numPixelsInArray * proportionOfPixels / 2);

if numPlots > 1
    figure
end
for plotCount = 1 : numPlots
    if numPlots > 1
    	subplot(numPlotsY, numPlotsX, plotCount);
    end
	hold all
	% Find eventIndex nearest to timePoint
	eventIndex = find(timeStamp >= timePoints(plotCount), 1, 'first');
	firstIndex = max(1, eventIndex - numPixelsToSelectEachWay);
	lastIndex = min(numEvents, eventIndex + numPixelsToSelectEachWay);
	selectedLogical = [false(firstIndex - 1, 1); ...
					true(lastIndex - firstIndex + 1, 1); ...
					false(numEvents - lastIndex, 1)];
	typeSelected = type(selectedLogical);
    typeUniqueValues = unique(typeSelected);

    for uniqueValue = typeUniqueValues'
        selectedByTypeLogical = selectedLogical & type == uniqueValue;
    	plot(x(selectedByTypeLogical), y(selectedByTypeLogical), '.');
    end

	axis equal tight
	if ~exist('flipVertical', 'var') || flipVertical
		set(gca, 'YDir', 'reverse')
	end
    if exist('flipHorizontal', 'var') && flipHorizontal
		set(gca, 'XDir', 'reverse')
    end
	title([num2str(double(timeStamp(eventIndex)) / 1e6) ' s'])
end

author: panpanfei


text:
function ar=lpcim2ar(im)
%LPCIM2AR Convert impulse response to AR coefs AR=(IM)

%      Copyright (C) Mike Brookes 1997
%      Version: $Id: lpcim2ar.m 713 2011-10-16 14:45:43Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[nf,p1]=size(im);
ar=zeros(nf,p1);
wz=[1 zeros(1,p1-1)];
for k=1:nf
  ar(k,:)=wz/toeplitz(wz,im(k,:)/im(k,1));
end

author: jtkim-kaist

repo: VAD

save_path: github-repos/MATLAB/jtkim-kaist-VAD


text:
function test_ft_timelockstatistics

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_timelockstatistics findcluster clusterstat ft_statistics_montecarlo

%For the case of "chan_time"

% make fake dataset
timelock = cell(1,10);
for idat = 1:10
  timelock{idat}.label = {'chan1','chan2','chan3'};
  timelock{idat}.dimord = 'chan_time';
  timelock{idat}.avg = rand(3,30);
  timelock{idat}.time = 0.1:0.1:3;
  timelock{idat}.cfg = [];
end

% do stats - montecarlo
cfg = [];
neighbours(1).label = 'chan1';
neighbours(1).neighblabel = {'chan2', 'chan3'};
neighbours(2).label = 'chan2';
neighbours(2).neighblabel = {'chan1', 'chan3'};
neighbours(3).label = 'chan3';
neighbours(3).neighblabel = {'chan1', 'chan2'};
cfg.neighbours  = neighbours;
cfg.method      = 'montecarlo';
cfg.statistic   = 'ft_statfun_depsamplesT';
cfg.alpha       = 0.05;
cfg.correctm    = 'cluster';
cfg.clusterstatistic = 'maxsum';
cfg.clusterthreshold = 'parametric';
cfg.numrandomization = 500;
cfg.design = [ones(1,5) ones(1,5).*2; 1:5 1:5;];
cfg.ivar   = 1;
cfg.uvar   = 2;
stat = ft_timelockstatistics(cfg,timelock{:});

% do stats - analytic
cfg = [];
cfg.method      = 'analytic';
cfg.statistic   = 'ft_statfun_depsamplesT';
cfg.alpha       = 0.05;
cfg.design = [ones(1,5) ones(1,5).*2; 1:5 1:5;];
cfg.ivar   = 1;
cfg.uvar   = 2;
stat = ft_timelockstatistics(cfg,timelock{:});

% do stats - analytic
cfg = [];
cfg.method      = 'stats';
cfg.statistic   = 'ttest';
cfg.alpha       = 0.05;
cfg.design = [ones(1,10) ];
stat = ft_timelockstatistics(cfg,timelock{:});


text:
classdef ParallelToFrameAtTimeCoordSystem < AbstractGeometricCoordSystem
    %ParallelToFrameCoordSystem Summary of this class goes here
    %   Detailed explanation goes here

    properties
        frame AbstractReferenceFrame
        time(1,1) double = 0;

        name(1,:) char
        lvdData LvdData
    end

    methods
        function obj = ParallelToFrameAtTimeCoordSystem(frame, time, name, lvdData)
            obj.frame = frame;
            obj.time = time;

            obj.name = name;
            obj.lvdData = lvdData;
        end

        function [rotMatToInertial] = getCoordSysAtTime(obj, ~, vehElemSet, ~)
            [~, ~, ~, rotMatToInertial] = obj.frame.getOffsetsWrtInertialOrigin(obj.time, vehElemSet);
        end

        function name = getName(obj)
            name = obj.name;
        end

        function setName(obj, name)
            obj.name = name;
        end

        function listboxStr = getListboxStr(obj)
            listboxStr = sprintf('%s (Parallel To "%s" at UT = %0.3f sec)', obj.getName(), obj.frame.getNameStr(), obj.time);
        end

        function useTf = openEditDialog(obj)
            output = AppDesignerGUIOutput({false});
            lvd_EditParallelToFrameAtTimeCoordSysGUI_App(obj, obj.lvdData, output);
            useTf = output.output{1};
        end

        function tf = isVehDependent(obj)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.isVehDependent();
            else
                tf = false;
            end
        end

        function tf = usesGroundObj(obj, groundObj)
            tf = obj.frame.usesGroundObj(groundObj);
        end

        function tf = usesGeometricPoint(obj, point)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricPoint(point);
            else
                tf = false;
            end
        end

        function tf = usesGeometricVector(obj, vector)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricVector(vector);
            else
                tf = false;
            end
        end

        function tf = usesGeometricCoordSys(obj, coordSys)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricCoordSys(coordSys);
            else
                tf = false;
            end
        end

        function tf = usesGeometricRefFrame(obj, refFrame)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricRefFrame(refFrame);
            else
                tf = false;
            end
        end

        function tf = usesGeometricAngle(obj, angle)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricAngle(angle);
            else
                tf = false;
            end
        end

        function tf = usesGeometricPlane(obj, plane)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricPlane(plane);
            else
                tf = false;
            end
        end

        function tf = isInUse(obj, lvdData)
            tf = lvdData.usesGeometricCoordSys(obj);
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function copyDependenciesForCERRCompile(compiled_path)

% function copyDependenciesForCERRCompile(compiled_path)
%
% This function creates bin, doc, pics directories and copies files to
% them.
%
% APA, 03/26/2012
% RKP, 8/13/2019 - Updated to use dcm4che-5.17.0

CERRPath = getCERRPath;
CERRPathSlashes = strfind(getCERRPath,filesep);
topLevelCERRDir = CERRPath(1:CERRPathSlashes(end-1));

% Create bin, doc and pics directories
mkdir(fullfile(compiled_path,'bin'));
mkdir(fullfile(compiled_path,'doc'));
mkdir(fullfile(compiled_path,'pics'));
copyfile(fullfile(topLevelCERRDir,'CERR_core','CERROptions.m'),compiled_path);
copyfile(fullfile(topLevelCERRDir,'CERR_core','CERROptions.json'),compiled_path);

% Fill-in the bin directory
destin = fullfile(compiled_path,'bin');
mkdir(fullfile(destin,'Compression'));
mkdir(fullfile(destin,'Importing'));
mkdir(fullfile(destin,'IMRTP'));
mkdir(fullfile(destin,'mat_files'));
mkdir(fullfile(destin,'MeshInterp'));
copyfile(fullfile(topLevelCERRDir,'ML_Dicom','dcm4che-5.17.0'),fullfile(destin,'dcm4che-5.17.0'));
copyfile(fullfile(topLevelCERRDir,'CERR_core','Mex'),fullfile(destin,'Mex'));

destin_compression = fullfile(compiled_path,'bin','Compression');
copyfile(fullfile(topLevelCERRDir,'CERR_core','Compression','7z.dll'),destin_compression);
copyfile(fullfile(topLevelCERRDir,'CERR_core','Compression','7z.exe'),destin_compression);
copyfile(fullfile(topLevelCERRDir,'CERR_core','Compression','7z.sfx'),destin_compression);
copyfile(fullfile(topLevelCERRDir,'CERR_core','Compression','7z_License.txt'),destin_compression);
copyfile(fullfile(topLevelCERRDir,'CERR_core','Compression','tar.exe'),destin_compression);

destin_importing = fullfile(compiled_path,'bin','Importing');
copyfile(fullfile(topLevelCERRDir,'CERR_core','Importing','readASCIIDose.exe'),destin_importing);
copyfile(fullfile(topLevelCERRDir,'CERR_core','Importing','ES - IPT4.1CompatibleDictionary.mat'),destin_importing);

destin_IMRTP = fullfile(compiled_path,'bin','IMRTP');
copyfile(fullfile(topLevelCERRDir,'IMRTP','QIBData'),fullfile(destin_IMRTP,'QIBData'),'f');
copyfile(fullfile(topLevelCERRDir,'IMRTP','vmc++'),fullfile(destin_IMRTP,'vmc++'),'f');

copyfile(fullfile(topLevelCERRDir,'CERR_core','Icons','copperColorMap.mat'),fullfile(compiled_path,'bin','mat_files'));

destin_MeshInterp = fullfile(compiled_path,'bin','MeshInterp');
copyfile(fullfile(topLevelCERRDir,'CERR_core','MeshBasedInterp','libMeshContour.dll'),destin_MeshInterp);
copyfile(fullfile(topLevelCERRDir,'CERR_core','MeshBasedInterp','MeshContour.h'),destin_MeshInterp);
copyfile(fullfile(topLevelCERRDir,'CERR_core','MeshBasedInterp','pretriang_4.txt'),destin_MeshInterp);
copyfile(fullfile(topLevelCERRDir,'CERR_core','MeshBasedInterp','pretriang_5.txt'),destin_MeshInterp);
copyfile(fullfile(topLevelCERRDir,'CERR_core','MeshBasedInterp','pretriang_6.txt'),destin_MeshInterp);

% Fill-in the pics directory
destin = fullfile(compiled_path,'pics');
copyfile(fullfile(topLevelCERRDir,'CERR_core','Icons'),fullfile(destin,'Icons'));
copyfile(fullfile(topLevelCERRDir,'CERR_core','CERR.png'),destin);
copyfile(fullfile(topLevelCERRDir,'CERR_core','Contouring','structureFusionBackground.png'),destin);

% Fill-in the docs directory
destin = fullfile(compiled_path,'doc');
mkdir(fullfile(destin,'html'));
copyfile(fullfile(topLevelCERRDir,'CERR_core','CommandLine','CERRCommandLinehelp.html'),fullfile(destin,'html'));

%  Copy JSON configuration files for Segmentation and Dosimetric models
destin_modelConfig = fullfile(compiled_path,'ModelImplementationLibrary','SegmentationModels', 'ModelConfigurations');
mkdir(destin_modelConfig)
copyfile(fullfile(topLevelCERRDir,'CERR_core','ModelImplementationLibrary','SegmentationModels', 'ModelConfigurations'),destin_modelConfig);
destin_modelConfig = fullfile(compiled_path,'ModelImplementationLibrary','DosimetricModels', 'Models');
mkdir(destin_modelConfig)
copyfile(fullfile(topLevelCERRDir,'CERR_core','ModelImplementationLibrary','DosimetricModels', 'Models'),destin_modelConfig);

return;

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function T = TRaw( I )

if(nargin<1 || isempty(I)), T=single([]);   return; end

% T = single( I(:,:,4) );
T = single( I(:,:,end) );

end

author: SoonminHwang

repo: rgbt-ped-detection


text:
function arrMean = slarrmean(data, arrsiz, n, varargin)
%SLARRMEAN Computes the mean of a set of arrays
%
% $ Syntax $
%   - slarrmean(arrs, arrsiz, n, ...)
%   - slarrmean(fns, arrsiz, n, ...)
%
% $ Arguments $
%   - arrs:         the super-array consisting of all arrays
%   - fns:          the file paths of all array files
%   - arrsiz:       the size of each array unit. (for a column vector, it
%                   is the length of the vector)
%   - n:            the total number of array units
%
% $ Description $
%   - slarrmean(arrs, arrsiz, n, ...) computes the mean of all array units
%     with the size of each unit specified by arrsiz. If there are more
%     than one array unit, the size of arrs should be [arrsiz, n].
%
%   - slarrmean(fns, arrsiz, n, ...) computes the mean of all array units
%     stored in the array files given in fns. Each array file stores
%     an super-array of a set of array units.
%
%   - You can specify additional properties.
%       \t      The properties of slarrmean
%       \h      name       &        description
%              'weights'   &  The weights of each array unit, default = []
%
% $ History $
%   - Created by Dahua Lin on Jul 27th, 2006
%

%% parse and verify input arguments

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

if isnumeric(data)
    isdirect = true;
    arrs = data;
    arrsiz = arrsiz(:)';
    if ~isequal(size(arrs), [arrsiz, n])
        error('sltoolbox:sizmismatch', ...
            'The size of arrs (data) is invalid');
    end

elseif iscell(data)
    isdirect = false;
    fns = data;
    arrsiz = arrsiz(:)';
    nfiles = numel(fns);

else
    error('sltoolbox:invalidarg', ...
        'The first argument for slarrmean should be an numeric array or a cell array of file names');
end

opts.weights = [];

opts = slparseprops(opts, varargin{:});
hasweights = ~isempty(opts.weights);

if (hasweights)
    opts.weights = opts.weights(:);
    if length(opts.weights) ~= n
        error('sltoolbox:invalidarg', ...
            'The length of weights is inconsistent with the number of units');
    end
end

%% Main skeleton

if isdirect
    arrMean = compute_array_sum(arrs, arrsiz, n, opts.weights);
else
    arrMean = zeros(arrsiz);
    c = 0;
    for i = 1 : nfiles
        curarrs = slreadarray(fns{i});
        curn = size(curarrs, length(arrsiz) + 1);
        if ~hasweights
            arrMean = arrMean + compute_array_sum(curarrs, arrsiz, curn, []);
        else
            arrMean = arrMean + compute_array_sum(curarrs, arrsiz, curn, opts.weights(c+1:c+curn));
        end
        c = c + curn;

        if c > n
            error('sltoolbox:sizmismatch', ...
                'The total number of units in the set of array files is not n');
        end
    end

    if c ~= n
        error('sltoolbox:sizmismatch', ...
            'The total number of units in the set of array files is not n');
    end

end

if ~hasweights
    arrMean = arrMean / n;
else
    arrMean = arrMean / sum(opts.weights);
end

%% Compute function

function S = compute_array_sum(arrs, arrsiz, n, w)

if ~isequal(size(arrs), [arrsiz, n])
    error('sltoolbox:sizmismatch', ...
        'The size of array is not consistent as specified');
end

d = length(arrsiz);
if isempty(w)
    S = sum(arrs, d+1);
else
    S = reshape(arrs, [prod(arrsiz), n]) * w;
    if d == 1
        S = reshape(S, [arrsiz, 1]);
    else
        S = reshape(S, arrsiz);
    end
end

author: lmthang


text:
clear

pocr_dir = 'D:\Dropbox\Dropbox\AAM\3rd party models\PO-CR\300VW_mtcnn/';
cfss_dir = 'D:\Dropbox\Dropbox\AAM\3rd party models\CVPR15-CFSS-master\CVPR15-CFSS-master\300VW_mtcnn/';
iccr_dir = 'D:\demo_iccr\iCCR\iCCR\out_300VW/';
chehra_dir = 'D:\Datasets\300VW_Dataset_2015_12_14\chehra_out_mtcnn/';
sdm_dir = 'D:\Datasets\300VW_Dataset_2015_12_14\sdm_out_mtcnn/';
cfan_dir = 'D:\Datasets\300VW_Dataset_2015_12_14\CFAN_mtcnn/';

%% Gather predictions and ground truth
cat_1 = [ 114, 124, 125, 126, 150, 158, 401, 402, 505, 506, 507, 508, 509, 510, 511, 514, 515, 518, 519, 520, 521, 522, 524, 525, 537, 538, 540, 541, 546, 547, 548];
cat_2 = [203, 208, 211, 212, 213, 214, 218, 224, 403, 404, 405, 406, 407, 408, 409, 412, 550, 551, 553];
cat_3 = [410, 411, 516, 517, 526, 528, 529, 530, 531, 533, 557, 558, 559, 562];

%%

cfss_preds = zeros(68,2,0);
iccr_preds = zeros(66,2,0);
clnf_preds = zeros(68,2,0);
cfan_preds = zeros(68,2,0);
sdm_preds = zeros(49,2,0);
drmf_preds = zeros(49,2,0);
pocr_preds = zeros(49,2,0);

labels = zeros(68,2,0);
% Load results
for i=cat_1

    load(['CLNF_res_general/', num2str(i)]);
    clnf_preds = cat(3, clnf_preds, preds);

    labels = cat(3, labels, gt_landmarks);
    load([cfss_dir,  num2str(i)]);
    cfss_preds = cat(3, cfss_preds, preds);

    load([cfan_dir,  num2str(i)]);
    cfan_preds = cat(3, cfan_preds, preds);

    load([iccr_dir,  num2str(i)]);
    iccr_preds = cat(3, iccr_preds, pred_landmarks);

    load([chehra_dir,  num2str(i)]);
    drmf_preds = cat(3, drmf_preds, preds);

    load([pocr_dir,  num2str(i)]);
    pocr_preds = cat(3, pocr_preds, preds);
end

% As ICCR uses only 66 landmarks adapt all the others to the same format
labels = labels([1:60,62:64,66:end],:,:);
clnf_preds = clnf_preds([1:60,62:64,66:end],:,:);
cfss_preds = cfss_preds([1:60,62:64,66:end],:,:);
cfan_preds = cfan_preds([1:60,62:64,66:end],:,:);

clnf_error_66_cat_1 = compute_error(labels, clnf_preds);
cfss_error_66_cat_1 = compute_error(labels, cfss_preds - 0.5);
cfan_error_66_cat_1 = compute_error(labels, cfan_preds - 1.0);
iccr_error_66_cat_1 = compute_error(labels, iccr_preds);

% Do the 49 point version
labels = labels(18:end,:,:);

clnf_preds = clnf_preds(18:end,:,:);
cfan_preds = cfan_preds(18:end,:,:);
cfss_preds = cfss_preds(18:end,:,:);
iccr_preds = iccr_preds(18:end,:,:);

clnf_error_49_cat_1 = compute_error(labels, clnf_preds);
cfss_error_49_cat_1 = compute_error(labels, cfss_preds - 0.5);
cfan_error_49_cat_1 = compute_error(labels, cfan_preds - 1.0);
iccr_error_49_cat_1 = compute_error(labels, iccr_preds);
drmf_error_49_cat_1 = compute_error(labels, drmf_preds-0.5);
pocr_error_49_cat_1 = compute_error(labels, pocr_preds);

%%

cfss_preds = zeros(68,2,0);
iccr_preds = zeros(66,2,0);
clnf_preds = zeros(68,2,0);
cfan_preds = zeros(68,2,0);
sdm_preds = zeros(49,2,0);
drmf_preds = zeros(49,2,0);
pocr_preds = zeros(49,2,0);

labels = zeros(68,2,0);
% Load results
for i=cat_2

    load(['CLNF_res_general/', num2str(i)]);
    clnf_preds = cat(3, clnf_preds, preds);

    labels = cat(3, labels, gt_landmarks);
    load([cfss_dir,  num2str(i)]);
    cfss_preds = cat(3, cfss_preds, preds);

    load([cfan_dir,  num2str(i)]);
    cfan_preds = cat(3, cfan_preds, preds);

    load([iccr_dir,  num2str(i)]);
    iccr_preds = cat(3, iccr_preds, pred_landmarks);

    load([chehra_dir,  num2str(i)]);
    drmf_preds = cat(3, drmf_preds, preds);

    load([pocr_dir,  num2str(i)]);
    pocr_preds = cat(3, pocr_preds, preds);
end

% As ICCR uses only 66 landmarks adapt all the others to the same format
labels = labels([1:60,62:64,66:end],:,:);
clnf_preds = clnf_preds([1:60,62:64,66:end],:,:);
cfss_preds = cfss_preds([1:60,62:64,66:end],:,:);
cfan_preds = cfan_preds([1:60,62:64,66:end],:,:);

clnf_error_66_cat_2 = compute_error(labels, clnf_preds);
cfss_error_66_cat_2 = compute_error(labels, cfss_preds - 0.5);
cfan_error_66_cat_2 = compute_error(labels, cfan_preds - 1.0);
iccr_error_66_cat_2 = compute_error(labels, iccr_preds);

% Do the 49 point version
labels = labels(18:end,:,:);

clnf_preds = clnf_preds(18:end,:,:);
cfan_preds = cfan_preds(18:end,:,:);
cfss_preds = cfss_preds(18:end,:,:);
iccr_preds = iccr_preds(18:end,:,:);

clnf_error_49_cat_2 = compute_error(labels, clnf_preds);
cfss_error_49_cat_2 = compute_error(labels, cfss_preds - 0.5);
cfan_error_49_cat_2 = compute_error(labels, cfan_preds - 1.0);
iccr_error_49_cat_2 = compute_error(labels, iccr_preds);
drmf_error_49_cat_2 = compute_error(labels, drmf_preds-0.5);
pocr_error_49_cat_2 = compute_error(labels, pocr_preds);

%%
cfss_preds = zeros(68,2,0);
iccr_preds = zeros(66,2,0);
clnf_preds = zeros(68,2,0);
cfan_preds = zeros(68,2,0);
sdm_preds = zeros(49,2,0);
drmf_preds = zeros(49,2,0);
pocr_preds = zeros(49,2,0);

labels = zeros(68,2,0);
% Load results
for i=cat_3

    load(['CLNF_res_general/', num2str(i)]);
    clnf_preds = cat(3, clnf_preds, preds);

    labels = cat(3, labels, gt_landmarks);
    load([cfss_dir,  num2str(i)]);
    cfss_preds = cat(3, cfss_preds, preds);

    load([cfan_dir,  num2str(i)]);
    cfan_preds = cat(3, cfan_preds, preds);

    load([iccr_dir,  num2str(i)]);
    iccr_preds = cat(3, iccr_preds, pred_landmarks);

    load([chehra_dir,  num2str(i)]);
    drmf_preds = cat(3, drmf_preds, preds);

    load([pocr_dir,  num2str(i)]);
    pocr_preds = cat(3, pocr_preds, preds);
end

% As ICCR uses only 66 landmarks adapt all the others to the same format
labels = labels([1:60,62:64,66:end],:,:);
clnf_preds = clnf_preds([1:60,62:64,66:end],:,:);
cfss_preds = cfss_preds([1:60,62:64,66:end],:,:);
cfan_preds = cfan_preds([1:60,62:64,66:end],:,:);

clnf_error_66_cat_3 = compute_error(labels, clnf_preds);
cfss_error_66_cat_3 = compute_error(labels, cfss_preds - 0.5);
cfan_error_66_cat_3 = compute_error(labels, cfan_preds - 1.0);
iccr_error_66_cat_3 = compute_error(labels, iccr_preds);

% Do the 49 point version
labels = labels(18:end,:,:);

clnf_preds = clnf_preds(18:end,:,:);
cfan_preds = cfan_preds(18:end,:,:);
cfss_preds = cfss_preds(18:end,:,:);
iccr_preds = iccr_preds(18:end,:,:);

clnf_error_49_cat_3 = compute_error(labels, clnf_preds);
cfss_error_49_cat_3 = compute_error(labels, cfss_preds - 0.5);
cfan_error_49_cat_3 = compute_error(labels, cfan_preds - 1.0);
iccr_error_49_cat_3 = compute_error(labels, iccr_preds);
drmf_error_49_cat_3 = compute_error(labels, drmf_preds-0.5);
pocr_error_49_cat_3 = compute_error(labels, pocr_preds);

%% Save the results
save('results/clnf_errors', 'clnf_error_66_cat_1', 'clnf_error_66_cat_2', 'clnf_error_66_cat_3',...
    'clnf_error_49_cat_1', 'clnf_error_49_cat_2', 'clnf_error_49_cat_3');
save('results/cfss_errors', 'cfss_error_66_cat_1', 'cfss_error_66_cat_2', 'cfss_error_66_cat_3',...
    'cfss_error_49_cat_1', 'cfss_error_49_cat_2', 'cfss_error_49_cat_3');
save('results/iccr_errors', 'iccr_error_66_cat_1', 'iccr_error_66_cat_2', 'iccr_error_66_cat_3',...
    'iccr_error_49_cat_1', 'iccr_error_49_cat_2', 'iccr_error_49_cat_3');
save('results/cfan_errors', 'cfan_error_66_cat_1', 'cfan_error_66_cat_2', 'cfan_error_66_cat_3',...
    'cfan_error_49_cat_1', 'cfan_error_49_cat_2', 'cfan_error_49_cat_3');

save('results/drmf_errors', 'drmf_error_49_cat_1', 'drmf_error_49_cat_2', 'drmf_error_49_cat_3');
save('results/pocr_errors', 'pocr_error_49_cat_1', 'pocr_error_49_cat_2', 'pocr_error_49_cat_3');

author: TadasBaltrusaitis

repo: OpenFace


text:
addpath('/Users/gt/Dropbox/scratch_matlab/RocketSeismology')
sync_spacex_videos_usfdata
sync_youtube_video_usfdata

author: geoscience-community-codes

repo: GISMO


text:
function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters.
%               You should set p to a vector of 0's and 1's
%

p = sigmoid(X * theta)

for i = 1:size(p)
  if (p(i) >= 0.5)
    p(i) = 1;
  else
    p(i) = 0;
  endif
end

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

end

author: fewtime

repo: ML

save_path: github-repos/MATLAB/fewtime-ML


text:
% demos for HMM in ch13
d = 3; k = 2; n = 10000;
[x,model] = hmmRnd(d,k,n);
%% Viterbi algorithm
[z, llh] = hmmViterbi(model, x);
%% HMM filter (forward algorithm)
[alpha, llh] = hmmFilter(model, x);
%% HMM smoother (forward backward)
[gamma,alpha,beta,c] = hmmSmoother(model, x);
%% Baum-Welch algorithm
[model, llh] = hmmEm(x,k);
plot(llh)

author: PRML

repo: PRMLT

save_path: github-repos/MATLAB/PRML-PRMLT


text:
function table = i4mat_data_read ( input_filename, m, n )

%*****************************************************************************80
%
%% I4MAT_DATA_READ reads data from an I4MAT file.
%
%  Discussion:
%
%    An I4MAT is an array of I4's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 January 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Input, integer M, N, the number of rows and columns in the data.
%
%    Output, integer TABLE(M,N), the point coordinates.
%
  table = [];
%
%  Build up the format string for reading M real numbers.
%
  string = ' ';

  for i = 0 : m
    string = strcat ( string, ' %d' );
  end

  input_unit = fopen ( input_filename );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_DATA_READ - Error!\n' );
    fprintf ( 1, '  Could not open the input file.\n' );
    error ( 'I4MAT_DATA_READ - Error!' );
    return;
  end

  i = 0;

  while ( i < n )

    line = fgets ( input_unit );

    if ( line == -1 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'I4MAT_DATA_READ - Error!\n' );
      fprintf ( 1, '  End of input while reading data.\n' );
      error ( 'I4MAT_DATA_READ - Error!' );
    end

    if ( line(1) == '#' )

    elseif ( s_len_trim ( line ) == 0 )

    else

      [ x, count ] = sscanf ( line, string );

      if ( count == m )
        i = i + 1;
        table(1:m,i) = x(1:m);
      end

    end

  end

  fclose ( input_unit );

  return
end

author: johannesgerer


text:
%% Load Images
wallpaper1=imread('Nike.jpg');
wallpaper2=imread('Fire.jpg');

%% Display Wallpaper1
image(wallpaper1);
axis equal; grid off;

%% Display Wallpaper2
image(wallpaper2);
axis equal; grid off;

%% Scale and Display Wallpaper1
darkerlogo=0.4*wallpaper1;
image(darkerlogo);
axis equal; grid off;

%% Add images
% Image fusion is made here ;)
fusion=darkerlogo+wallpaper2;
image(fusion);
axis equal; grid off;

repo: Aero-matlab


text:
function blas1_d_test08 ( )

%*****************************************************************************80
%
%% TEST08 tests DROTG.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 November 2006
%
%  Author:
%
%    John Burkardt
%
  test_num = 5;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST08\n' );
  fprintf ( 1, '  DROTG generates a real Givens rotation\n' );
  fprintf ( 1, '    (  C  S ) * ( A ) = ( R )\n' );
  fprintf ( 1, '    ( -S  C )   ( B )   ( 0 )\n' );
  fprintf ( 1, '\n' );

  seed = 123456789;

  for test = 1 : test_num

    [ a, seed ] = r8_uniform_01 ( seed );
    [ b, seed ] = r8_uniform_01 ( seed );

    [ c, s, r, z ] = drotg ( a, b );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  A =  %f  B =  %f\n', a, b );
    fprintf ( 1, '  C =  %f  S =  %f\n', c, s );
    fprintf ( 1, '  R =  %f  Z =  %f\n', r, z );
    fprintf ( 1, '   C*A+S*B = %f\n',  c * a + s * b );
    fprintf ( 1, '  -S*A+C*B = %f\n', -s * a + c * b );

  end

  return
end


text:
function varargout = cylinderMesh(cyl, varargin)
%CYLINDERMESH Create a 3D mesh representing a cylinder.
%
%   [V, F] = cylinderMesh(CYL)
%   Computes vertex coordinates and face vertex indices of a mesh
%   representing a 3D cylinder given as [X1 Y1 Z1 X2 Y2 Z2 R].
%
%   [V, F] = cylinderMesh(..., OPT)
%   with OPT = 'open' (0) (default) or 'closed' (1), specify if the bases
%   of the cylinder should be included.
%
%   [V, F] = cylinderMesh(..., NAME, VALUE);
%   Specifies one or several options using parameter name-value pairs.
%   Available options are:
%   'nPerimeter' the number of circles represeting the perimeter
%   'nRho' the number of circles along the hight
%
%   Example
%     % Draw a rotated cylinder
%     cyl = [0 0 0 10 20 30 5];
%     [v, f] = cylinderMesh(cyl);
%     figure;drawMesh(v, f, 'FaceColor', 'r');
%     view(3); axis equal;
%
%     % Draw three mutually intersecting cylinders
%       p0 = [30 30 30];
%       p1 = [90 30 30];
%       p2 = [30 90 30];
%       p3 = [30 30 90];
%       [v1 f1] = cylinderMesh([p0 p1 25]);
%       [v2 f2] = cylinderMesh([p0 p2 25]);
%       [v3 f3] = cylinderMesh([p0 p3 25],'closed','nPeri',40,'nRho',20);
%       figure; hold on;
%       drawMesh(v1, f1, 'FaceColor', 'r');
%       drawMesh(v2, f2, 'FaceColor', 'g');
%       drawMesh(v3, f3, 'FaceColor', 'b');
%       view(3); axis equal
%       set(gcf, 'renderer', 'opengl')
%
%   See also
%     drawCylinder, torusMesh, sphereMesh

% ------
% Author: David Legland
% E-mail: david.legland@inra.fr
% Created: 2012-10-25, using Matlab 7.9.0.529 (R2009b)
% Copyright 2012-2022 INRA - Cepia Software Platform

parser = inputParser;
addRequired(parser, 'cyl', @(x) validateattributes(x, {'numeric'},...
    {'size',[1 7],'real','finite','nonnan'}));
capParValidFunc = @(x) (islogical(x) ...
    || isequal(x,1) || isequal(x,0) || any(validatestring(x, {'open','closed'})));
addOptional(parser,'cap','open', capParValidFunc);
addParameter(parser, 'nPerimeter', 20, @(x) validateattributes(x,{'numeric'},...
    {'integer','scalar','>=',4}));
addParameter(parser, 'nRho', 10, @(x) validateattributes(x,{'numeric'},...
    {'integer','scalar','>=',2}));
parse(parser,cyl,varargin{:});
cyl=parser.Results.cyl;
cap=lower(parser.Results.cap(1));
NoPP=parser.Results.nPerimeter;
nRho=parser.Results.nRho;

% extract cylinder data
p1 = cyl(:, 1:3);
p2 = cyl(:, 4:6);
r  = cyl(:, 7);

% compute length and orientation
[theta, phi, rho] = cart2sph2d(p2 - p1);

% parametrisation on x
t = linspace(0, 2*pi, NoPP);
lx = r * cos(t);
ly = r * sin(t);

% parametrisation on z
lz = linspace(0, rho, nRho);

% generate surface grids
x = repmat(lx, [length(lz) 1]);
y = repmat(ly, [length(lz) 1]);
z = repmat(lz', [1 length(t)]);

% transform points
trans = localToGlobal3d(p1, theta, phi, 0);
[x, y, z] = transformPoint3d(x, y, z, trans);

% convert to FV mesh
[vertices, faces] = surfToMesh(x, y, z, 'xPeriodic', true);

% Close cylinder
if cap == 'c' || cap == 1
    toe.vertices = [x(1,1:NoPP-1); y(1,1:NoPP-1); z(1,1:NoPP-1)]';
    toe.vertices(NoPP,:) = transformPoint3d([0 0 0], trans);
    toe.faces = [repmat(NoPP, 1, NoPP-1); [2:NoPP-1 1]; 1:NoPP-1]';

    top.vertices = [x(end,1:NoPP-1); y(end,1:NoPP-1); z(end,1:NoPP-1)]';
    top.vertices(NoPP,:) = transformPoint3d([0 0 rho], trans);
    top.faces = fliplr(toe.faces);

    [vertices, faces] = concatenateMeshes(vertices, triangulateFaces(faces), ...
        toe.vertices, toe.faces, top.vertices, top.faces);
end

% format output
varargout = formatMeshOutput(nargout, vertices, faces);

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function [pyra, im_pyra] = deep_pyramid(im, cnn_model)
% [pyra, im_pyra] = deep_pyramid(im, cnn_model, cache_opts)
%
% im: a color image
% cnn_model: a handle to the model loaded into caffe

% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the DeepPyramid code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

[pyra, im_pyra] = feat_pyramid(im, cnn_model);

imsize = size(im);
pyra.imsize = imsize(1:2);
pyra.num_levels = cnn_model.pyra.num_levels;
pyra.stride = cnn_model.pyra.stride;

pyra.valid_levels = true(pyra.num_levels, 1);
pyra.padx = 0;
pyra.pady = 0;

% ------------------------------------------------------------------------
function [pyra, im_pyra] = feat_pyramid(im, cnn_model)
% ------------------------------------------------------------------------
% Compute a feature pyramid with caffe

if cnn_model.init_key ~= caffe('get_init_key')
  error('You probably need to load the cnn model into caffe.');
end

% we're assuming the input height and width are the same
assert(cnn_model.pyra.dimx == cnn_model.pyra.dimy);
% compute output width and height
sz_w = (cnn_model.pyra.dimx - 1) / cnn_model.pyra.stride + 1;
sz_h = sz_w;
sz_l = cnn_model.pyra.num_levels;
sz_c = cnn_model.pyra.num_channels;

%th = tic;
[batch, scales, level_sizes] = image_pyramid(im, cnn_model);
%fprintf('prep: %.3fs\n', toc(th));

%th = tic;
feat = caffe('forward', {batch});
% standard song and dance of swapping width and height between caffe and matlab
feat = permute(reshape(feat{1}, [sz_w sz_h sz_c sz_l]), [2 1 3 4]);
%fprintf('fwd: %.3fs\n', toc(th));

pyra.feat = feat;
pyra.scales = scales;
pyra.level_sizes = level_sizes;

im_pyra = batch;

% ------------------------------------------------------------------------
function [batch, scales, level_sizes] = image_pyramid(im, cnn_model)
% ------------------------------------------------------------------------
% Construct an image pyramid that's ready for feeding directly into caffe
% forward

batch_width = cnn_model.pyra.dimx;
batch_height = cnn_model.pyra.dimy;
num_levels = cnn_model.pyra.num_levels;
stride = cnn_model.pyra.stride;

im = single(im);
% Convert to BGR
im = im(:,:,[3 2 1]);
% Subtract mean (mean of the image mean--one mean per channel)
im = bsxfun(@minus, im, cnn_model.mu);

% scale = base scale relative to input image
im_sz = size(im);
if im_sz(1) > im_sz(2)
  height = batch_height;
  width = NaN;
  scale = height / im_sz(1);
else
  height = NaN;
  width = batch_width;
  scale = width / im_sz(2);
end
im_orig = im;

batch = zeros(batch_width, batch_height, 3, num_levels, 'single');
alpha = cnn_model.pyra.scale_factor;
scales = scale*(alpha.^-(0:num_levels-1))';
level_sizes = zeros(num_levels, 2);
for i = 0:num_levels-1
  if i == 0
    im = imresize(im_orig, [height width], 'bilinear');
  else
    im = imresize(im_orig, scales(i+1), 'bilinear');
  end
  im_sz = size(im);
  im_sz = im_sz(1:2);
  level_sizes(i+1, :) = ceil((im_sz - 1) / stride + 1);
  % Make width the fastest dimension (for caffe)
  im = permute(im, [2 1 3]);
  batch(1:im_sz(2), 1:im_sz(1), :, i+1) = im;
end

author: rbgirshick

repo: DeepPyramid


text:
function [sicdmeta] = pfa_sicd_meta(meta, nbdata, ifp_params)
%PFA_SICD_META Creates a SICD metadata structure for an image created by pfa_file.m
%
% Inputs:
%     meta:          Collection narrowband data.  This is the same
%                    structure returned by the get_meta function for a
%                    object returned by open_ph_reader.
%     nbdata:        CPHD-style per-pulse narrowband data.  This is the
%                    same structure returned as the second return parameter
%                    of the read_cphd function.
%     ifp_params:    Structure of some additional parameters computed
%                    during image formation.
%
% Outputs:
%     sicdmeta:      Image formation and collection information in a
%                    structure compatible with the SICD writer.
%
% Authors: Wade Schwartzkopf and Tom Krauss, NGA/IDT
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

% Create SICD meatdata structure
sicdmeta = meta2sicd_cphdx(meta,nbdata,ifp_params.channel);

% Image Creation
sicdmeta.ImageCreation.DateTime = now();
sicdmeta.ImageCreation.Profile  = 'pfa_sicd_meta.m';

% ImageData
sicdmeta.ImageData.PixelType               = 'RE32F_IM32F';
sicdmeta.ImageData.NumRows                 = ifp_params.image_size_pixels(1);
sicdmeta.ImageData.NumCols                 = ifp_params.image_size_pixels(2);
sicdmeta.ImageData.FirstRow                = 0;
sicdmeta.ImageData.FirstCol                = 0;
sicdmeta.ImageData.FullImage.NumRows       = sicdmeta.ImageData.NumRows;
sicdmeta.ImageData.FullImage.NumCols       = sicdmeta.ImageData.NumCols;
sicdmeta.ImageData.SCPPixel.Row            = floor(sicdmeta.ImageData.NumRows/2);
sicdmeta.ImageData.SCPPixel.Col            = floor(sicdmeta.ImageData.NumCols/2);

% GeoData
sicdmeta.GeoData.EarthModel='WGS_84';
center=mean(nbdata.SRPPos); % Current PFA code only forms to this point
sicdmeta.GeoData.SCP.ECF.X=mean(center(1));
sicdmeta.GeoData.SCP.ECF.Y=mean(center(2));
sicdmeta.GeoData.SCP.ECF.Z=mean(center(3));
scp_lla = ecf_to_geodetic([sicdmeta.GeoData.SCP.ECF.X sicdmeta.GeoData.SCP.ECF.Y sicdmeta.GeoData.SCP.ECF.Z]);
sicdmeta.GeoData.SCP.LLH.Lat=scp_lla(1);
sicdmeta.GeoData.SCP.LLH.Lon=scp_lla(2);
sicdmeta.GeoData.SCP.LLH.HAE=scp_lla(3);
% Corner coordinates will be popupated later in derived_sicd_fields call

% Grid
sicdmeta.Grid.ImagePlane     = 'SLANT';
sicdmeta.Grid.Type           = 'RGAZIM';
sicdmeta.Grid.Row.Sgn=-1; % We have done an IFFT in PFA
sicdmeta.Grid.Row.ImpRespBW  = diff(ifp_params.k_v_bounds);
sicdmeta.Grid.Row.ImpRespWid = 0.886/sicdmeta.Grid.Row.ImpRespBW;
sicdmeta.Grid.Row.SS         = 1/(ifp_params.sample_rate*sicdmeta.Grid.Row.ImpRespBW);
sicdmeta.Grid.Row.KCtr       = mean(ifp_params.k_v_bounds);
sicdmeta.Grid.Row.DeltaKCOAPoly = 0;
sicdmeta.Grid.Row.WgtType.WindowName = 'UNIFORM';
sicdmeta.Grid.Col.Sgn=-1; % We have done an IFFT in PFA
sicdmeta.Grid.Col.ImpRespBW  = diff(ifp_params.k_u_bounds);
sicdmeta.Grid.Col.ImpRespWid = 0.886/sicdmeta.Grid.Col.ImpRespBW;
sicdmeta.Grid.Col.SS         = 1/(ifp_params.sample_rate*sicdmeta.Grid.Col.ImpRespBW);
sicdmeta.Grid.Col.KCtr       = 0;
sicdmeta.Grid.Col.WgtType.WindowName = 'UNIFORM';
sicdmeta.Grid.Col.DeltaKCOAPoly = 0;

% ImageFormation
sicdmeta.ImageFormation.RcvChanProc.NumChanProc = 1; % This function only handles single-channel data
sicdmeta.ImageFormation.RcvChanProc.ChanIndex = ifp_params.channel;
sicdmeta.ImageFormation.ImageFormAlgo = 'PFA';
sicdmeta.ImageFormation.TStartProc = nbdata.TxTime(1);
sicdmeta.ImageFormation.TEndProc = nbdata.TxTime(end);
if isfield(meta.Channel,'Parameters') && ...
        isfield(meta.Channel.Parameters(ifp_params.channel),'Polarization') && ...
        all(isfield(meta.Channel.Parameters(ifp_params.channel).Polarization,{'TxPol','RcvPol'}))
    sicdmeta.ImageFormation.TxRcvPolarizationProc = ...
        [meta.Channel.Parameters(ifp_params.channel).Polarization.TxPol ':' ...
            meta.Channel.Parameters(ifp_params.channel).Polarization.RcvPol];
end
sicdmeta.ImageFormation.TxFrequencyProc.MinProc = ...
    min(nbdata.SC0 + (nbdata.SCSS * double(min(ifp_params.sample_range)-1)));
sicdmeta.ImageFormation.TxFrequencyProc.MaxProc = ...
    max(nbdata.SC0 + (nbdata.SCSS * double(max(ifp_params.sample_range)-1)));
sicdmeta.ImageFormation.ImageFormAlgo = 'PFA';
sicdmeta.ImageFormation.STBeamComp = 'NO';
sicdmeta.ImageFormation.ImageBeamComp = 'NO';
sicdmeta.ImageFormation.AzAutofocus = 'NO';
sicdmeta.ImageFormation.RgAutofocus = 'NO';

% SCPCOA
sicdmeta.SCPCOA.SCPTime = nbdata.TxTime(ifp_params.ref_pulse_index);

% Timeline
if isfield(meta,'Global') && isfield(meta.Global, 'Timeline') && ...
        all(isfield(meta.Global.Timeline, {'TxTime1', 'TxTime2'}))
    sicdmeta.Timeline.CollectDuration = meta.Global.Timeline.TxTime2 - ...
        meta.Global.Timeline.TxTime1;
else
    sicdmeta.Timeline.CollectDuration = nbdata.TxTime(end) - nbdata.TxTime(1);
end

% PFA
sicdmeta.PFA.FPN = struct('X',ifp_params.fpn(1),'Y',ifp_params.fpn(2),'Z',ifp_params.fpn(3));
sicdmeta.PFA.IPN = struct('X',ifp_params.ipn(1),'Y',ifp_params.ipn(2),'Z',ifp_params.ipn(3));
sicdmeta.PFA.PolarAngRefTime = nbdata.TxTime(ifp_params.ref_pulse_index);
% This often givens a "badly conditioned" polynomial warning with fitting a
% polynomial in ECF space.  Ignore.
old_state = warning('off','MATLAB:polyfit:RepeatedPointsOrRescale');
sicdmeta.PFA.PolarAngPoly = fliplr( polyfit(nbdata.TxTime, ifp_params.k_a, 5) ).';
sicdmeta.PFA.SpatialFreqSFPoly = fliplr( polyfit(ifp_params.k_a, ifp_params.k_sf, 5) ).';
warning(old_state);
sicdmeta.PFA.Krg1 = ifp_params.k_v_bounds(1);
sicdmeta.PFA.Krg2 = ifp_params.k_v_bounds(2);
sicdmeta.PFA.Kaz1 = ifp_params.k_u_bounds(1);
sicdmeta.PFA.Kaz2 = ifp_params.k_u_bounds(2);

sicdmeta = derived_sicd_fields(sicdmeta); % Computes many derived fields

end

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

author: ngageoint


function outputs=run_benchmark(imnames, topchosen, topscores, sptextdir, regspimgdir, sbddir, categids, refineddir)

%first compute all overlaps
overlaps=cell(numel(imnames),1);
for i=1:numel(imnames)
    if(rem(i-1,10)==0) fprintf('Computing overlaps:%d/%d\n',i, numel(imnames)); end
    %read the sprep
    [sp, reg2sp]=read_sprep(fullfile(sptextdir, [imnames{i} '.txt']), fullfile(regspimgdir, [imnames{i} '.png']));

    %load gt
    [cls, inst, categories]=load_gt(sbddir, imnames{i});

    %for each category of interest
    for j=1:numel(categids)
        categ_reg2sp=reg2sp(:,topchosen{categids(j)}{i});

        %if there is refined regions, read them
        if(exist('refineddir', 'var') & ~isempty(topchosen{categids(j)}{i}))
            tmp=load(fullfile(refineddir, int2str(categids(j)), [imnames{i} '.mat']));
            categ_reg2sp=tmp.newreg2sp;
        end

        %compute overlaps
        [overlap, pprecision, precall]=get_gt_overlaps(logical(categ_reg2sp), sp, double(inst));

        overlaps{j}{i}=overlap;
    end
    gt{i}=categories;

end

%now run the evaluation. This is relatively fast once overlaps are precomputed
ap_vol=zeros(9,numel(categids));
for j=1:numel(categids)
    for t=1:9
        outputs(t,j)=generalized_det_eval(imnames, topscores{categids(j)}, overlaps{j}, gt, categids(j), 0.1, 0.1*t);
        ap_vol(t,j)=outputs(t,j).PR.ap;
        fprintf('Evaluated threshold:%f for category:%d\n', 0.1*t, categids(j));
    end
end

%Print out ap_vol for all categories
categ_names_and_groups;
fprintf('Category name \t\t | AP^r\t | AP^r_{vol}\n');
fprintf('_______________________________________________________\n');
for j=1:numel(categids)
    fprintf('%s \t\t | %f\t | %f\n',categnames{categids(j)}, ap_vol(5,j), mean(ap_vol(:,j)));
end
fprintf('_______________________________________________________\n');
fprintf('Mean \t\t | %f\t | %f\n', mean(ap_vol(5,:)), mean(mean(ap_vol,2)));

%we will only work with the 0.5 threshold now
%produce the impact chart
produce_impact_chart_all(outputs(5,:));
output.ap_vol=ap_vol;


text:
function varargout = lvd_EditActionSetExtremumRecordingStateGUI(varargin)
% LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI MATLAB code for lvd_EditActionSetExtremumRecordingStateGUI.fig
%      LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI, by itself, creates a new LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI or raises the existing
%      singleton*.
%
%      H = LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI returns the handle to a new LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI or the handle to
%      the existing singleton*.
%
%      LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI.M with the given input arguments.
%
%      LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI('Property','Value',...) creates a new LVD_EDITACTIONSETEXTREMUMRECORDINGSTATEGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_EditActionSetExtremumRecordingStateGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_EditActionSetExtremumRecordingStateGUI_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_EditActionSetExtremumRecordingStateGUI

% Last Modified by GUIDE v2.5 14-Jan-2019 13:53:03

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_EditActionSetExtremumRecordingStateGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_EditActionSetExtremumRecordingStateGUI_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_EditActionSetExtremumRecordingStateGUI is made visible.
function lvd_EditActionSetExtremumRecordingStateGUI_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_EditActionSetExtremumRecordingStateGUI (see VARARGIN)

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

    centerUIFigure(hObject);

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

    lv = varargin{2};
    setappdata(hObject,'lv',lv);

    populateGUI(handles, action, lv);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, action, lv)
    [exListStr, extrema] = lv.getExtremaListBoxStr();
    if(not(isempty(exListStr)))
        set(handles.refExtremumCombo,'String',exListStr);
    else
        set(handles.refExtremumCombo,'String',' ');
    end

    recordingStateStrs = LaunchVehicleExtremaRecordingEnum.getNameStrs();
    set(handles.stateCombo,'String',recordingStateStrs);

    if(not(isempty(action.extremum)))
        ind = find(extrema == action.extremum,1,'first');
    else
        ind = [];
    end

    if(not(isempty(ind)))
        set(handles.refExtremumCombo,'Value',ind);
    end

    if(not(isempty(action.extremum)))
        ind = LaunchVehicleExtremaRecordingEnum.getIndOfListboxStrs(action.extremum.startingState);
    else
        ind = 1;
    end
    set(handles.stateCombo,'Value',ind);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditActionSetExtremumRecordingStateGUI_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} = false;
    else
        action = getappdata(hObject,'action');
        lv = getappdata(hObject,'lv');

        [~, extrema] = lv.getExtremaListBoxStr();
        if(not(isempty(extrema)))
            ind = get(handles.refExtremumCombo,'Value');
            action.extremum = extrema(ind);
        end

        [~,m] = LaunchVehicleExtremaRecordingEnum.getNameStrs();
        action.runningStateToSet = m(get(handles.stateCombo,'Value'));

        varargout{1} = true;
        close(handles.lvd_EditActionSetExtremumRecordingStateGUI);
    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_EditActionSetExtremumRecordingStateGUI);

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

% --- Executes on selection change in refExtremumCombo.
function refExtremumCombo_Callback(hObject, eventdata, handles)
% hObject    handle to refExtremumCombo (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 refExtremumCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from refExtremumCombo

% --- Executes during object creation, after setting all properties.
function refExtremumCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to refExtremumCombo (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 selection change in stateCombo.
function stateCombo_Callback(hObject, eventdata, handles)
% hObject    handle to stateCombo (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 stateCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from stateCombo

% --- Executes during object creation, after setting all properties.
function stateCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stateCombo (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 key press with focus on lvd_EditActionSetExtremumRecordingStateGUI or any of its controls.
function lvd_EditActionSetExtremumRecordingStateGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditActionSetExtremumRecordingStateGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditActionSetExtremumRecordingStateGUI);
    end


text:
function fractOverlap = getSurfaceAttachment(structNum1,structNum2,margin,planC)
%function min_dist = getSurfaceAttachment(structNum1,structNum2,margin,planC)
%
%This function calculates fractional overlap between the masks of structNum2
% and structNum2 contracted by margin. planC is an optional input argument.
%
%APA, 11/25/2019
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

if ~exist('planC','var')
    global planC
end

indexS = planC{end};

% Create Union of the two structure structNum1 (lung) and structNum2 (gtv)
planC = createUnionStructure(structNum1,structNum2,planC);

unionStrNum = length(planC{indexS.structures});

% Get surface mask of contracted unionStrNum
xyDownsampleIndex = 1; % no downsampling
contractedStr1M = getSurfaceContract(unionStrNum,margin,xyDownsampleIndex,planC);

% Remove unionStrNum
maskUnionM = getUniformStr(unionStrNum,planC);
ringMaskM = maskUnionM - contractedStr1M;
planC = deleteStructure(planC,unionStrNum);

% Get mask of structNum2 (gtv)
mask2M = getUniformStr(structNum2,planC);

% Get overlapping fraction of structNum2
overlapM = ringMaskM & mask2M;
fractOverlap = sum(overlapM(:)) / sum(mask2M(:));


text:
function xyb = Xb(s)
x = s ;
y = 0 ;

xyb = [x ; y] ;

author: Sable

repo: mcbench-benchmarks


text:
function [llratios, models] = gpTwoSample(t, y)

% GPTWOSAMPLE Do Oliver Stegles simple two sample test on a data set.
% FORMAT
% DESC computes a two sample test using independent or combined GPs to
% determine whether two gene expression profiles were more likely to be
% independently generated or generated together.
% ARG t : cell array containing times of the two gene expression
% profiles.
% ARG y : cell array containing log expression levels of the gene
% expression. In each component of the cell array different genes are in
% different columns and different time points in different rows.
% RETURN llratios : the log likelihood ratio between the combined and
% independent models.
%
% COPYRIGHT : Neil D. Lawrence, 2010
%
% SEEALSO : multimodelCreate, gpCreate

% GP
maxIters = 500;
display = 0;
tTemp = sort(t{1});
diffs = tTemp(2:end) - tTemp(1:end-1);
diffs(~diffs) = [];
typDiff = min(diffs);
invWidth = 1/(typDiff*typDiff);
%disp(1/invWidth)
options = gpOptions('ftc');
options.scale2var1 = true;
tfull = [t{1}; t{2}];
options.kern = kernCreate(tfull, options.kern);
options.kern.comp{1}.inverseWidth = invWidth;

optionsMulti = multimodelOptions('gp', 2, 'ftc');
optionsMulti.separate = [];
llComb = zeros(size(y{1}, 2), 1);
llInd = zeros(size(y{1}, 2), 1);
models = cell(size(y{1},2), 2);

for i = 1:size(y{1}, 2)
    fprintf('Start gene %d\n', i)

    % Check for missing data.
    if any(isnan(y{1}(:, i))) || any(isnan(y{2}(:, i)))
        options.isMissingData = true;
        options.isSpherical = false;
    else
        options.isMissingData = false;
        options.isSpherical = true;
    end
    % Fit a combined Gaussian process to the data.
    model = gpCreate(1, 1, tfull, [y{1}(:, i); y{2}(:, i)], options);
    model = gpOptimise(model, display, maxIters, 0);
    llComb(i) = gpLogLikelihood(model);
    models{i, 1} = model;
    % Plot regression.
    %{
    xstar = linspace(t{1}(1), t{1}(end),100)';
    [mu, S] = gpPosteriorMeanVar(models{i,1}, xstar);
    % %       S = S - exp(2*loghypers(3,h)); % subtract noise variance
    f = [mu+2*sqrt(S); flipdim(mu-2*sqrt(S),1)];
    clf, hFill = fill([xstar; flipdim(xstar,1)], f, [0 0 1], 'FaceAlpha', .1, 'EdgeColor', [0 0 1], 'EdgeAlpha', 0.1);
    datamax = max(max(y{1,2})); datamin = min(min(y{1,2})); % Data min/max for plot limits.
    ylim([datamin datamax]), xlim([min(xstar) max(xstar)]),
    hold on, plot(xstar, mu,'b-','LineWidth',2)
    plot(t{1}, y{1}(:, i), '+b', t{2}, y{2}(:, i), 'or', 'MarkerSize', 8);
    set(get(get(hFill,'Annotation'),'LegendInformation'), 'IconDisplayStyle','off');
    legend('GP','oxidised','non-oxidised')
    xlabel('time(months)','fontsize',12,'fontweight','bold'), ylabel('gene expression','fontsize',12,'fontweight','bold')
    %}

    % Fit independent Gaussian processes to the data.
    ymulti = cell(2, 1);
    ymulti{1} = y{1}(:, i);
    ymulti{2} = y{2}(:, i);
    optionsMulti.compOptions = options;
    multiModel = multimodelCreate(1, 1, t, ymulti, optionsMulti);
    % Make sure we scale using variance of combined data
    multiModel.comp{1}.scale = model.scale;
    multiModel.comp{1}.m = gpComputeM(multiModel.comp{1});
    multiModel.comp{2}.scale = model.scale;
    multiModel.comp{2}.m = gpComputeM(multiModel.comp{2});
    % Optimise the model
    multiModel.optimiser = 'scg';
    multiModel = modelOptimise(multiModel, [], [], display, maxIters, 0);
    llInd(i) = multimodelLogLikelihood(multiModel);
    models{i,2} = multiModel;
end
llratios = llInd - llComb;
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function [status,results] = mrtrix_brainmask_generate(in_file, out_file, verbose)

%
% Generate a brain mask in .mif format from a diffusion file in .mif format
%
% Parameters
% ----------
% in_file: string, full-path to a dwi file from which the
% out_file: the name of the resulting brain-mask file
%
% Returns
% -------
% status: return value from the system call; 0 (success), non-zero
% (failure)
% results: the results of the operation in stdout
%
% Notes
% -----
% http://www.brain.org.au/software/mrtrix/tractography/preprocess.html
%
%

if notDefined('verbose')
    verbose = true;
end

% This command string generates a brain-mask (quite liberal):
cmd_str = sprintf('mrconvert %s -coord 3 0 - | threshold - - | median3D - - | median3D - %s',...
                  in_file, out_file);

% Send the command to mrtrix:
[status, results] = mrtrix_cmd(cmd_str, verbose);

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [sttm] = tt_sparse_for_mv(ttm, cuttol)
%Sparsify the TT matrix in TT1.0 matrix format
%   [STTM]=TT_SPARSE_FOR_MV(TTM,[CUTTOL]) Computes the sparse version of the
%   matrix in the TT1.0 matrix format. May work for certain operators
%
%
% TT-Toolbox 2.2, 2009-2012
%
%This is TT Toolbox, written by Ivan Oseledets et al.
%Institute of Numerical Mathematics, Moscow, Russia
%webpage: http://spring.inm.ras.ru/osel
%
%For all questions, bugs and suggestions please mail
%ivan.oseledets@gmail.com
%---------------------------

if (nargin<2)||(isempty(cuttol))
    cuttol = 1e-14;
end;

d=size(ttm,1);

sttm=cell(d+2,1);
sttm{d+1}=zeros(d-1,1);
sttm{d+2}=zeros(d,1);

n=size(ttm{1},1);
m=size(ttm{1},2);
rm1=size(ttm{1},3);
sttm{d+1}(1)=rm1;
sttm{d+2}(1)=n;
if (~issparse(ttm{1}))
    sttm{1}=reshape(permute(ttm{1},[1,3,2]),[n*rm1,m]);
    sttm{1}(abs(sttm{1})/max(max(abs(sttm{1})))<cuttol)=0;
    sttm{1}=sparse(sttm{1});
else
    sttm{1} = ttm{1}; % let it be rank-1 first
end;

if (d>1)
    n=size(ttm{d},1);
    m=size(ttm{d},2);
    rm1=size(ttm{d},3);
    sttm{d+1}(d-1)=rm1;
    sttm{d+2}(d)=n;
    if (~issparse(ttm{1}))
        sttm{d}=reshape(permute(ttm{d},[1,3,2]),[n*rm1,m]);
        sttm{d}(abs(sttm{d})/max(max(abs(sttm{d})))<cuttol)=0;
        sttm{d}=sparse(sttm{d});
    else
        sttm{d} = ttm{d}; % let it be rank-1 first
    end;
end;

for i=2:d-1
    n=size(ttm{i},1);
    m=size(ttm{i},2);
    rm1=size(ttm{i},3);
    rm2=size(ttm{i},4);
    sttm{d+1}(i)=rm2;
    sttm{d+2}(i)=n;
    if (~issparse(ttm{1}))
        sttm{i}=reshape(permute(ttm{i},[1,4,3,2]),[n*rm2*rm1,m]);
        sttm{i}(abs(sttm{i})/max(max(abs(sttm{i})))<cuttol)=0;
        sttm{i}=sparse(sttm{i});
    else
        sttm{i} = ttm{i}; % let it be rank-1 first
    end;
end

end

author: oseledets

repo: TT-Toolbox


text:
% Shared Matting Matte Refinement
% This function implements the matte refinement approach described in
% Eduardo S. L. Gastal, Manuel M. Oliveira, "Shared Sampling for
% Real-Time Alpha Matting", Computer Graphics Forum, 2010.
% 'alphaHat' and 'confidences' parameters are typically obtained by a
% sampling-based natural matting algorithm. 'confidences' is filled by
% ones if not provided. Optional input parameter 'params' can be
% customized by editing the default values in the struct returned
% by 'getMattingParams('SharedMatting').
% - loc_*** define the parameters for the matting Laplacian.
% - refinement_mult determines how much trust is given to the initial
%   alpha estimation

function alpha = sharedMattingMatteRefinement(image, trimap, alphaHat, confidences, params, suppressMessages)
    abmtSetup
    tic;
    if ~exist('confidences', 'var') || isempty(confidences)
        confidences = ones(size(alphaHat(:,:,1)));
    end
    if ~exist('params', 'var') || isempty(params)
        params = getMattingParams('SharedMatting');
    end
    if ~exist('suppressMessages', 'var') || isempty(suppressMessages)
        suppressMessages = false;
    end
    if(~suppressMessages) display('Matte refinement via Shared Matting...'); end

    image = im2double(image);
    trimap = im2double(trimap(:,:,1));
    alphaHat = im2double(alphaHat(:,:,1));

    % Compute matting Laplacian
    unk = trimap < 0.8 & trimap > 0.2;
    dilUnk = imdilate(unk, ones(3, 3));
    if(~suppressMessages) display('     Computing matting Laplacian...'); end
    Lap = affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps));

    if(~suppressMessages) display('     Solving for alphas...'); end
    alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve, alphaHat, confidences, params.refinement_mult);

    alpha = reshape(alpha, [size(image, 1), size(image, 2)]);

    dur = toc;
    if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end
end

author: yaksoy

repo: AffinityBasedMattingToolbox


text:
function [rowAssignments,colAssignments,blocks] = findNonInteractingRowsAndColumns(A)
% Factors a matrix into non-interacting blocks of rows and columns. Each
% block consists of the smallest set of rows and the smallest set of
% columns such that entries of the matrix outside the columns in the rows
% are zero and vice-versa.
%
% Author: Jonathan Karr
% Affiliation: Covert Lab, Depatment of Bioengineering, Stanford University
% Last updated: 11/5/2008

%Test Cases
% A = [1 0 1;
%      0 0 0;
%      1 0 0];
%
% A = [0 0 1;
%      0 1 0;
%      1 0 0];
%
% A = [1 0 1;
%      0 1 0;
%      1 0 0];

%assign rows, columns to blocks
nBlocks=0;
rowAssignments=zeros(size(A,1),1);
colAssignments=zeros(size(A,2),1);

%assign empty rows and columns to single block
for i=1:size(A,1)
    if(isempty(find(A(i,:),1)))
        nBlocks=1;
        rowAssignments(i)=nBlocks;
    end
end
for i=1:size(A,2)
    if(isempty(find(A(:,i),1)))
        nBlocks=1;
        colAssignments(i)=nBlocks;
    end
end

%assign remaining rows and columns
for i=1:size(A,1)
    if(rowAssignments(i)~=0); continue; end;
    nBlocks=nBlocks+1;
    rowAssignments(i)=nBlocks;
    [rowAssignments,colAssignments]=assignRecursively_row(A,i,nBlocks,rowAssignments,colAssignments);
end
for i=1:size(A,2)
    if(colAssignments(i)~=0); continue; end;
    nBlocks=nBlocks+1;
    colAssignments(i)=nBlocks;
    [rowAssignments,colAssignments]=assignRecursively_col(A,i,nBlocks,rowAssignments,colAssignments);
end

%assemble blocks
blocks=cell(nBlocks,1);
for i=1:nBlocks
    blocks{i}=A(rowAssignments==i,colAssignments==i);
end

% helper function
function [rowAssignments,colAssignments]=assignRecursively_row(A,row,nBlocks,rowAssignments,colAssignments)
for i=1:size(A,2)
    if(colAssignments(i)==0 && A(row,i)~=0)
        colAssignments(i)=nBlocks;
        [rowAssignments,colAssignments]=assignRecursively_col(A,i,nBlocks,rowAssignments,colAssignments);
    end
end

%helper function
function [rowAssignments,colAssignments]=assignRecursively_col(A,col,nBlocks,rowAssignments,colAssignments)
for i=1:size(A,1)
    if(rowAssignments(i)==0 && A(i,col)~=0)
        rowAssignments(i)=nBlocks;
        [rowAssignments,colAssignments]=assignRecursively_row(A,i,nBlocks,rowAssignments,colAssignments);
    end
end

author: CovertLab

repo: WholeCell

save_path: github-repos/MATLAB/CovertLab-WholeCell


text:
function [dataOut3M,scanNum,planC] = reverseTransformAIOutput(scanNum,data3M,...
                             userOptS,planC)
% Undo pre-processing transformations (cropping, resampling, registration)
% AI 09/01/22

if ~exist('planC','var')
    global planC
end
indexS = planC{end};

isUniform = 0;
preserveAspectFlag = 0;
scanOptS = userOptS.input.scan(scanNum);

%% Get output type
output = userOptS.output;

%% Resize/pad mask to original dimensions

%Get parameters for resizing & cropping
cropS = scanOptS.crop;
if ~isempty(cropS) && isfield(cropS(1),'params')
    for cropNum = 1:length(cropS)
        cropS(cropNum).params.saveStrToPlanCFlag = 0;
    end
end

% cropS.params.saveStrToPlanCFlag=0;
[minr, maxr, minc, maxc, slcV, ~, planC] = getCropLimits(planC,data3M,...
    scanNum,cropS);
scanArray3M = planC{indexS.scan}(scanNum).scanArray;
sizV = size(scanArray3M);
%dataOut3M = zeros(sizV, 'uint32');
dataOut3M = zeros(sizV,class(data3M));
originImageSizV = [sizV(1:2), length(slcV)];

%Undo resizing & cropping
resizeS = scanOptS.resize;

for nMethod = length(resizeS):-1:1

    resizeMethod = resizeS(nMethod).method;

    if isfield(resizeS(nMethod),'preserveAspectRatio') && ...
            strcmp(resizeS(nMethod).preserveAspectRatio,'Yes')
        preserveAspectFlag = 1;
    end

    if nMethod<length(resizeS)
        data3M = dataOut3M;
    end
    switch lower(resizeMethod)

        case 'pad2d'

            dataOut3M = zeros(sizV, 'uint32');
            limitsM = [minr, maxr, minc, maxc];
            resizeMethod = 'unpad2d';
            originImageSizV = [sizV(1:2), length(slcV)];
            [~, dataOut3M(:,:,slcV)] = ...
                resizeScanAndMask([],data3M,originImageSizV,...
                resizeMethod,limitsM);

        case 'pad3d'
            resizeMethod = 'unpad3d';
            [~, tempData3M] = ...
                resizeScanAndMask([],data3M,sizV,resizeMethod);
            dataOut3M(:,:,slcV) = tempData3M;

        case 'padorcrop3d'
            resizeMethod = 'padorcrop3d';
            [~, tempData3M] = ...
                resizeScanAndMask([],data3M,sizV,resizeMethod);
            dataOut3M(:,:,slcV) = tempData3M;

        case 'padorcrop2d'
            resizeMethod = 'padorcrop2d';
            limitsM = [minr, maxr, minc, maxc];
            originImageSizV = [sizV(1:2), length(slcV)];
            [~, dataOut3M(:,:,slcV)] = ...
                resizeScanAndMask([],data3M,originImageSizV,...
                resizeMethod,limitsM);

        case 'padslices'
            resizeMethod = 'unpadslices';
            [~, dataOut3M] = ...
                resizeScanAndMask([],data3M,originImageSizV(3),...
                resizeMethod);

        case { 'bilinear', 'sinc', 'bicubic'}
            dataOut3M = zeros(sizV, 'uint32');
            limitsM = [minr, maxr, minc, maxc];

            outSizeV = [maxr-minr+1,maxc-minc+1,originImageSizV(3)];
            if strcmpi(output,'labelmap')
                % resize currData3M using nearest neighbor interpolation
                [~,tempData3M] = ...
                    resizeScanAndMask([],data3M,outSizeV,resizeMethod,...
                    limitsM,preserveAspectFlag);
            else
                % resize currData3M using nearest neighbor interpolation
                tempData3M = ...
                    resizeScanAndMask(data3M,[],outSizeV,resizeMethod,...
                    limitsM,preserveAspectFlag);
            end

            if size(limitsM,1)>1
                %2-D resize methods
                dataOut3M(:,:,slcV) = tempData3M;
            else
                %3-D resize methods
                dataOut3M(minr:maxr, minc:maxc, slcV) = tempData3M;
            end

        case 'none'
            dataOut3M(minr:maxr,minc:maxc,slcV) = data3M;
    end
end

%% Resample to original resolution
resampleS = scanOptS.resample;
if ~strcmpi(resampleS.method,'none')
    fprintf('\n Resampling output...\n');
    % Get the new x,y,z grid
    [xValsV, yValsV, zValsV] = getScanXYZVals(planC{indexS.scan}(scanNum));
    if yValsV(1) > yValsV(2)
        yValsV = fliplr(yValsV);
    end
    %Get original grid
    origScanNum = scanOptS.origScan;
    [xVals0V, yVals0V, zVals0V] = getScanXYZVals(planC{indexS.scan}(origScanNum));
    if yVals0V(1) > yVals0V(2)
        yVals0V = fliplr(yVals0V);
    end

    if strcmpi(output,'labelmap')
        %Resample mask ('nearest' interpolation)
        [~,dataOut3M] = resampleScanAndMask([],double(dataOut3M),xValsV,...
            yValsV,zValsV,xVals0V,yVals0V,zVals0V);
    else
        dataOut3M = resampleScanAndMask(double(dataOut3M),[],xValsV,...
            yValsV,zValsV,xVals0V,yVals0V,zVals0V);
    end

    scanNum = origScanNum;
end

end

author: cerr


text:
function test_ode_test ( )

%*****************************************************************************80
%
%% TEST_ODE_TEST tests the TEST_ODE library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 February 2013
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_ODE_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the TEST_ODE library.\n' );

  test_ode_test01 ( );
  test_ode_test02 ( );
  test_ode_test03 ( );
  test_ode_test04 ( );
  test_ode_test05 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_ODE_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end

repo: jburkardt-m


text:
function [R2_cv,mP,VP,R2] = PRESS_GLM(X,y,verbose)
% evaluates the PRESS-R2 cross-valuidation metric for a GLM
% function [R2_cv,mP,VP,R2] = PRESS_GLM(X,y,verbose)
% This function evaluates a prediction accuracy metric (PRESS-R2), in the
% context of a leave-one-out cross-validation scheme for a GLM. Note: it is
% based upon the predicted residual error sum of squares (PRESS) statistic.
% IN:
%   - X: nxp design matrix (independent variables)
%   - y: nxk dependent variables
%   - verbose: verbose flag
% OUT:
%   - R2_cv: PRESS-R2, i.e. percentage of predicted variance, where
%   predictions are derived for each fold of the leave-one-out
%   cross-validation scheme.
%   - mP: pxk OLS-estimates of the GLM parameters
%   - VP: pxk varianceso of the parameters estimates
%   - R2: coefficeint of determination

% Get time
et0 = clock;

% 0- check basic data dimension requirements
[n,p] = size(X);
if n < 3
    disp('Error: PRESS_GLM: data dimension is lower than 3!!')
    R2_cv = [];
    return
else
    if verbose
        fprintf(1,'PRESS_GLM: leave-one-out cross-validation scheme:...')
        fprintf(1,'%6.2f %%',0)
    end
end

% 1- perform leave-one-out scheme
Eg = NaN(size(y));
ii = 0;
for i=1:n
    X0 = X;
    X0(i,:) = [];
    y0 = y;
    y0(i,:) = [];
    b = pinv(X0'*X0)*X0'*y0;
    Eg(i,:) = X(i,:)*b;
    if verbose
        fprintf(1,repmat('\b',1,8))
        fprintf(1,'%6.2f %%',floor(100*i/n))
    end
end
if verbose
    fprintf(1,repmat('\b',1,8))
    fprintf(1,[' OK (took ',num2str(etime(clock,et0)),' seconds).'])
    fprintf(1,'\n')
end

% 2- evaluate PRESS and R2_cv
for i=1:size(y,2)
    PRESS = sum((y(:,i)-Eg(:,i)).^2);
    TSS(i) = sum((y(:,i)-mean(y(:,i))).^2);
    R2_cv(i) = 1 - PRESS./TSS(i);
end

% 3- fit the model conditional on all data and wrap-up
if verbose
    disp('PRESS_GLM: model fit on full-data...')
end
iX = pinv(X'*X);
mP = iX*X'*y;
for i=1:size(y,2)
    yhat = X*mP(:,i);
    RSS = sum((yhat-y(:,i)).^2);
    vhat = RSS./(n-p);
    C = vhat*iX;
    VP(:,i) = diag(C);
    R2(i) = 1 - RSS./TSS(i);
end
if verbose
    disp('PRESS_GLM: model fit on full-data... OK.')
end

author: MBB-team

repo: VBA-toolbox


text:
function r8col_mean_test ( )

%*****************************************************************************80
%
%% R8COL_MEAN_TEST tests R8COL_MEAN;
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2009
%
%  Author:
%
%    John Burkardt
%
  m = 3;
  n = 4;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8COL_MEAN_TEST\n' );
  fprintf ( 1, '  For an R8COL, an array of column vectors;\n' );
  fprintf ( 1, '  R8COL_MEAN computes means;\n' );

  k = 0;
  for i = 1 : m
    for j = 1 : n
      k = k + 1;
      a(i,j) = k;
    end
  end

  r8mat_print ( m, n, a, '  The array:' );

  mean = r8col_mean ( m, n, a );

  r8vec_print ( n, mean, '  Column means:' );

  return
end


text:
% PURPOSE: loads channel location information into an erpset
%
% FORMAT:
%
% ERP = erpchanedit(ERP, filename);
%
%
% See also borrowchanloc.m
%
%
% *** This function is part of ERPLAB Toolbox ***
% Author: Javier Lopez-Calderon && Johanna Kreither
% Center for Mind and Brain
% University of California, Davis,
% Davis, CA
% 2013

function [ERP, erpcom] = pop_erpchanedit(ERP, filename, varargin)
erpcom = '';
if nargin<1
        help erpchanedit
        return
end
if nargin==1
        [filename, filepath] = uigetfile({ ...
                '*.elp','Besa Spherical (*.elp)'; ...
                '*.sfp','BESA/EGI (*.sfp)'; ...
                '*.loc','EEGLAB (*.loc)'; ...
                '*.ced','EEGLAB (ASCII) (*.ced)'; ...
                '*.xyz','EEGLAB (Matlab) (*.xyz)'; ...
                '*.elc','EETrack (*.elc)'; ...
                '*.sph','Matlab (*.sph)'; ...
                '*.asc','Neuroscan (*.asc)'; ...
                '*.dat','Neuroscan (*.dat)'; ...
                '*.elp','Polhemus (*.elp)'; ...
                '*.*',  'All Files (*.*)'}, ...
                'Select channel location file', ...
                'MultiSelect', 'off');
        if isequal(filename,0)
                disp('User selected Cancel')
                return
        else
                filename = fullfile(filepath, filename);
                disp(['For channel location file user selected  ' filename ''])
        end

        %
        % Somersault
        %
        [ERP, erpcom] = pop_erpchanedit(ERP, filename, 'Warning', 'on', 'Saveas', 'on', 'History', 'gui');
        return
end

%
% Parsing inputs
%
p = inputParser;
p.FunctionName  = mfilename;
p.CaseSensitive = false;
p.addRequired('ERP');
p.addRequired('filename', @ischar);
% option(s)
p.addParamValue('Warning', 'off', @ischar);
p.addParamValue('Saveas', 'off', @ischar); % 'on', 'off'
p.addParamValue('History', 'script', @ischar); % history from scripting

p.parse(ERP, filename, varargin{:});

if strcmpi(p.Results.Warning,'on')
        wchmsgon = 1;
else
        wchmsgon = 0;
end
if strcmpi(p.Results.History,'implicit')
        shist = 3; % implicit
elseif strcmpi(p.Results.History,'script')
        shist = 2; % script
elseif strcmpi(p.Results.History,'gui')
        shist = 1; % gui
else
        shist = 0; % off
end
if ismember_bc2({p.Results.Saveas}, {'on','yes'})
        issaveas  = 1;
else
        issaveas  = 0;
end

%
% Subroutine
%
[ERP, serror] = erpchanedit(ERP, filename);
if isempty(serror)
        disp('User selected Cancel')
        return
end
if serror~=0
        msgboxText = ['pop_erpchanedit could not find channel locations info.\n\n'...
                'Hint: Identify channel(s) without location looking at '...
                'command window comments (Channel lookup). Try again excluding this(ese) channel(s).'];
        tittle = 'pop_scalplot:  error:';
        errorfound(sprintf(msgboxText), tittle);
        return
end

ERP.saved  = 'no';
erpcom = sprintf('%s = pop_erpchanedit( %s, ''%s'');', inputname(1), inputname(1), filename);

if issaveas
        [ERP, issave, erpcom_save] = pop_savemyerp(ERP,'gui','erplab', 'History', 'implicit');
        if issave>0
                % generate text command
                if issave==2
                        erpcom = sprintf('%s\n%s', erpcom, erpcom_save);
                        msgwrng = '*** Your ERPset was saved on your hard drive.***';
                else
                        msgwrng = '*** Warning: Your ERPset was only saved on the workspace.***';
                end
                fprintf('\n%s\n\n', msgwrng)
                try cprintf([0 0 1], 'COMPLETE\n\n');catch,fprintf('COMPLETE\n\n');end ;
        else
                ERP = ERPaux;
                msgwrng = 'ERPLAB Warning: Your changes were not saved';
                try cprintf([1 0.52 0.2], '%s\n\n', msgwrng);catch,fprintf('%s\n\n', msgwrng);end ;
        end
end
% get history from script. ERP
switch shist
        case 1 % from GUI
                displayEquiComERP(erpcom);
        case 2 % from script
                ERP = erphistory(ERP, [], erpcom, 1);
        case 3
                % implicit
                %ERP = erphistory(ERP, [], erpcom, 1);
                %fprintf('%%Equivalent command:\n%s\n\n', erpcom);
        otherwise %off or none
                erpcom = '';
end

%
% Completion statement
%
msg2end
return

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab


text:
function [irLin, irNonLin] = extractIR(sweep_response, invsweepfft)
% Extract impulse response from swept-sine response.
%   [irLin, irNonLin] = extractIR(sweep_response, invsweepfft)
%   Extracts the impulse response from the swept-sine response.  Use
%   synthSweep.m first to create the stimulus; then pass it through the
%   device under test; finally, take the response and process it with the
%   inverse swept-sine to produce the linear impulse response and
%   non-linear simplified Volterra diagonals.  The location of each
%   non-linear order can be calculated with the sweepRate - this will be
%   implemented as a future revision.
%
%   Developed at Oygo Sound LLC
%
%   Equations from Muller and Massarani, "Transfer Function Measurement
%   with Sweeps."
%
%   Modified by Jacob Donley (jrd089@uowmail.edu.au) (January 2017)

if diff(size(sweep_response))>0, sweep_response = sweep_response.'; end
if diff(size(invsweepfft))>0, invsweepfft = invsweepfft.'; end

N = length(invsweepfft);
sweepfft = fft(sweep_response,N);

%%% convolve sweep with inverse sweep (freq domain multiply)
invsweepfft = repmat(invsweepfft,1,size(sweepfft,2));
ir = real(ifft(invsweepfft.*sweepfft));

ir = circshift(ir, length(ir)/2, 1);

irLin = ir(end/2+1:end,:);
irNonLin = ir(1:end/2,:);

author: jtkim-kaist

repo: Speech-enhancement