text:
classdef MonitoringManager < handle

    properties (Access = public)
        monitoring
    end

    properties (Access = private)

    end

    properties (Access = private)

    end

    methods (Access = public)

        function obj = MonitoringManager(cParams)
            switch cParams.outputFunction.type
                case 'Academic'
                    obj.monitoring = AcademicMonitoring(cParams);
                case 'Topology'
                    obj.monitoring = TopologyMonitoring(cParams);
            end
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
%% DEMO_mesh_bifurcation_cut_loft_branch
% This demo shows how one can use logic operations to cut meshes and to
% extrude features from meshes. Here a bifurcated vessel is created by
% cutting a hole in a particular direction and by extruding the side-branch
% from this hole. The initial surface mesh is then thickened to produce a
% hexahedral mesh.

%%

clear; close all; clc;

%%
% Plot Settings
fontSize=15;
faceAlpha=0.8;
edgeColor=0.*ones(1,3);
lineWidth1=2;
markerSize1=50;
markerSize2=25;

%% Control parameters
pointSpacing=0.5;
trunkRadiusInner=3; %Radius
trunkLength=15; %Length
branchRadiusInner=2;
branchLength=6;
branchAngle=50;
cutDist=0.5;
branchBaseOffset=cutDist+pointSpacing;

wallThickness=0.5;
numElementsWall=2;

bezierTangency=0.5;

numSmootIterations=25;
smoothMethod='HC';
smoothIncludeSteps=2;

%% Derived parameters

%Get outer radii
trunkRadiusOuter=trunkRadiusInner+wallThickness;
branchRadiusOuter=branchRadiusInner+wallThickness;

%Have branch exit in middle
V_branch_origin=[0 0 -trunkRadiusOuter*tand(90-branchAngle)];

%% Create example geometry

%Guide curves and branches
R=euler2DCM([0 (branchAngle/180)*pi 0]);
R_90=euler2DCM([0 (90/180)*pi 0]);

%Main trunk
Vm=evenlySpaceCurve([0 0 -trunkLength/2; 0 0 trunkLength/2],pointSpacing);

N_branch_dir=[0 0 1]*R;
t=linspace(0,2*pi,ceil((2*pi*trunkRadiusOuter)./pointSpacing)+1)'; t=t(1:end-1);
Vc1=trunkRadiusOuter.*[cos(t) sin(t) zeros(size(t))];

Vc2_trunk=Vc1+Vm(end,:);
Vc1_trunk=Vc1+Vm(1,:);

%%

n1=vecnormalize(Vm(2,:)-Vm(1,:));
n2=vecnormalize(Vm(end,:)-Vm(end-1,:));
[Ft,Vt,Ct]=sweepLoft(Vc1_trunk,Vc2_trunk,n1,n2,Vm,[],0,0);

%% Ray trace branch direction onto trunk to get branch centre point

optionStruct.tolEps        = 1e-6;
optionStruct.triSide       = -1;
optionStruct.rayType       = 'ray';
optionStruct.exclusionType = 'inclusive';
optionStruct.paired        = 0;
P=triSurfRayTrace(V_branch_origin,N_branch_dir,Ft,Vt,optionStruct);
P=mean(P,1);

%%
% Visualization250

cFigure; hold on;
title('Main trunk');
hp1=gpatch(Ft,Vt,'w','k',faceAlpha);
hp2=quiverVec(V_branch_origin,N_branch_dir,branchLength*2,'r');
hp3=plotV(P,'b.','markerSize',markerSize1);
legend([hp1 hp2 hp3],{'Main trunk','Branch direction vector','Intersection point'})
axisGeom(gca,fontSize); camlight headlight;
gdrawnow;

%% Cut main trunk using side branch ellipse

t=linspace(0,2*pi,2*ceil((2*pi*branchRadiusOuter)./pointSpacing)+1)'; t=t(1:end-1);
b=branchRadiusOuter./cosd(90-branchAngle);
V_cut_ellipse=[b*cos(t) branchRadiusOuter.*sin(t) zeros(size(t))];
V_cut_ellipse=V_cut_ellipse*R_90+P;
[~,indRemove]=minDist(V_cut_ellipse,Vt);
indRemove=unique(indRemove);
logicFacesSelect=~any(ismember(Ft,indRemove),2);

Ft_precut=Ft(logicFacesSelect,:);

clear optionStruct
optionStruct.outputType='label';
[G,~,groupSize]=tesgroup(Ft_precut,optionStruct);
[~,indLargestGroup]=max(groupSize);
Ft_cut=Ft_precut(G==indLargestGroup,:);

Et_boundary_cut=patchBoundary(Ft_cut);
Et_boundary=patchBoundary(Ft);
Et_cut_boundary=Et_boundary_cut(~any(ismember(Et_boundary_cut,Et_boundary),2),:);
indCutCurve=edgeListToCurve(Et_cut_boundary);

clear optionStruct
optionStruct.numSeeds=numel(indCutCurve); %Number of seeds
optionStruct.waitBarOn=0; %Turn on/off waitbar
Dt_cut=meshDistMarch(Ft_cut,Vt,indCutCurve,optionStruct);
logicVerticesFar=Dt_cut>cutDist;
logicKeep=all(logicVerticesFar(Ft_cut),2);
Ft_cut=Ft_cut(logicKeep,:);

Et_boundary_cut=patchBoundary(Ft_cut);
Et_boundary=patchBoundary(Ft);
Et_cut_boundary=Et_boundary_cut(~any(ismember(Et_boundary_cut,Et_boundary),2),:);
indCutCurve=edgeListToCurve(Et_cut_boundary);

V_branch_curve_trunk=Vt(indCutCurve(1:end-1),:);
[~,~,Nt]=patchNormal(Ft_cut,Vt);

N_branch_curve_trunk=Nt(indCutCurve(1:end-1),:);

%%
% Visualization

cFigure; hold on;
title('Cut main trunk');
hp1=gpatch(Ft_cut,Vt,Dt_cut,'k',faceAlpha);
hp2=quiverVec(V_branch_origin,N_branch_dir,branchLength*2,'r');
hp3=plotV(V_cut_ellipse,'g.-','markerSize',markerSize2,'LineWidth',lineWidth1);
hp4=plotV(V_branch_curve_trunk,'b.-','markerSize',markerSize2,'LineWidth',lineWidth1);
legend([hp1 hp2 hp3 hp4],{'Cut main trunk','Branch direction vector','Branch base ellipse','Cut boundary'})
axisGeom(gca,fontSize); camlight headlight;
gdrawnow;

%% Define bezier start and end vector directions

[~,indNearest]=minDist(V_branch_curve_trunk(1,:),V_cut_ellipse);
dt=linspace(2*pi,0,size(V_branch_curve_trunk,1)+1)'; dt=dt(1:end-1);
dt=dt+t(indNearest);
V_cut_ellipse=[b*cos(dt) branchRadiusOuter.*sin(dt) zeros(size(dt))];
V_branch_curve_ellipse1=V_cut_ellipse*R_90+P+N_branch_dir.*(branchBaseOffset/cosd(90-branchAngle));

d1=sum(sqrt(sum((V_branch_curve_ellipse1-V_branch_curve_trunk).^2,2)));
d2=sum(sqrt(sum((flipud(V_branch_curve_ellipse1)-V_branch_curve_trunk).^2,2)));
if d2<d1
    V_branch_curve_ellipse1=flipud(V_branch_curve_ellipse1);
    dt=flipud(dt);
end

C1=vecnormalize(V_branch_curve_trunk-V_branch_curve_ellipse1);
D1=vecnormalize(cross(C1,N_branch_curve_trunk));
M1=vecnormalize(cross(D1,N_branch_curve_trunk));

M2=N_branch_dir(ones(size(M1,1),1),:);

%%
% Visualization

cFigure; hold on;
title('Cut main trunk');
hp1=gpatch(Ft_cut,Vt,'w','k',1);
hp2=plotV(V_branch_curve_trunk,'r.-','markerSize',markerSize2,'LineWidth',lineWidth1);
hp3=plotV(V_branch_curve_ellipse1,'g.-','markerSize',markerSize2,'LineWidth',lineWidth1);
hp4=quiverVec(V_branch_curve_trunk,M1,branchRadiusOuter/2,'r');
hp5=quiverVec(V_branch_curve_ellipse1,M2,branchRadiusOuter/2,'g');
legend([hp1 hp2 hp3 hp4 hp5],{'Cut main trunk','Cut boundary','Branch base ellipse','Branch base dir.','Branch vessel dir.'})
axisGeom(gca,fontSize); camlight headlight;
gdrawnow;

%% Create raw bezier surface

[Fb1,Vb1,X,Y,Z]=bezierLoft(V_branch_curve_trunk,V_branch_curve_ellipse1,M1,M2,pointSpacing,bezierTangency);

%%
% Visualization

cFigure; hold on;
title('Cut main trunk');
hp1=gpatch(Ft_cut,Vt,'w','k',1);
hp2=plotV(V_branch_curve_trunk,'r.-','markerSize',markerSize2,'LineWidth',lineWidth1);
hp3=plotV(V_branch_curve_ellipse1,'g.-','markerSize',markerSize2,'LineWidth',lineWidth1);
hp4=gpatch(Fb1,Vb1,'bw','k',1,0.5);

for q=1:size(X,2)
    hp5=plotV([X(:,q) Y(:,q) Z(:,q)],'k-','LineWidth',4);
end

legend([hp1 hp2 hp3 hp4 hp5],{'Cut main trunk','Cut boundary','Branch base ellipse','Branch base mesh','Bezier curves'})
axisGeom(gca,fontSize); camlight headlight;
gdrawnow;

%% Loft and merge side branch

endType=1;
switch endType
    case 1 %Circle
        V_branch_curve_ellipse2=branchRadiusOuter.*[cos(dt) sin(dt) zeros(size(dt))];
        V_branch_curve_ellipse2=V_branch_curve_ellipse2*R+P+N_branch_dir.*branchLength;
    case 2 %Ellipse
        V_branch_curve_ellipse2=V_branch_curve_ellipse1+N_branch_dir.*(branchLength-pointSpacing);
end

clear optionStruct
optionStruct.closeLoopOpt=1;
optionStruct.patchType='quad';
[Fb2,Vb2]=polyLoftLinear(V_branch_curve_ellipse1,V_branch_curve_ellipse2,optionStruct);
Fb2=fliplr(Fb2);

[F,V,C]=joinElementSets({Ft_cut,Fb1,Fb2},{Vt,Vb1,Vb2});
[F,V]=mergeVertices(F,V);
[F,V]=patchCleanUnused(F,V);

%% Constrained smoothing of branch base region

indSmoothRegion=F(C==2,:);
for q=1:1:smoothIncludeSteps
    indSmooth=F(any(ismember(F,indSmoothRegion),2),:);
    indSmoothRegion=indSmooth;
end
indRigid=F(~ismember(F,indSmooth));

clear optionStruct
optionStruct.Method=smoothMethod;
optionStruct.n=numSmootIterations;
optionStruct.RigidConstraints=indRigid;
V=patchSmooth(F,V,[],optionStruct);

%%
% Visualization

cFigure; hold on;
title('Merged surface mesh')
hp1=gpatch(F,V,C,'k',1,1);
hp2=patchNormPlot(F,V);
axisGeom(gca,fontSize); camlight headlight;
colormap(gjet); icolorbar;
legend([hp1 hp2],{'Bifurcation mesh','Normal directions'})
gdrawnow;

%% Thicken surface mesh to hexahedra

[E,V]=patchThick(F,V,-1,wallThickness,numElementsWall);
CE=repmat(C,numElementsWall,1);
[FE,CF_E,CF_type]=element2patch(E,CE);

%%
% Visualization

cFigure; hold on;
title('Hexahedral mesh')
gpatch(FE,V,'w','k');
axisGeom(gca,fontSize); camlight headlight;
gdrawnow;

%%

function [F,V,X,Y,Z]=bezierLoft(P1,P4,N1,N4,pointSpacing,f)

D12=sqrt(sum((P1-P4).^2,2));
numPoints=ceil(max(D12)./pointSpacing);
if numPoints<2
    numPoints=2;
end

P2=P1+D12.*f.*N1;
P3=P4-D12.*f.*N4;

X=zeros(numPoints,size(P1,1));
Y=zeros(numPoints,size(P1,1));
Z=zeros(numPoints,size(P1,1));
for q=1:1:size(P1,1)
    p=[P1(q,:); P2(q,:); P3(q,:); P4(q,:)]; %Control points
    V_bezier=bezierCurve(p,numPoints*2); %Compute bezier curve
    V_bezier=evenlySampleCurve(V_bezier,numPoints,'pchip'); %resample evenly
    X(:,q)=V_bezier(:,1);
    Y(:,q)=V_bezier(:,2);
    Z(:,q)=V_bezier(:,3);
end

%Create quad patch data
[F,V] = surf2patch(X,Y,Z);
I=[(1:size(Z,1)-1)' (1:size(Z,1)-1)' (2:size(Z,1))' (2:size(Z,1))' ];
J=[size(Z,2).*ones(size(Z,1)-1,1) ones(size(Z,1)-1,1) ones(size(Z,1)-1,1) size(Z,2).*ones(size(Z,1)-1,1)];
F_sub=sub2ind(size(Z),I,J);
F=[F;F_sub];
F=fliplr(F);

end

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function signal = flt_rmbase(varargin)
% Subtract a baseline from an data set, computed over the given baseline window.
% Signal = flt_rmbase(Signal, Window)
%
% Baseline correction is a commonly used method in the analysis of Event-Related Potentials, to
% factor out irrelevant variations in a signal's baseline. It is applied to an epoched data set, by
% specifying a sub-window that (typically) lies before the phenomena of interest, where the mean
% signal value in that window is subtracted from the entire signal (per channel or component).
% Baseline considerations are relevant for BCIs operating on slow cortical potentials, and can be
% implemented in a variety of other ways, too. One is to use a highpass filter (flt_iir, flt_fir,
% flt_select) to subtract low-frequency drifts in the signal. Another one is to add features from
% the signal which measure the baseline, for example one or a collection of windows of various
% lengths prior to the phenomenon of interest (in this case, the baseline correction is done by the
% machine learning algorithm that operates on these features). Paradigms which assign different
% weights for every time point in an epoch typically do baseline correction implicitly.
%
% In:
%   Signal          :   epoched data set to be processed
%
%   BaselineWindow  :   baseline window in seconds, e.g. [-0.5 -0.3]
%
% Out:
%   Signal  :   baseline-corrected data set
%
% Examples:
%   % remove the baseline of a continuous or epoched data set
%   eeg = flt_rmbase(eeg)
%
%   % in an epoched signal, subtract the average of the signal from 250ms before the time-locking
%   % event to 100ms after the time-locking event
%   eeg = flt_rmbase(eeg,[-0.25 0.1])
%
%   % pass the arguments by name
%   eeg = flt_rmbase('Signal'eeg,'BaselineWindow',[-0.25 0.1])
%
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-03-28

% flt_rmbase_version<1.0> -- for the cache

if ~exp_beginfun('filter') return; end

% only useful for epoch baselines
declare_properties('name','BaselineRemoval', 'depends','set_makepos', 'precedes','flt_window', 'independent_channels',true, 'independent_trials',true);

arg_define(varargin, ...
    arg_norep({'signal','Signal'}), ...
    arg({'wnd','BaselineWindow'}, [], [], 'Baseline window in seconds.','shape','row'));

if isempty(wnd)  %#ok<*NODEF>
    wnd = [-Inf Inf]; end

for f = utl_timeseries_fields(signal)
    signal.(f{1}) = double(signal.(f{1}));
    wnd = round(max(1,min(size(signal.(f{1}),2),(wnd-signal.xmin)*signal.srate+1)));
    signal.(f{1}) = signal.(f{1}) - repmat(mean(signal.(f{1})(:,wnd(1):wnd(2),:),2),[1,size(signal.(f{1}),2),1]);
end

exp_endfun;

repo: REST


text:
function [ know, x ] = p42_sol ( n )

%*****************************************************************************80
%
%% P42_SOL returns the solution for problem 42.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 March 2002
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the problem.  This value
%    is only needed for those problems with variable N.
%
%    Output, integer KNOW.
%    If KNOW is 0, then the solution is not known.
%    If KNOW is positive, then the solution is known, and is returned in X.
%
%    Output, real X(N), the solution, if known.
%
  know = 1;

  x = ones ( n, 1 );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function showboundary(node,elem,expr,varargin)
%% SHOWBOUNDARY boundary mesh plot
%
%    showboundary(node,elem) displays the boundary surface mesh of a
%    3-dimensional tetrahderon mesh given by node and elem matrices. The
%    boundary is found by the function findboundary3.
%
%    showboundary(node,elem,expr) displays the boundary of parts of the
%    mesh specificed by the expression. For example,
%    showboundary3(node,elem,'~(x>=0 & y>=0 & z>=0)') only shows the boundary
%    mesh for tetrahedrons not in the first quadrant.
%
%    showboundary(node,elem,expr,viewangle) changes the display angle. The
%    deault view angle is view(3).
%
%    showboundary(node,elem,expr,'param','value','param','value'...)
%    allows additional patch param/value pairs to be used when displaying
%    the mesh. For example, the default transparency parameter is set to
%    0.5. You can overwrite this value by using the param pair
%    ('FaceAlpha', value). The value has to be a number between 0 and 1.
%    Other parameters include: 'Facecolor', 'Edgecolor' etc.
%
%    To display the tetrahedron mesh in 3-d, use showmesh3. Notice that the
%    3-d graphical visulization is slow for large mesh data.
%
%   Example:
%     node = [-1,-1,-1; 1,-1,-1; 1,1,-1; -1,1,-1; -1,-1,1; 1,-1,1; 1,1,1; -1,1,1];
%     elem = [1,2,3,7; 1,6,2,7; 1,5,6,7; 1,8,5,7; 1,4,8,7; 1,3,4,7];
%     [node,elem] = uniformbisect3(node,elem);
%     subplot(1,2,1);
%     showboundary3(node,elem);
%     subplot(1,2,2);
%     showboundary3(node,elem,'~(x>=0 & y>=0 & z>=0)',[59,20]);
%
%   See also showboundary, showsolution3, showmesh.
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

if (nargin >= 3) && (any(expr))
    x = node(:,1);  y = node(:,2);  z = node(:,3); %#ok<*NASGU>
    incl = find(eval(expr));
    elem = elem(any(ismember(elem,incl),2),:);
end
[bdNode, bdFace] = findboundary3(elem); %#ok<*ASGLU>
if isempty(varargin)
    showmesh(node,bdFace);
else
    showmesh(node,bdFace,varargin{1:end});
end

repo: ifem


text:
function idmap = read_txt(infilename)
% Reads ids from a text file and constructs an Id_Map object.
% Inputs:
%   infilename: The name for the text file to read.
% Outputs:
%   idmap: An Id_Map object created from the information in the text
%     file.

assert(nargin==1)
assert(isa(infilename,'char'))

fid = fopen(infilename);
lines = textscan(fid,'%s%s');
fclose(fid);

idmap = Id_Map();
idmap.leftids = lines{1};
idmap.rightids = lines{2};

assert(idmap.validate())

end

author: nesl


text:
function res = bhp(im,thresh,n)

% inputs
% im is the fourier transform of the image
% thresh is the cutoff circle radius

%outputs
% res is the filtered image

[r,c]=size(im);
d0=thresh;

d=zeros(r,c);
h=zeros(r,c);

for i=1:r
    for j=1:c
     d(i,j)=  sqrt( (i-(r/2))^2 + (j-(c/2))^2);
    end
end

for i=1:r
    for j=1:c
      h(i,j)=  1 / (1+ (d0/d(i,j))^(2*n) ) ;
    end
end

for i=1:r
    for j=1:c
    res(i,j)=(h(i,j))*im(i,j);

    end
end

author: Sable

repo: mcbench-benchmarks


text:
function nSlices = numSlices(vw)
%
% nSlices = numSlices(view)
%
% Number of anatomy slices. Use slices(view,scan) to get
% the slices for a functional scan.
% For volumes/grays, this is a hack that simply returns 1 because
% the data are stored in a vector.
% For flats, there are 2 slices, one for each hemisphere.
% (except across-level flat views, this number is different
% in that case).
%
% djh, 2/21/2001
% ras, 10/04, support for flat level view
%
% jw, 6/2010: Obsolete. Use nSlices = viewGet(vw, 'numSlices') instead

warning('vistasoft:obsoleteFunction', 'numSlices.m is obsolete.\nUsing\n\tnSlices = viewGet(vw, ''numSlices'')\ninstead.');

nSlices = viewGet(vw, 'numSlices');

return

%
% global mrSESSION
%
% switch view.viewType
%     case 'Inplane'
%         nSlices = mrSESSION.inplanes.nSlices;
%     case {'Volume' 'Gray'}
%         nSlices = 1;
%     case 'Flat'
%         if isfield(view,'numLevels') % acr levels view
%             nSlices = 2 + sum(view.numLevels);
%         else
%             nSlices = 2;
%         end
% end
%
% return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function combo_test18 ( )

%*****************************************************************************80
%
%% COMBO_TEST18 tests NPART_ENUM, _RSF_LEX_RANK, _RSF_LEX_SUCCESSOR, _RSF_LEX_UNRANK.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 January 2011
%
%  Author:
%
%    John Burkardt
%
  npart = 3;
  n = 12;

  fprintf ( 1, ' \n' );
  fprintf ( 1, 'COMBO_TEST18\n' );
  fprintf ( 1, '  Partitions of N with NPART parts\n' );
  fprintf ( 1, '  in reverse standard form:\n' );
  fprintf ( 1, ' \n' );
  fprintf ( 1, '  NPART_ENUM enumerates,\n' );
  fprintf ( 1, '  NPART_RSF_LEX_RANK ranks,\n' );
  fprintf ( 1, '  NPART_RSF_LEX_SUCCESSOR lists;\n' );
  fprintf ( 1, '  NPART_RSF_LEX_UNRANK unranks.\n' );
%
%  Enumerate.
%
  npartitions = npart_enum ( n, npart );

  fprintf ( 1, ' \n' );
  fprintf ( 1, '  For N = %d\n', n );
  fprintf ( 1, '  and NPART = %d\n', npart );
  fprintf ( 1, '  the number of partitions is %d\n', npartitions );
  fprintf ( 1, ' \n' );
%
%  List.
%
  t = [];
  rank = -1;

  while ( 1 )

    rank_old = rank;

    [ t, rank ] = npart_rsf_lex_successor ( n, npart, t, rank );

    if ( rank <= rank_old )
      break
    end

    fprintf ( 1, '  %4d  ', rank );
    for i = 1 : npart
      fprintf ( 1, '%5d', t(i) );
    end
    fprintf ( 1, '\n' );

  end
%
%  Unrank.
%
  rank = floor ( npartitions / 3 );

  t = npart_rsf_lex_unrank ( rank, n, npart );

  fprintf ( 1, ' \n' );
  fprintf ( 1, '  The element of rank %d:\n', rank );
  fprintf ( 1, ' \n' );
  i4vec_print ( npart, t, '  The element:' );
%
%  Rank.
%
  rank = npart_rsf_lex_rank ( n, npart, t );

  fprintf ( 1, ' \n' );
  fprintf ( 1, '  The rank of the element is computed as %d:\n', rank );

  return
end


text:
% Surface fit artifact removal
[x,y] = meshgrid(0:.01:1);
z0 = exp(x+y);

znan = z0;
znan(20:50,40:70) = NaN;
znan(30:90,5:10) = NaN;
znan(70:75,40:90) = NaN;

z = inpaint_nans(znan,3);

% Comparison to griddata
k = isnan(znan);
zk = griddata(x(~k),y(~k),z(~k),x(k),y(k));
zg = znan;
zg(k) = zk;

close all
figure
surf(z0)
title 'Original surface'

figure
surf(znan)
title 'Artifacts (large holes) in surface'

figure
surf(zg)
title(['Griddata inpainting (',num2str(sum(isnan(zg(:)))),' NaNs remain)'])

figure
surf(z)
title 'Inpainted surface'

figure
surf(zg-z0)
title 'Griddata error surface'

figure
surf(z-z0)
title 'Inpainting error surface (Note z-axis scale)'

author: goGPS-Project


text:
function [ortho_mask_IND,ortho_mask_I,ortho_mask_J,ortho_mask_K]=oblique_mask(V_ort_vec,IND_mask,mask_height,siz,v,opt)

[I_mask,J_mask,K_mask] = ind2sub(siz,IND_mask);

%Factor for number of points across mask
f=1+(2.*abs(sqrt((V_ort_vec(:,1)-V_ort_vec(:,2)).^2+(V_ort_vec(:,2)-V_ort_vec(:,3)).^2+(V_ort_vec(:,1)-V_ort_vec(:,3)).^2)-sqrt(2))./sqrt(2));
f=max(f(:));

%Defining orthogonal neighbourhoods
if size(V_ort_vec,1)~=numel(IND_mask)
    V_ort_vec=ones(numel(IND_mask),1)*V_ort_vec;
end
V_ort_vec=V_ort_vec.*mask_height; %Lengthen orthogonal vector by mask_height
V_ort_vec_X=V_ort_vec(:,1); V_ort_vec_Y=V_ort_vec(:,2); V_ort_vec_Z=V_ort_vec(:,3);

%Creating mask points in cartesian coordinates
n_ort=ceil(f.*((2.*mask_height)./min(v))); %Number of points from -vector to +vector
n_ort=n_ort+iseven(n_ort); %Ensure its uneven so middle element will be self
ortho_mask_X=linspacen(-V_ort_vec_X,V_ort_vec_X,n_ort);
ortho_mask_Y=linspacen(-V_ort_vec_Y,V_ort_vec_Y,n_ort);
ortho_mask_Z=linspacen(-V_ort_vec_Z,V_ort_vec_Z,n_ort);

%Creating mask points in image coordinates
ortho_mask_I=round(ortho_mask_Y./v(1))+I_mask*ones(1,size(ortho_mask_Y,2));
ortho_mask_J=round(ortho_mask_X./v(2))+J_mask*ones(1,size(ortho_mask_Y,2));
ortho_mask_K=round(ortho_mask_Z./v(3))+K_mask*ones(1,size(ortho_mask_Y,2));

%Removing out of bound indices
L_not_valid= (ortho_mask_I<1 | ortho_mask_I>siz(1)) | ...
             (ortho_mask_J<1 | ortho_mask_J>siz(2)) |...
             (ortho_mask_K<1 | ortho_mask_K>siz(3));
ortho_mask_IND=NaN(size(L_not_valid));
ortho_mask_ind = sub2ind(siz,ortho_mask_I(~L_not_valid),ortho_mask_J(~L_not_valid),ortho_mask_K(~L_not_valid));
ortho_mask_IND(~L_not_valid)=ortho_mask_ind;

%Removing doubles
[ortho_mask_IND_sort,J_sort] = sort(ortho_mask_IND,2); %Sorting to prepare for diff
[j_sort,J_sort_inv] = sort(J_sort,2); clear j_sort; %Determine inverse of sorting
I_sort=(1:size(ortho_mask_IND,1))'*ones(1,size(ortho_mask_IND,2));
IND_sort_inv=sub2ind(size(ortho_mask_IND),I_sort,J_sort_inv); %Inverse indices
L_double=[ones(size(ortho_mask_IND_sort,1),1) diff(ortho_mask_IND_sort,1,2)]==0; %Find doubles
ortho_mask_IND_sort(L_double)=NaN; %Set doubles to NaN
ortho_mask_IND=ortho_mask_IND_sort(IND_sort_inv); %Fixing order

%Ensuring only centre element is self
L_self=(ortho_mask_IND-(IND_mask*ones(1,size(ortho_mask_IND,2))))==0;
ortho_mask_IND(L_self)=NaN;
ortho_mask_IND(:,round(size(ortho_mask_IND,2)./2))=IND_mask;

if opt==1
    %Removing non-mask elements
    L_mask=ismembc(ortho_mask_IND,sort(IND_mask));
    ortho_mask_IND(~L_mask)=NaN;
    ortho_mask_I(~L_mask)=NaN;
    ortho_mask_J(~L_mask)=NaN;
    ortho_mask_K(~L_mask)=NaN;
end

end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.


text:
meas_model = LinearGaussianX('NumMeasDims',2,'NumStateDims',2,'Mapping', [1,2], 'MeasurementErrVariance', 1);
H = meas_model.matrix();
R = meas_model.covar();
measurements = [10 15;10 15];

dist = GaussianDistributionX([1;1], 10*eye(2));

numParticles = 1000;
particles = dist.random(numParticles);
weights = repmat(1/numParticles,1,numParticles);

xPred = dist.Mean;
PPred=dist.Covar;
[yPred, S, K] = KalmanFilterX.predictMeasurement_(xPred,PPred,H,R);

lik = meas_model.pdf(measurements,particles);
l = meas_model.pdf(measurements,xPred,PPred);

% Data assoc
lambda = 1/10000;
Pd = 0.9;
hypothesiser = EfficientHypothesisManagementX();

W = hypothesiser.hypothesise([lambda*(1-Pd); sum(Pd*lik,2)]');
% W = lambda*(1-Pd);
% W = [W Pd*sum(l)];
% W = W./sum(W);
%
% Wp = lambda*(1-Pd);
% Wp = [Wp Pd*sum(lik)];
% Wp = Wp./sum(Wp);
%W = [0.009 1-0.009];

%[xPost, PPost] = KalmanFilterX.update_(xPred,dist.Covar,measurements,yPred, S, K);
[xPost, PPost] = KalmanFilterX.updatePDA_(xPred,PPred,measurements,W,yPred, S, K);

[newWeights] = ParticleFilterX_UpdatePDA(@(y,x)meas_model.pdf(y,x),measurements,particles,weights,W,lik);
XPost = particles*newWeights';
resampler = SystematicResamplerX();
new_weights = weights.*lik;
%new_weights =  W(1)*dist.Weights + sum(W(2:end).*lik.*dist.Weights,1);
new_weights = new_weights./sum(new_weights);
[new_particles, new_weights] = resampler.resample(particles,new_weights);

new_dist = ParticleDistributionX(new_particles, new_weights);

% [X,Y] = meshgrid(-3:0.1:5,0:0.1:8);
% Z = dist.pdf([X;Y]);
% for i=1:size(X,1)
%     Z(i,:) = dist.pdf([X;Y]);
% end

figure;
hold on;
[bandwidth,Z,X,Y]=kde2d([particles, measurements+meas_model.random(numParticles)]');
%contour3(X,Y,density,50);
h = surf(X,Y,Z);
shading interp
colormap(jet(3000))
[bandwidth,Z,X,Y]=kde2d([new_dist.Particles, measurements+meas_model.random(numParticles)]');
%contour3(X,Y,density,50);
h = surf(X,Y,Z);
shading interp
colormap(jet(3000))
plot(measurements(1,:),measurements(2,:),'r*');
plot_gaussian_ellipsoid(dist.Particles*dist.Weights',weightedcov(dist.Particles,dist.Weights));
plot_gaussian_ellipsoid(new_dist.Particles*new_dist.Weights',weightedcov(new_dist.Particles,new_dist.Weights));

author: sglvladi

repo: TrackingX

save_path: github-repos/MATLAB/sglvladi-TrackingX


text:
function h = p02_fh ( p, varargin )

%*****************************************************************************80
%
%% P02_FH returns a mesh size function for problem 2.
%
%  Licensing:
%
%    (C) 2004 Per-Olof Persson.
%    See COPYRIGHT.TXT for details.
%
%  Modified:
%
%    06 February 2006
%
%  Reference:
%
%    Per-Olof Persson and Gilbert Strang,
%    A Simple Mesh Generator in MATLAB,
%    SIAM Review,
%    Volume 46, Number 2, June 2004, pages 329-345.
%
%  Parameters:
%
%    Input, real P(NP,ND), the point coordinates.
%
%    Input, VARARGIN, room for extra arguments.
%
%    Output, real H(NP,1), the mesh size function.
%
  np = size ( p, 1 );
  h = ones ( np, 1 );

  return
end


text:
function [g1L, g2L, g3L, g4L] = sdlfmvXsdlfmvKernGradientICBlock(lfmKern1, ...
    lfmKern2, tInit1, tInit2, kyy, kyv, kvy, kvv, i, j, generalConst, ...
    generalConstGrad, gkyy1, gkyy2, gkyy3, gkyy4, gkyv1, gkyv2, ...
    gkyv3, gkyv4, gkvy1, gkvy2, gkvy3, gkvy4, gkvv1, gkvv2, gkvv3, gkvv4)

% SDLFMVXSDLFMVKERNGRADIENTICBLOCK Partial derivatives initial conditions
%
% COPYRIGHT : Mauricio A. Alvarez, 2010

% KERN

g1L = cell(2);
g2L = cell(2);
g3L = cell(2);
g4L = cell(2);

typeParam = {'sdlfmv', 'sdlfmv'};

% Compute for tInit1(1) and tInit2(2)

[g1L{1,2}, g2L{1,2}, g3L{1,2}] = sdlfmvXsdlfmvKernGradientBlock(lfmKern1, lfmKern2, tInit1(1), ...
    tInit2(2), kyy, kyv, kvy, kvv, i, j, generalConst, generalConstGrad, 1);

g1Plus = sdlfmaXsdlfmvKernComputeBlock(lfmKern1, lfmKern2, tInit1(1), ...
    tInit2(2), kyy, kyv, kvy, kvv, i, j, generalConst);

g2Plus = sdlfmaXsdlfmvKernComputeBlock(lfmKern2, lfmKern1, tInit2(2), ...
    tInit1(1), kyy, kvy, kyv, kvv, j, i, generalConst');

if (i==1 && j==1) || (i==1) && (j~=1)

    if i~=1 || j~=1
        [gkyy1IC, gkyy2IC, gkyy3IC, gkyy4IC] = sdlfmXsdlfmKernGradientIC(lfmKern1, lfmKern2, ...
            tInit1(1), tInit2(2), gkyy1{i,j}, gkyy2{i,j}, gkyy3{i,j}, gkyy4{i,j}, gkyv1{i,j}, gkyv2{i,j}, ...
            gkyv3{i,j}, gkyv4{i,j}, gkvy1{i,j}, gkvy2{i,j}, gkvy3{i,j}, gkvy4{i,j}, gkvv1{i,j}, gkvv2{i,j}, ...
            gkvv3{i,j}, gkvv4{i,j}, 1, typeParam);
        for k=1:3
            g1L{1,2}{k} = g1L{1,2}{k} + gkyy1IC{k};
            g2L{1,2}{k} = g2L{1,2}{k} + gkyy2IC{k};
        end
        cLength = length(gkyy3IC);
        g3L{1,2}(1:cLength) = g3L{1,2}(1:cLength) + gkyy3IC;
        g3L{1,2}(i)   = g3L{1,2}(i) + g1Plus;
        g3L{1,2}(j+1) = g2Plus;
        g4L{1,2} = gkyy4IC;
    else
        g3L{1,2}(i)   = g3L{1,2}(i) + g1Plus;
        g3L{1,2}(j+1) = g2Plus;
        g4L{1,2} = sdlfmKernMeanCovPartial(lfmKern1(1), lfmKern2(1), tInit1(1), ...
            tInit2(2), 1, typeParam);
    end
end

% Compute for tInit1(2) and tInit2(1)

[g1L{2,1}, g2L{2,1}, g3L{2,1}] = sdlfmvXsdlfmvKernGradientBlock(lfmKern1, lfmKern2, tInit1(2), ...
    tInit2(1), kyy, kyv, kvy, kvv, i, j, generalConst, generalConstGrad, 1);

g1Plus = sdlfmaXsdlfmvKernComputeBlock(lfmKern1, lfmKern2, tInit1(2), ...
    tInit2(1), kyy, kyv, kvy, kvv, i, j, generalConst);

g2Plus = sdlfmaXsdlfmvKernComputeBlock(lfmKern2, lfmKern1, tInit2(1), ...
    tInit1(2), kyy, kvy, kyv, kvv, j, i, generalConst');

if (i==1 && j==1) || (i~=1) && (j==1)
    if i~=1 || j~=1
        [gkyy1IC, gkyy2IC, gkyy3IC, gkyy4IC] = sdlfmXsdlfmKernGradientIC(lfmKern1, lfmKern2, ...
            tInit1(2), tInit2(1), gkyy1{i,j}, gkyy2{i,j}, gkyy3{i,j}, gkyy4{i,j}, gkyv1{i,j}, gkyv2{i,j}, ...
            gkyv3{i,j}, gkyv4{i,j}, gkvy1{i,j}, gkvy2{i,j}, gkvy3{i,j}, gkvy4{i,j}, gkvv1{i,j}, gkvv2{i,j}, ...
            gkvv3{i,j}, gkvv4{i,j}, 1, typeParam);
        for k=1:3
            g1L{2,1}{k} = g1L{2,1}{k} + gkyy1IC{k};
            g2L{2,1}{k} = g2L{2,1}{k} + gkyy2IC{k};
        end
        cLength = length(gkyy3IC);
        g3L{2,1}(1:cLength) = g3L{2,1}(1:cLength) + gkyy3IC;
        g3L{2,1}(j)   =  g3L{2,1}(j) + g2Plus;
        g3L{2,1}(i+1) =  g1Plus;
        g4L{2,1} = gkyy4IC;
    else
        g3L{2,1}(j)   =  g3L{2,1}(j) + g2Plus;
        g3L{2,1}(i+1) =  g1Plus;
        g4L{2,1} = sdlfmKernMeanCovPartial(lfmKern1(1), lfmKern2(1), tInit1(2), ...
            tInit2(1), 1, typeParam);
    end
end

% Compute for tInit1(2) and tInit2(2)

[g1L{2,2}, g2L{2,2}, g3Local] = sdlfmvXsdlfmvKernGradientBlock(lfmKern1, lfmKern2, tInit1(2), ...
    tInit2(2), kyy, kyv, kvy, kvv, i, j, generalConst, generalConstGrad, 1);

g1Plus = sdlfmaXsdlfmvKernComputeBlock(lfmKern1, lfmKern2, tInit1(2), ...
    tInit2(2), kyy, kyv, kvy, kvv, i, j, generalConst);

g2Plus = sdlfmaXsdlfmvKernComputeBlock(lfmKern2, lfmKern1, tInit2(2), ...
    tInit1(2), kyy, kvy, kyv, kvv, j, i, generalConst');

if i~=1 || j~=1
    [gkyy1IC, gkyy2IC, gkyy3IC, gkyy4IC] = sdlfmXsdlfmKernGradientIC(lfmKern1, lfmKern2, ...
        tInit1(2), tInit2(2), gkyy1{i,j}, gkyy2{i,j}, gkyy3{i,j}, gkyy4{i,j}, gkyv1{i,j}, gkyv2{i,j}, ...
        gkyv3{i,j}, gkyv4{i,j}, gkvy1{i,j}, gkvy2{i,j}, gkvy3{i,j}, gkvy4{i,j}, gkvv1{i,j}, gkvv2{i,j}, ...
        gkvv3{i,j}, gkvv4{i,j}, 1, typeParam);
    if i>=2 && j>=2
        g1L{2,2}{1} = g1L{2,2}{1} + gkyy1IC{1};
        g2L{2,2}{1} = g2L{2,2}{1} + gkyy2IC{1};
        g1L{2,2}{2} = [gkyy1IC{2} g1L{2,2}{2}];
        g2L{2,2}{2} = [gkyy2IC{2} g2L{2,2}{2}];
        g1L{2,2}{3} = [gkyy1IC{3} g1L{2,2}{3}];
        g2L{2,2}{3} = [gkyy2IC{3} g2L{2,2}{3}];
    else
        for k=1:3
            g1L{2,2}{k} = g1L{2,2}{k} + gkyy1IC{k};
            g2L{2,2}{k} = g2L{2,2}{k} + gkyy2IC{k};
        end
    end
    cLength = length(g3Local);
    g3L{2,2} = zeros(1, cLength+1);
    g3L{2,2}(1:cLength) = g3L{2,2}(1:cLength) + g3Local;
    cLength = length(gkyy3IC);
    g3L{2,2}(1:cLength) = g3L{2,2}(1:cLength) + gkyy3IC;
    g3L{2,2}(i+1) = g3L{2,2}(i+1) + g1Plus;
    g3L{2,2}(j+1) = g3L{2,2}(j+1) + g2Plus;
    g4L{2,2} = gkyy4IC;
else
    g3L{2,2} = g3Local;
    g3L{2,2}(i+1) = g1Plus;
    g3L{2,2}(j+1) = g3L{2,2}(j+1) + g2Plus;
    g4L{2,2} = sdlfmKernMeanCovPartial(lfmKern1(1), lfmKern2(1), tInit1(2), ...
    tInit2(2), 1, typeParam);
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function i4vec_indexed_heap_d_insert_test ( )

%*****************************************************************************80
%
%% I4VEC_INDEXED_HEAP_D_INSERT_TEST tests I4VEC_INDEXED_HEAP_D_INSERT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 September 2014
%
%  Author:
%
%    John Burkardt
%
  m = 20;
  n_max = 20;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'I4VEC_INDEXED_HEAP_D_INSERT_TEST\n' );
  fprintf ( 1, '  For an indexed I4VEC,\n' );
  fprintf ( 1, '  I4VEC_INDEXED_HEAP_D_INSERT inserts a value into the heap.\n' );
%
%  Set the data array.  To keep things easy, we will use the indicator vector.
%
  a = i4vec_indicator1 ( m );
%
%  The index array will initially be a random subset of the numbers 1 to M,
%  in random order.
%
  n = 5;
  indx(1:11,1) = [ 9, 2, 8, 14, 5, 7, 15, 1, 19, 20, 3 ]';

  i4vec_print ( m, a, '  The data vector:' );
  i4vec_print ( n, indx, '  The index vector:' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  A(INDX):\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '  %4d  %4d\n', i, a(indx(i)) );
  end
%
%  Create a descending heap from the indexed array.
%
  indx = i4vec_indexed_heap_d ( n, a, indx );

  i4vec_print ( n, indx, '  The index vector after heaping:' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  A(INDX) after heaping:\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '  %4d  %4d\n', i, a(indx(i)) );
  end
%
%  Insert five entries, and monitor the maximum.
%
  for i = 1 : 5

    indx_insert = indx(n+1);

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Inserting value %d\n', a(indx_insert) );

    [ n, indx ] = i4vec_indexed_heap_d_insert ( n, a, indx, indx_insert );

    indx_max = i4vec_indexed_heap_d_max ( n, a, indx );

    fprintf ( 1, '  Current maximum is %d\n', a(indx_max) );

  end
  i4vec_print ( m, a, '  The data vector after insertions:' )
  i4vec_print ( n, indx, '  The index vector after insertions:' )
  fprintf ( 1, '\n' );
  fprintf ( 1, '  A(INDX) after insertions:\n' );
  fprintf ( 1, '\n' );
  for i = 1 : n
    fprintf ( 1, '  %4d  %4d\n', i, a(indx(i)) );
  end

  return
end


text:
classdef TestInitWideAngleProjMap
    %TestInitWideAngleProjMap

    methods (Static)
        function test_1
            camMat = eye(3);
            distCoeffs = zeros(1,4);
            sz = [50 100];  % [w,h]
            dw = 80;        % w
            [map1,map2,scale] = cv.initWideAngleProjMap(...
                camMat, distCoeffs, sz, dw, 'M1Type','int16');
            validateattributes(map1, {'int16'}, {'ncols',dw, 'ndims',3});
            validateattributes(map2, {'uint16'}, {'ncols',dw, 'ndims',2});
            validateattributes(scale, {'numeric'}, {'scalar'});
        end

        function test_error_argnum
            try
                cv.initWideAngleProjMap();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function layers = spp_layers_in_gpu(layers)
% layers = spp_layers_in_gpu(layers)
%   create each layers weight array in gpu
%
% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Shaoqing Ren
%
% This file is part of the SPP 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.
% ---------------------------------------------------------

    for i = 1:length(layers)
       if isempty(layers(i).weights)
          continue;
       end
       layers(i).weights_gpu = layers(i).weights;
       for j = 1:length(layers(i).weights)
            layers(i).weights_gpu{j} = gpuArray(layers(i).weights{j});
       end
    end
end

author: ShaoqingRen


text:
function [PSK_BER, PSK_SER] = PSK_Simulate(SNRs, varargin)

% Run M_PSK_Model.mdl to generate Monte Carlo simulation results for
% PSK signals over AWGN channels

if nargin>1
    simLines = varargin{1};
end

open_system('M_PSK_Model')
maxNumBits = 1e7;
maxNumErrs = 100;
Ts = 1e-6;

% SNRs = -4:28;
PSK_BER = zeros(5,length(SNRs));
PSK_SER = zeros(5,length(SNRs));

S = simset('SrcWorkspace','current', 'DstWorkspace','current');
k=1;
for M = [2, 4, 8, 16, 32, 64]
    for EbNo = SNRs
        % Don't try to simulate BER < 1e-5 (too long!)
        tBER = berawgn(EbNo,'psk',M,'nondiff');
        if (tBER>1e-5)
            fprintf('Simulating %i-PSK, %idB, ', M, EbNo)
            sim('M_PSK_Model',[], S)
            PSK_BER(k,EbNo+6) = BER(1);
            PSK_SER(k,EbNo+6) = SER(1);
            fprintf('BER=%e, SER=%e\n', BER(1), SER(1))
            % Add the result to the plot if it exists
            if nargin>1
                set(simLines(k),'YData',PSK_BER(k,:))
            end
        end
    end
    drawnow
    k=k+1;
end
close_system('M_PSK_Model')


text:
function c = stringToCellArray(s)
%stringToCellArray Convert string with newlines to cell array of strings.
%   C = stringToCellArray(S) converts the input string S to a cell array of
%   strings, breaking up S at new lines.

%   Steven L. Eddins
%   Copyright 2009 The MathWorks, Inc.

if isempty(s)
    c = cell(0, 1);
else
    c = textscan(s, '%s', 'Delimiter', '\n', 'Whitespace', '');
    c = c{1};
end

author: ricedsp


text:
function [ebsd, header] = loadEBSD_h5(fname,varargin)

if ~exist(fname,'file'), error(['File ' fname ' not found!']); end

ginfo = locFindEBSDGroups(fname);

if numel(ginfo) > 0

  groupNames = {ginfo.Name};

  patternMatch = false(size(groupNames));
  for k=1:numel(varargin)
    if ischar(varargin{k})
      patternMatch = patternMatch | strncmpi(groupNames,varargin{k},numel(varargin{k}));
    end
  end

  if nnz(patternMatch) == 0
    if length(ginfo) > 1
      [sel,ok] = listdlg('ListString',{ginfo.Name},'ListSize',[400 300]);

      if ok
        ginfo = ginfo(sel);
      else
        return
      end
    end
  else
    ginfo = ginfo(patternMatch);
  end
end

assert(numel(ginfo) > 0);

if check_option(varargin,'check'), ebsd = EBSD; header = {}; return; end

try
  for k = 1:numel(ginfo)
    kGroup = ginfo(k);

    CS = locReadh5Phase(fname,kGroup);

    kGroupData = kGroup.Groups(1).Datasets;

    props = struct;

    for j=1:numel(kGroupData)

      if length(kGroupData(j).ChunkSize) > 1, continue; end
      data = double(h5read(fname,[kGroup.Groups(1).Name '/' kGroupData(j).Name]));

      name = strrep(kGroupData(j).Name,' ','_');

      name = strrep(name,'X_Position','x');
      name = strrep(name,'Y_Position','y');
      name = strrep(name,'X_SAMPLE','x');
      name = strrep(name,'Y_SAMPLE','y');

      name = regexprep(name,'phi','Phi','ignorecase');
      name = regexprep(name,'phi1','phi1','ignorecase');
      name = regexprep(name,'phi2','phi2','ignorecase');

      props.(name) = data(:);
    end

    % sometimes not indexed orientations are marked as 4*pi
    notIndexed = isappr(props.phi1,4*pi,1e-5);
    if all(props.phi1(~notIndexed)<=2.001*pi) ...
        && all(props.Phi(~notIndexed)<=1.001*pi) ...
        && all(props.phi2(~notIndexed)<=2.001*pi)

      props.phi1(notIndexed) = NaN;
      props.phi2(notIndexed) = NaN;
      props.Phi(notIndexed) = NaN;

      isDegree = 1;

    else
      isDegree = degree;
    end

    rot = rotation.byEuler(props.phi1*isDegree,props.Phi*isDegree,props.phi2*isDegree);
    phases = props.Phase;

    props = rmfield(props,{'Phi','phi1','phi2','Phase'});

    ebsd = EBSD(rot,phases,CS,props);

    ind = props.x > -11111;
    ebsd = ebsd(ind);
    ebsd.unitCell = calcUnitCell([ebsd.prop.x,ebsd.prop.y]);

    if length(kGroup.Groups) > 1
      header = h5group2struct(fname,kGroup.Groups(2));
    else
      header = [];
    end

  end
end

end

function [ginfo] = locFindEBSDGroups(fname)

info = h5info(fname,'/');

ginfo = struct('Name',{},...
  'Groups',{},...
  'Datasets',{},...
  'Datatypes',{},...
  'Links',{},...
  'Attributes',{});

ginfo = locGr(fname, info.Groups,ginfo);
end

function [ginfo] = locGr(fname,group,ginfo)

if ~isempty(group)

  for k=1:numel(group)
    attr  = group(k).Attributes;
    name = group(k).Name;

    if (~isempty(attr) && check_option({attr.Value},'EBSD')) || strcmp(name(end-4:end),'/EBSD')

      ginfo(end+1) = group(k);

    end

    [ginfo] = locGr(fname,group(k).Groups,ginfo);
  end
end
end

function CS = locReadh5Phase(fname,group)
% load phase informations from h5 file

group = group.Groups(strcmp([group.Name '/Header'],{group.Groups.Name}));
token = [group.Name '/Phase'];
group = group.Groups(strncmp(token,{group.Groups.Name},length(token)));

for iphase = 1:numel(group.Groups)

  try
    mineral = strtrim(char(h5read(fname,[group.Groups(iphase).Name '/MaterialName'])));
  catch
    mineral = strtrim(char(h5read(fname,[group.Groups(iphase).Name '/Name'])));
  end
  formula = strtrim(char(h5read(fname,[group.Groups(iphase).Name '/Formula'])));

  try
    lattice(1) = h5read(fname,[group.Groups(iphase).Name '/Lattice Constant a']);
    lattice(2) = h5read(fname,[group.Groups(iphase).Name '/Lattice Constant b']);
    lattice(3) = h5read(fname,[group.Groups(iphase).Name '/Lattice Constant c']);

    lattice(4) = h5read(fname,[group.Groups(iphase).Name '/Lattice Constant alpha']);
    lattice(5) = h5read(fname,[group.Groups(iphase).Name '/Lattice Constant beta']);
    lattice(6) = h5read(fname,[group.Groups(iphase).Name '/Lattice Constant gamma']);

    pointGroup = h5read(fname,[group.Groups(iphase).Name '/Point Group']);
    pointGroup = regexp(char(pointGroup),'\[([1-6m/\-]*)\]','tokens');
    spaceGroup = pointGroup{1};

  catch
    lattice = h5read(fname,[group.Groups(iphase).Name '/LatticeConstants']);

    spaceGroup = h5read(fname,[group.Groups(iphase).Name '/SpaceGroup']);
    spaceGroup = strrep(spaceGroup,'#ovl','-');
    spaceGroup = strrep(spaceGroup,'#sub','');
  end

  try
    CS{iphase} = crystalSymmetry(spaceGroup,double(lattice(1:3)),double(lattice(4:6))*degree,'mineral',mineral);
  catch
    CS{iphase} = 'notIndexed';
  end
end

end

author: mtex-toolbox

repo: mtex

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


text:
function [Mout, RHSout] = combineBC2D(BC, Meq, RHSeq)
%COMBINEBC This function combines the boundary condition equations with the
%main physical model equations, and delivers the matrix of coefficient and
%RHS to be solved for the internal cells.
%
% SYNOPSIS:
%   [Mout, RHSout] = combineBC2D(BC, Meq, RHSeq)
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% extract data from the mesh structure
Nxy = BC.domain.dims;
Nx = Nxy(1); Ny = Nxy(2);
G=reshape(1:(Nx+2)*(Ny+2), Nx+2, Ny+2);
dx = BC.domain.cellsize.x;
dy = BC.domain.cellsize.y;

% define the RHS column vector
ms = size(Meq);
M = Meq;
RHS = RHSeq;

% Assign values to the boundary condition matrix and the RHS vector based
% on the BC structure
% top boundary
j=Ny+2;
i=2:Nx+1;
top = reshape(sub2ind(ms, G(i,j-1), G(i,j-1)), Nx,1); % top boundary cells
topN = reshape(sub2ind(ms, G(i,j-1), G(i,j)), Nx, 1); % north cells to top boundary cells
M(top) = M(top)-((BC.top.b/2 - BC.top.a/dy(end))./(BC.top.b/2 + BC.top.a/dy(end))).*M(topN);
RHS(G(i,j-1)) = RHS(G(i,j-1))-M(topN).*BC.top.c./(BC.top.b/2 + BC.top.a/dy(end));

% Bottom boundary
j=1;
i=2:Nx+1;
bottom = reshape(sub2ind(ms, G(i,j+1), G(i,j+1)), Nx,1); % bottom boundary cells
bottomS = reshape(sub2ind(ms, G(i,j+1), G(i,j)), Nx, 1); % south cells to bottom boundary cells
M(bottom) = M(bottom)-((BC.bottom.b/2 + BC.bottom.a/dy(1))./(BC.bottom.b/2 - BC.bottom.a/dy(1))).*M(bottomS);
RHS(G(i,j+1)) = RHS(G(i,j+1))-M(bottomS).*BC.bottom.c./(BC.bottom.b/2 - BC.bottom.a/dy(1));

% Right boundary
i=Nx+2;
j=2:Ny+1;
right = reshape(sub2ind(ms, G(i-1,j), G(i-1,j)), Ny,1); % right boundary cells
rightE = reshape(sub2ind(ms, G(i-1,j), G(i,j)), Ny, 1); % east cells to right boundary cells
M(right) = M(right)-((BC.right.b/2 - BC.right.a/dx(end))./(BC.right.b/2 + BC.right.a/dx(end)))'.*M(rightE);
RHS(G(i-1,j)) = RHS(G(i-1,j))-M(rightE).*(BC.right.c./(BC.right.b/2 + BC.right.a/dx(end)))';

% Left boundary
i = 1;
j=2:Ny+1;
left = reshape(sub2ind(ms, G(i+1,j), G(i+1,j)), Ny,1); % left boundary cells
leftW = reshape(sub2ind(ms, G(i+1,j), G(i,j)), Ny, 1); % west cells to left boundary cells
M(left) = M(left)-((BC.left.b/2 + BC.left.a/dx(1))./(BC.left.b/2 - BC.left.a/dx(1)))'.*M(leftW);
RHS(G(i+1,j)) = RHS(G(i+1,j))-M(leftW).*(BC.left.c./(BC.left.b/2 - BC.left.a/dx(1)))';

Mout = M(G(2:end-1,2:end-1), G(2:end-1,2:end-1));
RHSout = RHS(reshape(G(2:end-1,2:end-1),Nx*Ny,1));

author: simulkade

repo: FVTool

save_path: github-repos/MATLAB/simulkade-FVTool


text:
function value = p08_i4 ( action, name, value )

%*****************************************************************************80
%
%% P08_I4 sets or gets I4 parameters for problem 08.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION,
%    'D' to set a parameter to its default value.
%    'S' to set a parameter,
%    'G' to get a parameter,
%    'I' to increment a parameter.
%
%    Input, string NAME, the name of the variable.
%    '#' is the number of calls to the integrand routine.
%
%    Input/output, integer VALUE.
%    * If ACTION = 'I', then VALUE is an input quantity, and is the
%      new value to be added to NAME.
%    * If ACTION = 'S', then VALUE is an input quantity, and is the
%      new value to be assigned to NAME.
%    * If ACTION = 'G', then VALUE is an output quantity, and is the
%      current value of NAME.
%
  persistent calls;

  if ( action == 'D' | action == 'd' )

    if ( name == '#' | name == '*' )
      calls = 0;
    end

  elseif ( action == 'G' | action == 'g' )

    if ( name == '#' )
      value = calls;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P08_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P08_I4 - Fatal error!' );
    end

  elseif ( action == 'I' | action == 'i' )

    if ( name == '#' )
      calls = calls + value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P08_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P08_I4 - Fatal error!' );
    end

  elseif ( action == 'S' | action == 's' )

    if ( name == '#' )
      calls = value;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P08_I4 - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P08_I4 - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P08_I4 - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action = "%s".\n', action );
    error ( 'P08_I4 - Fatal error!' );

  end

  return
end


text:
function geometry_test170 ( )

%*****************************************************************************80
%
%% TEST170 tests PROVEC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2005
%
%  Author:
%
%    John Burkardt
%
  m = 4;
  n = 2;

  base = [ ...
    4.0, 3.0, 2.0, 1.0; ...
    1.0, 2.0, 3.0, 4.0 ]';
  vecm = [ 1.0, 1.0, 1.0, 2.0 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST170\n' );
  fprintf ( 1, '  PROVEC projects a vector onto a subspace.\n' );

  r8mat_transpose_print ( m, n, base, '  Base vectors' );

  r8vec_print ( m, vecm, '  Vector to be projected:' );

  [ vecn, vecnm ] = provec ( m, n, base, vecm );

  r8vec_print ( n, vecn, '  Projected vector in BASE coordinates:' );

  r8vec_print ( m, vecnm, '  Projected vector in original coordinates:' );

  return
end


text:
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni

%Fourier Transfrom properties

%	Time reversal

%x(t)=t*u(t)

%X(-w)
x=t*heaviside(t);
X=fourier(x,w) ;
Right=subs(X,w,-w)

%x(-t)
x_t=subs(x,t,-t);
Left=fourier(x_t,w)


text:
function [G] = gsp_hypergraph(N,E, w, coords, limits)
%GSP_HYPERGRAPH  Initialize a hypergraph from a set of edges and weights
%   Usage:  G = gsp_hypergraph(N,E);
%           G = gsp_hypergraph(N,E, w);
%           G = gsp_hypergraph(N,E, w, coords);
%           G = gsp_hypergraph(N, E, w, coords, limits);
%
%   Input parameters:
%         N     : Number of nodes
%         E     : Set of edges (cell array)
%         w     : weights of the edges (default all ones)
%         coords: Coordonates of the points (optional)
%         limits: limits for the coordonates (optional)
%   Output parameters:
%         G     : Graph structure.
%
%   Example:::
%
%         N = 100;
%         Nf = 2;
%         k = 4;
%         x = rand(N,Nf);
%         paramnn.k = k;
%         [indx, indy, d] = gsp_nn_distanz(x',x',paramnn);
%         sigma = mean(d)^2;
%         wt = exp(-d.^2/sigma);
%         E = cell(N,1);
%         w = zeros(N,1);
%         for ii = 1:N
%             edge = indx((1:k)+(ii-1)*k);
%             E{ii} = edge;
%             w(ii) = sum(wt(edge));
%         end
%
%         G = gsp_hypergraph(N,E,w)
%
%   See also: gsp_nn_hypergraph gsp_graph

% Author: Nathanael Perraudin
% Date: 21  October 2015

if nargin<3
    w = ones(numel(E));
end

if nargin > 3
    G.coords = coords;
end
if nargin > 4
    G.plotting.limits = limits;
end
G.N = N;
G.Ne = numel(E);
G.W = sparse(N,G.Ne);
G.E = E;
for ii = 1:G.Ne
    % Here we use W for HW...
    G.W(G.E{ii},ii) = sqrt(w(ii));
end

G.type = 'hypergraph from edges';
G.directed = 0;
G.hypergraph = 1;

G = gsp_graph_default_parameters(G);

end

repo: gspbox


text:
% DEMOIL100FGPLVM2 Oil100 data with FGPLVM.

% FGPLVM

% Fix seeds
randn('seed', 1e5);
rand('seed', 1e5);

dataSetName = 'oil100';
experimentNo = 2;

% load data
[Y, lbls] = lvmLoadData(dataSetName);

% Set up model
options = fgplvmOptions('ftc');
options.optimiser = 'graddesc';
latentDim = 2;
d = size(Y, 2);
options.initX = randn(size(Y, 1), latentDim)*1e-3;
model = fgplvmCreate(latentDim, d, Y, options);

% Optimise the model.
iters = 1000;
display = 1;

model = fgplvmOptimise(model, display, iters);

% Save the results.
modelWriteResult(model, dataSetName, experimentNo);

if exist('printDiagram') & printDiagram
  lvmPrintPlot(model, lbls, dataSetName, experimentNo);
end

% Load the results and display dynamically.
lvmResultsDynamic(model.type, dataSetName, experimentNo, 'vector')

% compute the nearest neighbours errors in latent space.
errors = lvmNearestNeighbour(model, lbls);


text:
% Following code bakes a birthday cake for someone special to whom you
% wanna surprise on his/her birthday with a cake in MATLAB ;)
%
% This is a chocolate flavored cake decorated with cheries on top ......
% yyuummmyy :) :)
%
% Lighted birthday candle has been put up on cake; Think of a wish and blow
% off candle by clicking on flame (yellowish in colour)... and here comes
% the celebration with birthday song.. :) :) .. Wish you a very very happy
% birthday..
%
% While running code, make sure that PC speakers are ON
%
% Cake prepared by Amol G. Mahurkar
%
% Birthday_gift.m Revisions
%
% Version 1.2   04/25/2013  A/V sync
%
% Version 1.1	12/19/2011
%
% Version 1.0	10/28/2011
%
% Please suggest some extra features you think should be in this birthday gift
%

%%
function Birthday_gift()

clc; clear; close all;

instruc = ['Happy Birthday !!!!',char(10),char(10),...
    'Here is a birthday cake for someone special,',char(10),char(10),...
    'Make sure that PC speakers are ON',char(10),char(10),...
    'This cake has following features:',char(10),...
    '1. Chocolate flavored... and yummy :) :) ',char(10),...
    '2. Decorated with cheries :) :)',char(10),...
    '3. Lighted birthday candle on top of it',char(10),char(10),...
    'Think of a wish, and',char(10),...
    'Blow off candle by clicking on flame (yellowish in colour, obviously)',char(10),...
    'Enjoy your birthday cake!!!',char(10),char(10),...
    'And ya, wish you a very happy birthday'];

if(~strcmp('Ok',questdlg(instruc,'Surprise !!!!!','Ok','Cancel','Ok')))
    quit;
end

global bday_name;
global your_name;
temp = inputdlg({'Birthday boy/girl name:','Best Wishes from:'});
bday_name = temp{1};
your_name = temp{2};
clear temp;
%% Base

n = 20;
theta = (0:n)/n*2*pi;
sintheta = sin(theta); sintheta(n+1) = 0;
m = 11;
r = ones(1,m)';
x1 = r * cos(theta);
y1 = r * sintheta;
z1 = (0:m-1)'/(m-1) * ones(1,n+1);

r = [1 1 linspace(0.8,0,9)]';
x2 = r * cos(theta);
y2 = r * sintheta;
z2 = ones(11,21);

%% Cherry

theta = (-n:2:n)/n*pi;
phi = (-n:2:n)'/n*pi/2;
cosphi = cos(phi); cosphi(1) = 0; cosphi(n+1) = 0;
sintheta = sin(theta); sintheta(1) = 0; sintheta(n+1) = 0;
x3 = 0.1.*cosphi*cos(theta);
y3 = 0.1.*cosphi*sintheta;
z3 = 0.1.*sin(phi)*ones(1,n+1);

%% Candle

x4=0.05.*ones(m,1)*cos(theta) + 0.5;
y4=0.05.*ones(m,1)*sintheta + 0.5;
z4 = (0:m-1)'/(m-1) * ones(1,n+1) + 0.5;

r11=linspace(0.05,0,10);
r11=[0.05 r11];
r11=r11';
x5=r11*cos(theta) + 0.5;
y5=r11*sintheta + 0.5;
z5 = linspace(1.5,1.8,11)' * ones(1,n+1);

%% Flame

theta = (-n:2:n)/n*pi;
phi = (-n:2:n)'/n*pi/2;
cosphi = cos(phi); cosphi(1) = 0; cosphi(n+1) = 0;
sintheta = sin(theta); sintheta(1) = 0; sintheta(n+1) = 0;
x6 = 0.04.*cosphi*cos(theta) + 0.5;
y6 = 0.04.*cosphi*sintheta + 0.5;
z6 = (linspace(1.7,2,21)')*ones(1,n+1);

%% Cake

[figure1, axes1] = figureset();
cake_w_flame(x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6,z1,z2,z3,z4,z5,z6,figure1,axes1,1);

again = 1;
while(again)
[xin yin] = ginput(1);
if(xin < 0.5 && xin > -1 && yin < 0.6 && yin > -1)
    again = 0;
    load('bday_song_8bit_11025.mat');
%     sound(song,11025,8);
    obj = audioplayer(song, 11025, 8);
    play(obj);
    close(figure1)
    [figure1, axes1] = figureset();
    cake_w_flame(x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6,z1,z2,z3,z4,z5,z6,figure1,axes1,0);
    eatmore = 'Wanna eat more ??  Use rotate tool or/and zoom in/out tool for it';
    msgbox(eatmore);
else
    while(~strcmp(questdlg('Blow off candle','Click on candle to blow it off','Ok','No'),'Ok'))
    end
    again = 1;
end
end

function [figure1, axes1] = figureset()

figure1 = figure('NumberTitle','off','Name','Wish you a very very happy birthday');

axes1 = axes('Visible','off','Parent',figure1,'PlotBoxAspectRatio',[1 1 1],...
    'DataAspectRatio',[1 1 1],'CameraViewAngle',10);
% 10.7508094342063
view(axes1,[-72.5 30]);
hold(axes1,'all');

oldRootUnits=get(0,'Units');
set(0,'Units','Pixels');
pos=get(0,'ScreenSize');
set(0,'Units',oldRootUnits);
maxPos=[-3 27 pos(3)+8 pos(4)-22];
oldUnits=get(figure1,'Units');
oldActivePositionProperty=get(figure1,'ActivePositionProperty');
set(figure1,'Units','Pixels','ActivePositionProperty','outerposition');
set(figure1,'Position',maxPos,'OuterPosition',maxPos);
set(figure1,'Units',oldUnits,'ActivePositionProperty',oldActivePositionProperty);

%% Cake w/wo flame
function cake_w_flame(x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6,z1,z2,z3,z4,z5,z6,~,axes1,flame)

global bday_name;
global your_name;

surf(x1,y1,z1,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[0.200000002980232 0 0]);
surf(x2,y2,z2,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[0.600000023841858 0.200000002980232 0]);

text('Parent',axes1,'String','Happy Birthday','Position',[-0.57 0.18 1.5],...
    'FontSize',28,...
    'FontName','Monotype Corsiva','Color',[1 0 0]);
text('Parent',axes1,'String',bday_name,'Position',[-0.3 -0.1 1.2],...
    'FontSize',28,...
    'FontName','Monotype Corsiva','Color',[1 0 0]);
text('Parent',axes1,'String',['Best Wishes from ',your_name],'Position',[-1.5 -1.5 1.5],...
    'FontSize',28,...
    'FontName','Monotype Corsiva','Color',[1 0 0]);
surf(x3+0,y3+0.8,z3+1.1,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[1 0 0]);
surf(x3+0,y3-0.8,z3+1.1,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[1 0 0]);
surf(x3+0.8,y3+0,z3+1.1,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[1 0 0]);

surf(x3-0.8,y3+0,z3+1.1,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[1 0 0]);
surf(x4,y4,z4,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[0.925490200519562 0.839215695858002 0.839215695858002]);
surf(x5,y5,z5,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[0.925490200519562 0.839215695858002 0.839215695858002]);
if(flame==1)
surf(x6,y6,z6,'Parent',axes1,'FaceLighting','phong',...
    'LineStyle','none',...
    'FaceColor',[1 1 0]);
end
light('Parent',axes1,'Style','local',...
    'Position',[-10.162701816704 -0.924193626363743 14.9951905283833]);

if(flame==0)
for i=1:110
view(axes1,[-10*i 20+0.2727*i])
pause(0.205)     %0.15
end
end
% EOF

author: TianfaYao

repo: ADRC

save_path: github-repos/MATLAB/TianfaYao-ADRC


text: %EQ Dataset overload

author: marianux

repo: ecg-kit

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


text:
function [ic,ik] = bspdegelev(d,c,k,t)
%
% Function Name:
%
%   bspdegevel - Degree elevate a univariate B-Spline.
%
% Calling Sequence:
%
%   [ic,ik] = bspdegelev(d,c,k,t)
%
% Parameters:
%
%   d	: Degree of the B-Spline.
%
%   c	: Control points, matrix of size (dim,nc).
%
%   k	: Knot sequence, row vector of size nk.
%
%   t	: Raise the B-Spline degree t times.
%
%   ic	: Control points of the new B-Spline.
%
%   ik	: Knot vector of the new B-Spline.
%
% Description:
%
%   Degree elevate a univariate B-Spline. This function provides an
%   interface to a toolbox 'C' routine.

[mc,nc] = size(c);
                                                          %
                                                          % int bspdegelev(int d, double *c, int mc, int nc, double *k, int nk,
                                                          %                int t, int *nh, double *ic, double *ik)
                                                          % {
                                                          %   int row,col;
                                                          %
                                                          %   int ierr = 0;
                                                          %   int i, j, q, s, m, ph, ph2, mpi, mh, r, a, b, cind, oldr, mul;
                                                          %   int n, lbz, rbz, save, tr, kj, first, kind, last, bet, ii;
                                                          %   double inv, ua, ub, numer, den, alf, gam;
                                                          %   double **bezalfs, **bpts, **ebpts, **Nextbpts, *alfs;
                                                          %
                                                          %   double **ctrl  = vec2mat(c, mc, nc);
% ic = zeros(mc,nc*(t));                                  %   double **ictrl = vec2mat(ic, mc, nc*(t+1));
                                                          %
n = nc - 1;                                               %   n = nc - 1;
                                                          %
bezalfs =  zeros(d+1,d+t+1);                              %   bezalfs = matrix(d+1,d+t+1);
bpts = zeros(mc,d+1);                                     %   bpts = matrix(mc,d+1);
ebpts = zeros(mc,d+t+1);                                  %   ebpts = matrix(mc,d+t+1);
Nextbpts = zeros(mc,d+1);                                 %   Nextbpts = matrix(mc,d+1);
alfs = zeros(d,1);                                        %   alfs = (double *) mxMalloc(d*sizeof(double));
                                                          %
m = n + d + 1;                                            %   m = n + d + 1;
ph = d + t;                                               %   ph = d + t;
ph2 = floor(ph / 2);                                      %   ph2 = ph / 2;
                                                          %
                                                          %   // compute bezier degree elevation coefficeients
bezalfs(1,1) = 1;                                         %   bezalfs[0][0] = bezalfs[ph][d] = 1.0;
bezalfs(d+1,ph+1) = 1;                                    %

for i=1:ph2                                               %   for (i = 1; i <= ph2; i++) {
   inv = 1/bincoeff(ph,i);                                %     inv = 1.0 / bincoeff(ph,i);
   mpi = min(d,i);                                        %     mpi = min(d,i);
                                                          %
   for j=max(0,i-t):mpi                                   %     for (j = max(0,i-t); j <= mpi; j++)
       bezalfs(j+1,i+1) = inv*bincoeff(d,j)*bincoeff(t,i-j);  %       bezalfs[i][j] = inv * bincoeff(d,j) * bincoeff(t,i-j);
   end
end                                                       %   }
                                                          %
for i=ph2+1:ph-1                                          %   for (i = ph2+1; i <= ph-1; i++) {
   mpi = min(d,i);                                        %     mpi = min(d, i);
   for j=max(0,i-t):mpi                                   %     for (j = max(0,i-t); j <= mpi; j++)
       bezalfs(j+1,i+1) = bezalfs(d-j+1,ph-i+1);          %       bezalfs[i][j] = bezalfs[ph-i][d-j];
   end
end                                                       %   }
                                                          %
mh = ph;                                                  %   mh = ph;
kind = ph+1;                                              %   kind = ph+1;
r = -1;                                                   %   r = -1;
a = d;                                                    %   a = d;
b = d+1;                                                  %   b = d+1;
cind = 1;                                                 %   cind = 1;
ua = k(1);                                                %   ua = k[0];
                                                          %
for ii=0:mc-1                                             %   for (ii = 0; ii < mc; ii++)
   ic(ii+1,1) = c(ii+1,1);                                %     ictrl[0][ii] = ctrl[0][ii];
end                                                       %
for i=0:ph                                                %   for (i = 0; i <= ph; i++)
   ik(i+1) = ua;                                          %     ik[i] = ua;
end                                                       %
                                                          %   // initialise first bezier seg
for i=0:d                                                 %   for (i = 0; i <= d; i++)
   for ii=0:mc-1                                          %     for (ii = 0; ii < mc; ii++)
      bpts(ii+1,i+1) = c(ii+1,i+1);                       %       bpts[i][ii] = ctrl[i][ii];
   end
end                                                       %
                                                          %   // big loop thru knot vector
while b < m                                               %   while (b < m)  {
   i = b;                                                 %     i = b;
   while b < m && k(b+1) == k(b+2)                        %     while (b < m && k[b] == k[b+1])
      b = b + 1;                                          %       b++;
   end                                                    %
   mul = b - i + 1;                                       %     mul = b - i + 1;
   mh = mh + mul + t;                                     %     mh += mul + t;
   ub = k(b+1);                                           %     ub = k[b];
   oldr = r;                                              %     oldr = r;
   r = d - mul;                                           %     r = d - mul;
                                                          %
                                                          %     // insert knot u(b) r times
   if oldr > 0                                            %     if (oldr > 0)
      lbz = floor((oldr+2)/2);                            %       lbz = (oldr+2) / 2;
   else                                                   %     else
      lbz = 1;                                            %       lbz = 1;
   end                                                    %

   if r > 0                                               %     if (r > 0)
      rbz = ph - floor((r+1)/2);                          %       rbz = ph - (r+1)/2;
   else                                                   %     else
      rbz = ph;                                           %       rbz = ph;
   end                                                    %

   if r > 0                                               %     if (r > 0) {
                                                          %       // insert knot to get bezier segment
      numer = ub - ua;                                    %       numer = ub - ua;
      for q=d:-1:mul+1                                    %       for (q = d; q > mul; q--)
         alfs(q-mul) = numer / (k(a+q+1)-ua);             %         alfs[q-mul-1] = numer / (k[a+q]-ua);
      end

      for j=1:r                                           %       for (j = 1; j <= r; j++)  {
         save = r - j;                                    %         save = r - j;
         s = mul + j;                                     %         s = mul + j;
                                                          %
         for q=d:-1:s                                     %         for (q = d; q >= s; q--)
            for ii=0:mc-1                                 %           for (ii = 0; ii < mc; ii++)
               tmp1 = alfs(q-s+1)*bpts(ii+1,q+1);
               tmp2 = (1-alfs(q-s+1))*bpts(ii+1,q);
               bpts(ii+1,q+1) = tmp1 + tmp2;              %             bpts[q][ii] = alfs[q-s]*bpts[q][ii]+(1.0-alfs[q-s])*bpts[q-1][ii];
            end
         end                                              %

         for ii=0:mc-1                                    %         for (ii = 0; ii < mc; ii++)
            Nextbpts(ii+1,save+1) = bpts(ii+1,d+1);       %           Nextbpts[save][ii] = bpts[d][ii];
         end
      end                                                 %       }
   end                                                    %     }
                                                          %     // end of insert knot
                                                          %
                                                          %     // degree elevate bezier
   for i=lbz:ph                                           %     for (i = lbz; i <= ph; i++)  {
      for ii=0:mc-1                                       %       for (ii = 0; ii < mc; ii++)
         ebpts(ii+1,i+1) = 0;                             %         ebpts[i][ii] = 0.0;
      end
      mpi = min(d, i);                                    %       mpi = min(d, i);
      for j=max(0,i-t):mpi                                %       for (j = max(0,i-t); j <= mpi; j++)
         for ii=0:mc-1                                    %         for (ii = 0; ii < mc; ii++)
            tmp1 = ebpts(ii+1,i+1);
            tmp2 = bezalfs(j+1,i+1)*bpts(ii+1,j+1);
            ebpts(ii+1,i+1) = tmp1 + tmp2;                %           ebpts[i][ii] = ebpts[i][ii] + bezalfs[i][j]*bpts[j][ii];
         end
      end
   end                                                    %     }
                                                          %     // end of degree elevating bezier
                                                          %
   if oldr > 1                                            %     if (oldr > 1)  {
                                                          %       // must remove knot u=k[a] oldr times
      first = kind - 2;                                                    %       first = kind - 2;
      last = kind;                                        %       last = kind;
      den = ub - ua;                                      %       den = ub - ua;
      bet = floor((ub-ik(kind)) / den);                   %       bet = (ub-ik[kind-1]) / den;
                                                          %
                                                          %       // knot removal loop
      for tr=1:oldr-1                                     %       for (tr = 1; tr < oldr; tr++)  {
         i = first;                                       %         i = first;
         j = last;                                        %         j = last;
         kj = j - kind + 1;                               %         kj = j - kind + 1;
         while j-i > tr                                   %         while (j - i > tr)  {
                                                          %           // loop and compute the new control points
                                                          %           // for one removal step
            if i < cind                                   %           if (i < cind)  {
               alf = (ub-ik(i+1))/(ua-ik(i+1));           %             alf = (ub-ik[i])/(ua-ik[i]);
               for ii=0:mc-1                              %             for (ii = 0; ii < mc; ii++)
                  tmp1 = alf*ic(ii+1,i+1);
                  tmp2 = (1-alf)*ic(ii+1,i);
                  ic(ii+1,i+1) = tmp1 + tmp2;             %               ictrl[i][ii] = alf * ictrl[i][ii] + (1.0-alf) * ictrl[i-1][ii];
               end
            end                                           %           }
            if j >= lbz                                   %           if (j >= lbz)  {
               if j-tr <= kind-ph+oldr                    %             if (j-tr <= kind-ph+oldr) {
                  gam = (ub-ik(j-tr+1)) / den;            %               gam = (ub-ik[j-tr]) / den;
                  for ii=0:mc-1                           %               for (ii = 0; ii < mc; ii++)
                     tmp1 = gam*ebpts(ii+1,kj+1);
                     tmp2 = (1-gam)*ebpts(ii+1,kj+2);
                     ebpts(ii+1,kj+1) = tmp1 + tmp2;      %                 ebpts[kj][ii] = gam*ebpts[kj][ii] + (1.0-gam)*ebpts[kj+1][ii];
                  end                                     %             }
               else                                       %             else  {
                  for ii=0:mc-1                           %               for (ii = 0; ii < mc; ii++)
                     tmp1 = bet*ebpts(ii+1,kj+1);
                     tmp2 = (1-bet)*ebpts(ii+1,kj+2);
                     ebpts(ii+1,kj+1) = tmp1 + tmp2;      %                 ebpts[kj][ii] = bet*ebpts[kj][ii] + (1.0-bet)*ebpts[kj+1][ii];
                  end
               end                                        %             }
            end                                           %           }
            i = i + 1;                                    %           i++;
            j = j - 1;                                    %           j--;
            kj = kj - 1;                                  %           kj--;
         end                                              %         }
                                                          %
         first = first - 1;                               %         first--;
         last = last + 1;                                 %         last++;
      end                                                 %       }
   end                                                    %     }
                                                          %     // end of removing knot n=k[a]
                                                          %
                                                          %     // load the knot ua
   if a ~= d                                              %     if (a != d)
      for i=0:ph-oldr-1                                   %       for (i = 0; i < ph-oldr; i++)  {
         ik(kind+1) = ua;                                 %         ik[kind] = ua;
         kind = kind + 1;                                 %         kind++;
      end
   end                                                    %       }
                                                          %
                                                          %     // load ctrl pts into ic
      for j=lbz:rbz                                       %     for (j = lbz; j <= rbz; j++)  {
         for ii=0:mc-1                                    %       for (ii = 0; ii < mc; ii++)
            ic(ii+1,cind+1) = ebpts(ii+1,j+1);            %         ictrl[cind][ii] = ebpts[j][ii];
         end
         cind = cind + 1;                                 %       cind++;
      end                                                 %     }
                                                          %
      if b < m                                            %     if (b < m)  {
                                                          %       // setup for next pass thru loop
         for j=0:r-1                                      %       for (j = 0; j < r; j++)
            for ii=0:mc-1                                 %         for (ii = 0; ii < mc; ii++)
               bpts(ii+1,j+1) = Nextbpts(ii+1,j+1);       %           bpts[j][ii] = Nextbpts[j][ii];
            end
         end
         for j=r:d                                        %       for (j = r; j <= d; j++)
            for ii=0:mc-1                                 %         for (ii = 0; ii < mc; ii++)
               bpts(ii+1,j+1) = c(ii+1,b-d+j+1);          %           bpts[j][ii] = ctrl[b-d+j][ii];
            end
         end
         a = b;                                           %       a = b;
         b = b+1;                                         %       b++;
         ua = ub;                                         %       ua = ub;
                                                          %     }
      else                                                %     else
                                                          %       // end knot
         for i=0:ph                                       %       for (i = 0; i <= ph; i++)
            ik(kind+i+1) = ub;                            %         ik[kind+i] = ub;
         end
      end
end                                                       %   }
% End big while loop                                      %   // end while loop
                                                          %
                                                          %   *nh = mh - ph - 1;
                                                          %
                                                          %   freevec2mat(ctrl);
                                                          %   freevec2mat(ictrl);
                                                          %   freematrix(bezalfs);
                                                          %   freematrix(bpts);
                                                          %   freematrix(ebpts);
                                                          %   freematrix(Nextbpts);
                                                          %   mxFree(alfs);
                                                          %
                                                          %   return(ierr);
                                                          % }

function b = bincoeff(n,k)
%  Computes the binomial coefficient.
%
%      ( n )      n!
%      (   ) = --------
%      ( k )   k!(n-k)!
%
%  b = bincoeff(n,k)
%
%  Algorithm from 'Numerical Recipes in C, 2nd Edition' pg215.

                                                          % double bincoeff(int n, int k)
                                                          % {
b = floor(0.5+exp(factln(n)-factln(k)-factln(n-k)));      %   return floor(0.5+exp(factln(n)-factln(k)-factln(n-k)));
                                                          % }

function f = factln(n)
% computes ln(n!)
if n <= 1, f = 0; return, end
f = gammaln(n+1); %log(factorial(n));</pre>


text:
function I = cellfind(C,pattern)
% I = cellfind(cellArray,[pattern])
%
% Returns index vector I of cells containing a
% desired pattern. Pattern can be anything that
% would be in a cell: a num, string, struct, another
% cell, etc. If pattern is omitted, I returns the
% indices of non-empty cells.
%
% Note the algorithm for finding a pattern isn't
% optimized to be fast, just convenient.
%
% ras 11/04: updated to include pattern finding
% bw/ab    : caught empty Cell condition

if isempty(C), I = []; return; end
if ndims(C) > 2, error('Cellfind doesn''t work on arrays > 2 dimensions.'); end

if ~iscell(C)
    help cellfind
    error('First argument must be a cell.')
end

if nargin < 2
    % no pattern, just find non-empty cells
	I=zeros(size(C));

	for t = 1:size(C,1)
        for u = 1:size(C,2)
            a = C{t,u};
            I(t,u)=~isempty(a);
        end
	end
else
    % find pattern
    for j = 1:size(C,1)
        for k = 1:size(C,2)
            I(j,k) = isequal(C{j,k},pattern);
        end
    end
end

I = find(I);

return


text:
function [idname,nodes,id]=eval(Tree,X,subtrees)
%EVAL Compute fitted value for decision tree applied to data.
%   YFIT = EVAL(T,X) takes a classification or regression tree T and a
%   matrix X of predictor values, and produces a vector YFIT of predicted
%   response values. For a regression tree, YFIT(J) is the fitted response
%   value for a point having the predictor values X(J,:).  For a
%   classification tree, YFIT(J) is the class into which the tree would
%   assign the point with data X(J,:).
%
%   YFIT = EVAL(T,X,SUBTREES) takes an additional vector SUBTREES of
%   pruning levels, with 0 representing the full, unpruned tree.  T must
%   include a pruning sequence as created by the CLASSREGTREE constructor or
%   the PRUNE method. If SUBTREES has K elements and X has N rows, then the
%   output YFIT is an N-by-K matrix, with the Ith column containing the
%   fitted values produced by the SUBTREES(I) subtree.  SUBTREES must be
%   sorted in ascending order. (To compute fitted values for a tree that is
%   not part of the optimal pruning sequence, first use PRUNE to prune the
%   tree.)
%
%   [YFIT,NODE] = EVAL(...) also returns an array NODE of the same size
%   as YFIT containing the node number assigned to each row of X.  The
%   VIEW method can display the node numbers for any node you select.
%
%   [YFIT,NODE,CNUM] = EVAL(...) is valid only for classification trees.
%   It returns a vector CNUM containing the predicted class numbers.
%
%   NaN values in the X matrix are treated as missing.  If the EVAL method
%   encounters a missing value when it attempts to evaluate the split rule
%   at a branch node, it cannot determine whether to proceed to the left or
%   right child node.  Instead, it sets the corresponding fitted value
%   equal to the fitted value assigned to the branch node.
%
%   For a tree T, the syntax [...]=T(X) or [...]=T(X,SUBTREES) also invokes
%   the EVAL method.
%
%   Example: Find predicted classifications for Fisher's iris data.
%      load fisheriris;
%      t = classregtree(meas, species);  % create decision tree
%      sfit = eval(t,meas);              % find assigned class names
%      mean(strcmp(sfit,species))        % proportion correctly classified
%
%   See also CLASSREGTREE, CLASSREGTREE/PRUNE, CLASSREGTREE/VIEW, CLASSREGTREE/TEST.

%   Copyright 2006-2007 The MathWorks, Inc.
%   $Revision: 1.1.6.5 $  $Date: 2009/11/05 17:04:07 $

if ~isfloat(X)
    error('stats:classregtree:eval:BadData',...
        'X must be a matrix of floating-point numbers.');
end

[nr,nc] = size(X);
if nc~=Tree.npred
   error('stats:treeval:BadInput',...
         'The X matrix must have %d columns.',Tree.npred);
end

if nargin<3
   subtrees = 0;
elseif numel(subtrees)>length(subtrees)
   error('stats:treeval:BadSubtrees','SUBTREES must be a vector.');
elseif any(diff(subtrees)<0)
   error('stats:treeval:BadSubtrees','SUBTREES must be sorted.');
end

if ~isempty(Tree.prunelist)
   prunelist = Tree.prunelist;
elseif ~isequal(subtrees,0)
   Tree = prune(Tree);
else
   prunelist = Inf(size(Tree.node));
end
if isequal(Tree.method,'classification') || ~isempty(Tree.catcols)
    nodes = classregtreeEval(X',Tree.node,Tree.var,Tree.cut,Tree.children,...
        prunelist,subtrees);
    nodes = nodes';
    id = Tree.class(nodes);
    if nr==1
        id = id(:)';
    end

    if isequal(Tree.method,'classification')
       idname = Tree.classname(id);
       if nr==1
           idname = idname(:)';
       end
    else
       idname = id;
    end
else
    [idname, nodes] = regtreeEval(X',Tree.node, Tree.var, Tree.cut, Tree.children,...
        Tree.reg_ws, Tree.reg_pvars);
end

author: Cloud-CV

repo: object-proposals


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

% This file is part of the Matlab Toolbox for Dimensionality Reduction v0.7.2b.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, 2010
% University California, San Diego / Delft University of Technology

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

% Last Modified by GUIDE v2.5 11-Sep-2008 10:53:04

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

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

nmc=varargin{1}; % number of columns

% Update handles structure
guidata(hObject, handles);

set(handles.noc,'string',num2str(nmc));
set(handles.col,'string',num2str(nmc));

cl=[0.4 0.4 0.4];
set(handles.coltxt,'ForegroundColor',cl);
set(handles.col,'Enable','off');

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

% --- Outputs from this function are returned to the command line.
function varargout = load_xls_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
varargout{1} = handles.output;

function col_Callback(hObject, eventdata, handles)
% hObject    handle to col (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of col as text
%        str2double(get(hObject,'String')) returns contents of col as a double

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

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

% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
uiresume(handles.figure1);

% --- Executes when selected object is changed in uipanel1.
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
if get(handles.uc,'value')
    cl=[0 0 0];
    set(handles.coltxt,'ForegroundColor',cl);
    set(handles.col,'Enable','on');
else
    cl=[0.4 0.4 0.4];
    set(handles.coltxt,'ForegroundColor',cl);
    set(handles.col,'Enable','off');
end

repo: cluster


text:
function script_extract_vgg16_conv_features(image_set, voc_year, varargin)
% image_set: string with the PASCAL VOC imaget set name, e.g. 'test','trainval',...
% voc_year: string with the PASCAL VOC challenge year of the imaget set, e.g. '2007','2012',...
%
% This file is part of the code that implements the following ICCV2015 accepted paper:
% title: "Object detection via a multi-region & semantic segmentation-aware CNN model"
% authors: Spyros Gidaris, Nikos Komodakis
% institutation: Universite Paris Est, Ecole des Ponts ParisTech
% Technical report: http://arxiv.org/abs/1505.01749
% code: https://github.com/gidariss/mrcnn-object-detection
%
% AUTORIGHTS
% --------------------------------------------------------
% Copyright (c) 2015 Spyros Gidaris
%
% "Object detection via a multi-region & semantic segmentation-aware CNN model"
% Technical report: http://arxiv.org/abs/1505.01749
% Licensed under The MIT License [see LICENSE for details]
% ---------------------------------------------------------

ip = inputParser;
ip.addOptional('start',      1,   @isscalar); % index of the first image in the set from which it will start extracting the feature maps.
ip.addOptional('end',        0,   @isscalar); % index of the last image in the set till which it will extract the feature maps.
ip.addOptional('scales',   [480 576 688 874 1200], @ismatrix);
ip.addOptional('gpu_id',     0,  @isnumeric);
ip.addOptional('use_flips', false, @islogical);

ip.parse(varargin{:});
opts = ip.Results;

mean_pix         = [103.939, 116.779, 123.68];
net_files_dir    = fullfile(pwd,'data','vgg_pretrained_models');
net_def_file     = fullfile(net_files_dir,'vgg16_conv5_deploy.prototxt');
net_weights_file = fullfile(net_files_dir,'VGG_ILSVRC_16_Convolutional_Layers.caffemodel');
assert(exist(net_files_dir,'dir')>0);
assert(exist(net_def_file,'file')>0);
assert(exist(net_weights_file,'file')>0);

image_db  = load_image_dataset('image_set',image_set,...
    'voc_year',voc_year,'use_flips',opts.use_flips);

feat_cache_name          = 'VGG_ILSVRC_16_layers';
feat_cache_dir_parent    = fullfile(pwd, 'feat_cache');
feat_cache_dir_child     = fullfile(feat_cache_dir_parent, feat_cache_name);
feat_cache_dir_image_set = fullfile(feat_cache_dir_child, image_db.image_set_name);

mkdir_if_missing(feat_cache_dir_parent);
mkdir_if_missing(feat_cache_dir_child);
mkdir_if_missing(feat_cache_dir_image_set);

caffe_set_device( opts.gpu_id );
caffe.reset_all();
net = caffe_load_model( net_def_file, {net_weights_file});

extract_conv_features_all_images(net, image_db.image_paths, feat_cache_dir_image_set, ...
    'start',opts.start,'end',opts.end,'scales',opts.scales,'mean_pix',mean_pix);

caffe.reset_all();

end

author: gidariss

repo: mrcnn-object-detection


text:
function solve(acados_ocp)

% solve
acados_ocp.solve();

author: OpenOCL

repo: OpenOCL

save_path: github-repos/MATLAB/OpenOCL-OpenOCL


text:
function output = runrmssd(rr)
% output = runrmssd(times, rr);
%   OVERVIEW:   calculates the rmssd: the square root of the mean
%               of the sum of the squares of the differences.
%   INPUT:      rr = a single row of rr interval data in seconds
%               times =  the time indices of the rr interval data (seconds)
%   OUTPUT:     output = rmssd
%   DEPENDENCIES
%   & LIBRARIES:    replaceOutliers.m
%                   AnnotationConversion.m
%   REFERENCE:
%	REPO:
%       https://github.com/cliffordlab/PhysioNet-Cardiovascular-Signal-Toolbox
%   SOURCE:     Adapted from Kaplan Tools
%               See: http://www.robots.ox.ac.uk/~gari/CODE/HRV/
%   AUTHORS:    Adriana Nicholson Vest, PhD
%   COPYRIGHT (C) 2016
%   LICENSE:
%%

leng = length(rr);

dif = diff(rr);

output = sqrt(mean(dif.*dif));

end

author: cliffordlab

repo: PhysioNet-Cardiovascular-Signal-Toolbox


text:
% Program_3c - The Mandelbrot Set in Color.
% Program supplied by Steve Lord from The MathWorks.
% Copyright Birkhauser 2013.

% Define parameters
Nmax = 50;   scale = 0.005;
xmin = -2.4; xmax  = 1.2;
ymin = -1.5;  ymax  = 1.5;

% Generate X and Y coordinates and Z complex values
[x,y]=meshgrid(xmin:scale:xmax, ymin:scale:ymax);
z = x+1i*y;

% Generate w accumulation matrix and k counting matrix
w = zeros(size(z));
k = zeros(size(z));

% Start off with the first step ...
N = 0;

% While N is less than Nmax and any k's are left as 0
while N<Nmax && ~all(k(:))
    % Square w, add z
    w = w.^2+z;
    % Increment iteration count
    N = N+1;
    % Any k locations for which abs(w)>4 at this iteration and no
    % previous iteration get assigned the value of N
    k(~k & abs(w)>4) = N;
end

% If any k's are equal to 0 (i.e. the corresponding w's never blew up) set
% them to the final iteration number
k(k==0) = Nmax;

% Open a new figure
figure

% Display the matrix as a surface
s=pcolor(x,y,k);

% If you truly want the Mandelbrot curve in B&W, comment the above line and
% uncomment these two
% s = pcolor(x, y, mod(k, 2));
% colormap([0 0 0;1 1 1])

% Turn off the edges of the surface (because the cells are so small, the
% edges would drown out any useful information if we left them black)
set(s,'edgecolor','none')

% Adjust axis limits, ticks, and tick labels
axis([xmin xmax -ymax ymax])
fontsize=15;
set(gca,'XTick',xmin:0.4:xmax,'FontSize',fontsize)
set(gca,'YTick',-ymax:0.5:ymax,'FontSize',fontsize)
xlabel('Re z','FontSize',fontsize)
ylabel('Im z','FontSize',fontsize)

keyboard
figure

% End of Probgram_3c.


text:
function bench_ssc_batch_omp(md)

num_samples_per_digit_arr = [50 80 100 150 200 300 400];

nns = numel(num_samples_per_digit_arr);
solver_name = 'ssc_batch_omp';
for ns=1:nns
    num_samples_per_digit = num_samples_per_digit_arr(ns);
    fprintf('Simulating: %s, for %d samples per digit\n', solver_name, num_samples_per_digit);
    result = check_digits(md, num_samples_per_digit, @ssc_batch_omp, solver_name);
    filepath = sprintf('bin/%s_digits=%d.mat', solver_name, num_samples_per_digit);
    save(filepath, 'result');
end

end

author: indigits

repo: sparse-plex


text:
function [w, g_sqr] = rmsprop(w, g_sqr, grad, opts, lr)
%RMSPROP
%   Example RMSProp solver, for use with CNN_TRAIN and CNN_TRAIN_DAG.
%
%   Set the initial learning rate for RMSProp in the options for
%   CNN_TRAIN and CNN_TRAIN_DAG. Note that a learning rate that works for
%   SGD may be inappropriate for RMSProp; the default is 0.001.
%
%   If called without any input argument, returns the default options
%   structure.
%
%   Solver options: (opts.train.solverOpts)
%
%   `epsilon`:: 1e-8
%      Small additive constant to regularize variance estimate.
%
%   `rho`:: 0.99
%      Moving average window for variance update, between 0 and 1 (larger
%      values result in slower/more stable updating).

% Copyright (C) 2016 Joao F. Henriques.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

if nargin == 0 % Return the default solver options
  w = struct('epsilon', 1e-8, 'rho', 0.99);
  return;
end

if isempty(g_sqr)
  g_sqr = 0 ;
end

g_sqr = g_sqr * opts.rho + grad.^2 * (1 - opts.rho) ;

w = w - lr * grad ./ (sqrt(g_sqr) + opts.epsilon) ;

repo: CREST-Release


text:
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni

% circular convolution

% mod(-m,N)
N=4;
for m=0:3
p(m+1)=mod(-m,N);
end
p

% circular time-reversed sequence
h=[1,1,0.5,2];
for m=0:3
hs(1+m)=h(1+p(m+1));
end
hs'
stem(0:N-1,hs);
axis([-.4 3.4 -.2 2.2])
legend('h_s(m)=h[((-m))_N]')

% circular convolution
clear y;
figure
N=4;
x=[1,0,2.5,1.5];
m=0:N-1;
stem(m,x);
axis([-.4 3.4 -.2 2.9])
legend('x[m]')
n=0;
hsn=circshift(hs',n);
stem(m,hsn);
axis([-.4 3.4 -.2 2.2]);
legend('h[((n-m))_N],n=0')
y(n+1)=sum( x.*hsn')
% or  alternatively
% y(n+1)=x*hsn;

figure
m=0:N-1;
stem(m,x);
axis([-.4 3.4 -.2 2.9])
legend('x[m]')

figure
n=1;
hsn=circshift(hs',n);
stem(m,hsn);
axis([-.4 3.4 -.2 2.2]);
legend(' h[((n-m))_N], n=1')
y(n+1)=sum(x.*hsn')

figure
n=2;
hsn=circshift(hs',n);
stem(m,hsn);
axis([-.4 3.4 -.2 2.2]);
legend(' h[((n-m))_N], n=2')
y(n+1)=sum(x.*hsn')

figure
n=3;
hsn=circshift(hs',n);
stem(m,hsn);
axis([-.4 3.4 -.2 2.2]);
legend('h[((n-m))_N], n=3')
y(n+1)=x*hsn

figure
stem(m,y)
axis([-.4 3.4 -.2 7.2]);
title('circular convolution')
legend(' y[n] ')

author: Sable

repo: mcbench-benchmarks


text:
function [] = test_one_dim_tv_denosing()

    clc;
    clear;
    close all;

    rng('default')

    max_epoch = 50;
    lambda_array = [0.1, 1, 10, 100];

    %% generate dataset
    noise_std = 0.1;

    if 0
        % Original signal
        n = 100;
        x = zeros(n,1);
        x(1:25) = 1;
        x(26:50) = 3;
        x(51:100) = 2;

    else
        % Original signal
        n = 1000;
        x = zeros(n,1);
        x(1:250) = 1;
        x(251:500) = 3;
        x(751:1000) = 2;

    end

    y = x + noise_std * randn(n, 1);

    algorithms = {'GD', 'AG', 'DPG', 'FDPG'};

    %% initialize
    w_list = cell(1);
    info_list = cell(1);

    total_idx = 0;

    for lamda_idx = 1 : numel(lambda_array)

        %% define l2-reg problem definitions
        problem_l2 = one_dim_tv_denoise_problem(y, lambda_array(lamda_idx), 'l2');
        w_init = randn(problem_l2.d, 1);

        %% perform algorithms
        clear options;
        options.w_init = w_init;
        options.tol_gnorm = 1e-10;
        options.max_epoch = max_epoch;
        options.verbose = true;

        % GD
        total_idx = total_idx + 1;
        options.step_alg = 'backtracking';
        [w_list{total_idx}, info_list{total_idx}] = sd(problem_l2, options);

        % AG
        total_idx = total_idx + 1;
        options.step_alg = 'backtracking';
        [w_list{total_idx}, info_list{total_idx}] = ag(problem_l2, options);

        %% define l1-reg problem definitions
        problem_l1 = one_dim_tv_denoise_problem(y, lambda_array(lamda_idx), 'l1');
        y_init = zeros(problem_l2.d-1, 1);

        clear options;
        options.w_init = y_init;
        options.tol_gnorm = 1e-10;
        options.max_epoch = max_epoch;
        options.verbose = true;
        options.step_init = 1/4; % L = 4;
        options.w_init = y_init;

        % dpg
        total_idx = total_idx + 1;
        options.sub_mode = 'std';
        [w_list{total_idx}, ~, info_list{total_idx}] = dpg(problem_l1, options);

        % fdpg
        total_idx = total_idx + 1;
        options.sub_mode = 'fast';
        [w_list{total_idx}, ~, info_list{total_idx}] = dpg(problem_l1, options);

        fprintf('\n\n');

    end

    %% plot all
    denoised_signal = cell(numel(total_idx), 1);
    total_idx = 0;
    for lambda_idx = 1 : numel(lambda_array)
        for alg_index = 1 : numel(algorithms)
            total_idx = total_idx + 1;
            denoised_signal{total_idx} = w_list{total_idx};
        end
    end

    figure;

    width = numel(algorithms);
    height = numel(lambda_array);

    fontsize = 12;
    total_idx = 0;
    for lambda_idx = 1 : numel(lambda_array)
        for alg_index = 1 : numel(algorithms)
            total_idx = total_idx + 1;
            subplot(height, width, total_idx);
            plot(1:n, x, ':k', 'LineWidth', 2); hold on
            plot(1:n, y, 'b', 'LineWidth', 2); hold on
            plot(1:n, denoised_signal{total_idx}, 'r', 'LineWidth', 2); hold off
            legend('Original signal', 'Noisy signal', 'Denoised signal');
            title_str = sprintf('%s (lambda=%5.1f)', algorithms{alg_index}, lambda_array(lambda_idx));
            title(title_str)
            set(gca, 'FontSize', fontsize);
        end
    end

end

author: hiroyuki-kasai

repo: SGDLibrary


text:
function sirfsdmap = doSIRFS_newIm(state,depthIm)
sigma = 3; % Controls the "bandwidth" of the input depth (the standard deviation of a Gaussian at which point the signal becomes reliable)
    mult = 5; % Controls the importance of the input depth (the multiplier on the loss)
    niters = 500;
    depthIm(isinf(depthIm)) = nan;
    depthIm = -depthIm;
    input_image = im2double(state.im);
    input_image(input_image<1/255) = 1/255;
    sirfsdmap = SIRFS(input_image, (state.mask), depthIm, ...
        ['params.DO_DISPLAY = 0; params.N_ITERS_OPTIMIZE = ' num2str(niters) ';params.USE_INIT_Z = true; params.INIT_Z_SIGMA = ',...
        num2str(sigma), ';params.multipliers.height.init = { ', num2str(mult), ' };']);
    sirfsdmap.mask = state.mask;
    sirfsdmap.im = input_image;
end

repo: CategoryShapes