text:
function [color,X]=som_fuzzycolor(sM,T,R,mode,initRGB,S)

% SOM_FUZZYCOLOR Heuristic contraction projection/soft cluster color coding for SOM
%
% function [color,X]=som_fuzzycolor(map,[T],[R],[mode],[initRGB],[S])
%
%  sM        (map struct)
%  [T]       (scalar) parameter that defines the speed of contraction
%              T<1: slow contraction, T>1: fast contraction. Default: 1
%  [R]       (scalar) number of rounds, default: 30
%  [mode]    (string) 'lin' or 'exp', default: 'lin'
%  [initRGB] (string) Strings accepted by SOM_COLORCODE,  default: 'rgb2'
%  [S]       (matrix) MxM matrix a precalculated similarity matrix
%  color     (matrix) of size MxRx3 resulting color codes at each step
%  X         (matrix) of size MxRx2 coordiantes for projected unit weight vectors
%             at each step of iteration. (Color code C is calculated using this
%             projection.)
%
% The idea of the projection is to use a naive contraction model which
% pulls the units together. Units that are close to each other in the
% output space (clusters) contract faster into the same point in the
% projection. The original position for each unit is its location in
% the topological grid.
%
% This is an explorative tool to color code the map units so that
% similar units (in the sense of euclidean norm) have similar coloring
% (See also SOM_KMEANSCOLOR) The tool gives a series of color codings
% which start from an initial color coding (see SOM_COLORCODE) and
% show the how the fuzzy clustering process evolves.
%
% The speed of contraction is controlled by the input parameter T. If
% it is high the projection contracts more slowly and reveals more
% intermediate stages (hierarchy).  A good value for T must be
% searched manually. It is probable that the default values do not
% yield good results.
%
% The conatrction process may be slow. In this case the mode can be
% set to 'exp' instead of 'lin', however, then the computing becomes
% heavier.
%
% EXAMPLE
%
%  load iris; % or any other map struct sM
%  [color]=som_fuzzycolor(sM,'lin',10);
%  som_show(sM,'color',color);
%
% See also SOM_KMEANSCOLOR, SOM_COLORCODE, SOM_CLUSTERCOLOR
%
% REFERENCES
%
% Johan Himberg, "A SOM Based Cluster Visualization and Its
% Application for False Coloring", in Proceedings of International
% Joint Conference on Neural Networks (IJCNN2000)},
% pp. 587--592,Vol. 3, 2000
%
% Esa Alhoniemi, Johan Himberg, and Juha Vesanto, Probabilistic
% Measures for Responses of Self-Organizing Map Units, pp. 286--290,
% in Proceedings of the International ICSC Congress on Computational
% Intelligence Methods and Applications (CIMA '99)}, ICSC Academic
% Press}, 1999
%
% Outline of the heuristic
%
% First a matrix D of squared pairwise euclidean distances
% D(i,j)=d(i,j)^2 between map weight vectors is calculated. This
% matrix is transformed into a similarity matrix S,
% s(i,j)=exp(-(D(i,j)/(T.^2*v)), where T is a free input parameter and
% v the variance of all elements of D v=var(D(:)). The matrix is
% further normalized so that all rows sum to one. The original
% topological coordinates X=som_unit_coords(sM) are successively
% averaged using this matrix. X(:,:,i)=S^i*X(:,:,1); As the process is
% actually a series of successive weighted averagings of the initial
% coordinates, all projected points eventually contract into one
% point.  T is a user defined parameter that defines how fast the
% projection contracts into this center point. If T is too small, the
% process will end into the center point at once.
%
% In practise, we don't calculate powers of S, but compute
%
%  X(:,:,i)=S.*X(:,:,i-1); % mode: 'lin'
%
% The contraction process may be slow if T is selected to be large,
% then for each step the similarity matrix is squared
%
%  X(:,:,i)=S*X(:,:,1); S=S*S % mode: 'exp'
%
% The coloring is done using the function SOM_COLORCODE according to
% the projections in X, The coordinates are rescaled in order to
% achieve maximum color resolution.

% Contributed to SOM Toolbox vs2, 2000 by Johan Himberg
% Copyright (c) by Johan Himberg
% http://www.cis.hut.fi/projects/somtoolbox/

% Previously rownorm function normalized the rows of S erroneously
% into unit length, this major bug was corrected 14042003. Now the
% rownorm normalizes the rows to have unit sum as it should johan 14042003

%% Check input arguments

if isstruct(sM),
   if ~isfield(sM,'topol')
      error('Topology field missing.');
   end
   M=size(sM.codebook,1);
else
   error('Requires a map struct.');
end

if nargin<2 || isempty(T),
   T=1;
end
if ~vis_valuetype(T,{'1x1'})
   error('Input for T must be a scalar.');
end

if nargin<3 || isempty(R),
   R=30;
end
if ~vis_valuetype(R,{'1x1'})
   error('Input for R must be a scalar.');
end

if nargin < 4 || isempty(mode),
   mode='lin';
end
if ~ischar(mode),
   error('String input expected for mode.');
else
   mode=lower(mode);
   switch mode
   case {'lin','exp'}
   otherwise
      error('Input for mode must be ''lin'' or ''exp''.');
   end
end

if nargin < 5 || isempty(initRGB)
   initRGB='rgb2';
end

if ischar(initRGB),
   try
      dummy=som_colorcode(sM,initRGB);
   catch
      error(['Color code ''' initRGB ''' not known, see SOM_COLORCODE.']);
   end
else
   error('Invalid color code string');
end

if nargin<6 || isempty(S),
   S=fuzzysimilarity(sM,1./T);
end

if ~vis_valuetype(S,{[M M]}),
   error('Similarity matrix must be a MunitsxMunits matrix.')
end

x = maxnorm(som_unit_coords(sM.topol.msize,sM.topol.lattice,'sheet'));

x = x-repmat(mean(x),size(x,1),1);

X(:,:,1)=x;
color(:,:,1)=som_colorcode(x,'rgb2',1);

%%% Actions

for i=1:R,
   switch mode
   case 'exp'
      S=rownorm(S*S);
      tmpX=S*X(:,:,1);
   case 'lin'
      tmpX=S*X(:,:,i);
   end
   X(:,:,i+1)=tmpX;
   color(:,:,i+1)=som_colorcode(X(:,:,i+1),initRGB);
end

color(isnan(color))=0;

function r=fuzzysimilarity(sM,p)
  % Calculate a "fuzzy response" similarity matrix
  % sM: map
  % p: sharpness factor
  d=som_eucdist2(sM,sM);
  v=std(sqrt(d(:))).^2;
  r=rownorm(exp(-p^2*(d./v)));
  r(~isfinite(r))=0;
  return;

function X = rownorm(X)

  r = sum(X,2);
  X = X ./ r(:,ones(size(X,2),1));
  return;

function X = maxnorm(X)

  for i=1:size(X,2), r = (max(X(:,i))-min(X(:,i))); if r, X(:,i) = X(:,i) / r; end, end
  return;

author: ilarinieminen

repo: SOM-Toolbox


text:
%% edgeListToCurve
% Below is a demonstration of the features of the |edgeListToCurve| function

%%
clear; close all; clc;

%% Syntax
% |[indList]=edgeListToCurve(E);|

%% Description
% This function converts the nx2 edges array |E|, which should define a
% single curve, to an ordered list of mx1 indices |indList| for that curve.
% Note that iff the edges define a closed curve the first and last indices
% in the ordered list are the same and therefore repeated.

%% Examples
%

%%
% Plot settings
markerSize=40;
lineWidth=4;
fontSize=25;

%% Getting indices for a single boundary curve

%%
% Creating example geometry
t=linspace(0,2*pi,50); t=t(1:end-1); %Angles
V1=[cos(t(:)) sin(t(:))];

%Desired point spacing
pointSpacing=0.5;

[F,V]=regionTriMesh2D({V1},pointSpacing,1,0);

%%
% Get boundary edges
Eb=patchBoundary(F);

%%
% Use |edgeListToCurve| to get curve indices
indList=edgeListToCurve(Eb);

%%
% Visualize example mesh and boundary edges/curves

cFigure;
subplot(1,2,1); hold on;
title('Boundary edges','FontSize',fontSize)
hp1=gpatch(F,V,'kw','k',1,1);
hp2=gpatch(Eb,V,'none',(1:1:size(Eb,1))',1,lineWidth);
legend([hp1 hp2],{'Mesh','Boundary edges'});
axisGeom(gca,fontSize); view(2);

subplot(1,2,2); hold on;
title('Boundary curve','FontSize',fontSize)
hp1=gpatch(F,V,'kw','k',1,1);
hp2=plotV(V(indList,:),'r.-','MarkerSize',markerSize,'LineWidth',lineWidth);
legend([hp1 hp2],{'Mesh','Ordered boundary curve'});
axisGeom(gca,fontSize); view(2);

drawnow;

%% Getting indices for a multiple boundary curves

%%
% Creating example geometry with multiple boundary sets

%Boundary 1
ns=150;
t=linspace(0,2*pi,ns);
t=t(1:end-1);
r=6+2.*sin(5*t);
[x,y] = pol2cart(t,r);
V1=[x(:) y(:)];

%Boundary 2
[x,y] = pol2cart(t,ones(size(t)));
V2=[x(:) y(:)+4];

%Boundary 3
[x,y] = pol2cart(t,2*ones(size(t)));
V3=[x(:) y(:)-0.5];

%Defining a region
regionCell={V1,V2,V3}; %A region between V1 and V2 (V2 forms a hole inside V1)

plotOn=1; %This turns on/off plotting

%Desired point spacing
pointSpacing=0.5;

[F,V]=regionTriMesh2D(regionCell,pointSpacing,1,0);

%%
% Get boundary edges
Eb=patchBoundary(F);

%%
% Use grouping to "seperate" boundary sets
optionStruct.outputType='label';
G=tesgroup(Eb,optionStruct);

%%

cFigure; hold on;
gpatch(F,V,'kw','k',1,1);
axisGeom(gca,fontSize); view(2);

plotColors=gjet(max(G(:)));
for q=1:1:max(G(:))

    E_now=Eb(G==q,:);

    plotV(V(E_now,:),'b.','markersize',25);

    [indListNow]=edgeListToCurve(E_now);

    hp=plotV(V(indListNow,:),'b.-','MarkerSize',markerSize,'LineWidth',lineWidth);
    hp.Color=plotColors(q,:);

end

drawnow;

%%
%
% <<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:
classdef SetRectangularlSensorAzAngleAction < AbstractEventAction
    %SetRectangularlSensorAzAngleAction Summary of this class goes here
    %   Detailed explanation goes here

    properties
        sensor RectangularSensor
        sensorAzAngle(1,1) double {mustBeGreaterThan(sensorAzAngle, 0)} = deg2rad(10);
    end

    properties(Constant)
        emptyVarArr = AbstractOptimizationVariable.empty(0,1);
    end

    methods
        function obj = SetRectangularlSensorAngleAction(sensor, sensorAzAngle)
            if(nargin > 0)
                obj.sensor = sensor;
                obj.sensorAzAngle = sensorAzAngle;
            end

            obj.id = rand();
        end

        function newStateLogEntry = executeAction(obj, stateLogEntry)
            newStateLogEntry = stateLogEntry;
            sensorState = newStateLogEntry.getSensorStateForSensor(obj.sensor);
            sensorState.setSensorAzAngle(obj.sensorAzAngle);
        end

        function initAction(obj, initialStateLogEntry)
            %nothing
        end

        function name = getName(obj)
            name = sprintf('Set Sensor Azimuth Half-Angle (%s => %0.3f deg)', obj.sensor.name, rad2deg(obj.sensorAzAngle));
        end

        function tf = usesStage(obj, stage)
            tf = false;
        end

        function tf = usesEngine(obj, engine)
            tf = false;
        end

        function tf = usesTank(obj, tank)
            tf = false;
        end

        function tf = usesEngineToTankConn(obj, engineToTank)
            tf = false;
        end

        function tf = usesStopwatch(obj, stopwatch)
            tf = false;
        end

        function tf = usesExtremum(obj, extremum)
            tf = false;
        end

        function tf = usesTankToTankConn(obj, tankToTank)
            tf = false;
        end

        function tf = usesSensor(obj, sensor)
            tf = obj.sensor == sensor;
        end

        function [tf, vars] = hasActiveOptimVar(obj)
            tf = false;
            vars = obj.emptyVarArr;
        end
    end

    methods(Static)
        function addActionTf = openEditActionUI(action, lv)
            lvdData = lv.lvdData;
            [~, sensors] = lvdData.sensors.getListboxStr();

            if(not(isempty(sensors)) && any([sensors.typeEnum] == SensorEnum.RectangularSensor))
                output = AppDesignerGUIOutput({false});
                lvd_EditActionSetRectangularSensorAzAngleGUI_App(action, lvdData, output);
                addActionTf = output.output{1};
            else
                addActionTf = false;
                warndlg('There are no rectangular sensors in this scenario.  Create one first.','Cannot Create Action','modal');
            end
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function [model] = svmTrain(X, Y, C, kernelFunction, ...
                            tol, max_passes)
%SVMTRAIN Trains an SVM classifier using a simplified version of the SMO
%algorithm.
%   [model] = SVMTRAIN(X, Y, C, kernelFunction, tol, max_passes) trains an
%   SVM classifier and returns trained model. X is the matrix of training
%   examples.  Each row is a training example, and the jth column holds the
%   jth feature.  Y is a column matrix containing 1 for positive examples
%   and 0 for negative examples.  C is the standard SVM regularization
%   parameter.  tol is a tolerance value used for determining equality of
%   floating point numbers. max_passes controls the number of iterations
%   over the dataset (without changes to alpha) before the algorithm quits.
%
% Note: This is a simplified version of the SMO algorithm for training
%       SVMs. In practice, if you want to train an SVM classifier, we
%       recommend using an optimized package such as:
%
%           LIBSVM   (http://www.csie.ntu.edu.tw/~cjlin/libsvm/)
%           SVMLight (http://svmlight.joachims.org/)
%
%

if ~exist('tol', 'var') || isempty(tol)
    tol = 1e-3;
end

if ~exist('max_passes', 'var') || isempty(max_passes)
    max_passes = 5;
end

% Data parameters
m = size(X, 1);
n = size(X, 2);

% Map 0 to -1
Y(Y==0) = -1;

% Variables
alphas = zeros(m, 1);
b = 0;
E = zeros(m, 1);
passes = 0;
eta = 0;
L = 0;
H = 0;

% Pre-compute the Kernel Matrix since our dataset is small
% (in practice, optimized SVM packages that handle large datasets
%  gracefully will _not_ do this)
%
% We have implemented optimized vectorized version of the Kernels here so
% that the svm training will run faster.
if strcmp(func2str(kernelFunction), 'linearKernel')
    % Vectorized computation for the Linear Kernel
    % This is equivalent to computing the kernel on every pair of examples
    K = X*X';
elseif strfind(func2str(kernelFunction), 'gaussianKernel')
    % Vectorized RBF Kernel
    % This is equivalent to computing the kernel on every pair of examples
    X2 = sum(X.^2, 2);
    K = bsxfun(@plus, X2, bsxfun(@plus, X2', - 2 * (X * X')));
    K = kernelFunction(1, 0) .^ K;
else
    % Pre-compute the Kernel Matrix
    % The following can be slow due to the lack of vectorization
    K = zeros(m);
    for i = 1:m
        for j = i:m
             K(i,j) = kernelFunction(X(i,:)', X(j,:)');
             K(j,i) = K(i,j); %the matrix is symmetric
        end
    end
end

% Train
fprintf('\nTraining ...');
dots = 12;
while passes < max_passes,

    num_changed_alphas = 0;
    for i = 1:m,

        % Calculate Ei = f(x(i)) - y(i) using (2).
        % E(i) = b + sum (X(i, :) * (repmat(alphas.*Y,1,n).*X)') - Y(i);
        E(i) = b + sum (alphas.*Y.*K(:,i)) - Y(i);

        if ((Y(i)*E(i) < -tol && alphas(i) < C) || (Y(i)*E(i) > tol && alphas(i) > 0)),

            % In practice, there are many heuristics one can use to select
            % the i and j. In this simplified code, we select them randomly.
            j = ceil(m * rand());
            while j == i,  % Make sure i \neq j
                j = ceil(m * rand());
            end

            % Calculate Ej = f(x(j)) - y(j) using (2).
            E(j) = b + sum (alphas.*Y.*K(:,j)) - Y(j);

            % Save old alphas
            alpha_i_old = alphas(i);
            alpha_j_old = alphas(j);

            % Compute L and H by (10) or (11).
            if (Y(i) == Y(j)),
                L = max(0, alphas(j) + alphas(i) - C);
                H = min(C, alphas(j) + alphas(i));
            else
                L = max(0, alphas(j) - alphas(i));
                H = min(C, C + alphas(j) - alphas(i));
            end

            if (L == H),
                % continue to next i.
                continue;
            end

            % Compute eta by (14).
            eta = 2 * K(i,j) - K(i,i) - K(j,j);
            if (eta >= 0),
                % continue to next i.
                continue;
            end

            % Compute and clip new value for alpha j using (12) and (15).
            alphas(j) = alphas(j) - (Y(j) * (E(i) - E(j))) / eta;

            % Clip
            alphas(j) = min (H, alphas(j));
            alphas(j) = max (L, alphas(j));

            % Check if change in alpha is significant
            if (abs(alphas(j) - alpha_j_old) < tol),
                % continue to next i.
                % replace anyway
                alphas(j) = alpha_j_old;
                continue;
            end

            % Determine value for alpha i using (16).
            alphas(i) = alphas(i) + Y(i)*Y(j)*(alpha_j_old - alphas(j));

            % Compute b1 and b2 using (17) and (18) respectively.
            b1 = b - E(i) ...
                 - Y(i) * (alphas(i) - alpha_i_old) *  K(i,j)' ...
                 - Y(j) * (alphas(j) - alpha_j_old) *  K(i,j)';
            b2 = b - E(j) ...
                 - Y(i) * (alphas(i) - alpha_i_old) *  K(i,j)' ...
                 - Y(j) * (alphas(j) - alpha_j_old) *  K(j,j)';

            % Compute b by (19).
            if (0 < alphas(i) && alphas(i) < C),
                b = b1;
            elseif (0 < alphas(j) && alphas(j) < C),
                b = b2;
            else
                b = (b1+b2)/2;
            end

            num_changed_alphas = num_changed_alphas + 1;

        end

    end

    if (num_changed_alphas == 0),
        passes = passes + 1;
    else
        passes = 0;
    end

    fprintf('.');
    dots = dots + 1;
    if dots > 78
        dots = 0;
        fprintf('\n');
    end
    if exist('OCTAVE_VERSION')
        fflush(stdout);
    end
end
fprintf(' Done! \n\n');

% Save the model
idx = alphas > 0;
model.X= X(idx,:);
model.y= Y(idx);
model.kernelFunction = kernelFunction;
model.b= b;
model.alphas= alphas(idx);
model.w = ((alphas.*Y)'*X)';

end

author: zsiciarz

repo: ml-coursera


text:
function varargout = nleqs_master(fcn, x0, opt)
%NLEQS_MASTER  Nonlinear Equation Solver wrapper function.
%   [X, F, EXITFLAG, OUTPUT, JAC] = NLEQS_MASTER(FCN, X0, OPT)
%   [X, F, EXITFLAG, OUTPUT, JAC] = NLEQS_MASTER(PROBLEM)
%   A common wrapper function for various nonlinear equation solvers.
%   Solves the nonlinear equation f(x) = 0, beginning from a starting
%   point x0.
%
%   Inputs:
%       FCN : handle to function that evaluates the function f(x) to
%           be solved and its (optionally, depending on the selected
%           solver) Jacobian, J(x). Calling syntax for this function is:
%               f = FCN(x)
%               [f, J] = FCN(x)
%           If f and x are n x 1, then J is the n x n matrix of partial
%           derivatives of f (rows) w.r.t. x (cols).
%       X0 : starting value, x0, of vector x
%       OPT : optional options structure with the following fields,
%           all of which are also optional (default values shown in
%           parentheses)
%           alg ('DEFAULT') : determines which solver to use
%               'DEFAULT' : automatic, current default is NEWTON
%               'NEWTON'  : standard, full-Jacobian Newton's method
%               'CORE'    : core algorithm, with arbitrary update function
%               'FD'      : fast-decoupled Newton's method
%               'FSOLVE'  : FSOLVE, MATLAB Optimization Toolbox
%               'GS'      : Gauss-Seidel method
%           verbose (0) - controls level of progress output displayed
%               0 = no progress output
%               1 = some progress output
%               2 = verbose progress output
%           max_it (0) - maximum number of iterations
%                       (0 means use solver's own default)
%           tol (0) - termination tolerance on f(x)
%                       (0 means use solver's own default)
%           core_sp - solver parameters struct for NLEQS_CORE, required
%               when alg = 'CORE' (see NLEQS_CORE for details)
%           fd_opt - options struct for fast-decoupled Newton, NLEQS_FD_NEWTON
%           fsolve_opt - options struct for FSOLVE
%           gs_opt - options struct for Gauss-Seidel method, NLEQS_GAUSS_SEIDEL
%           newton_opt - options struct for Newton's method, NLEQS_NEWTON
%       PROBLEM : The inputs can alternatively be supplied in a single
%           PROBLEM struct with fields corresponding to the input arguments
%           described above: fcn, x0, opt
%
%   Outputs (all optional, except X):
%       X : solution vector x
%       F : final function value, f(x)
%       EXITFLAG : exit flag
%           1 = converged
%           0 or negative values = solver specific failure codes
%       OUTPUT : output struct with the following fields:
%           alg - algorithm code of solver used
%           (others) - algorithm specific fields
%       JAC : final Jacobian matrix, J(x)
%
%   Note the calling syntax is almost identical to that of FSOLVE from
%   MathWorks' Optimization Toolbox. The function for evaluating the
%   nonlinear function and Jacobian is identical.
%
%   Calling syntax options:
%       [x, f, exitflag, output, jac] = nleqs_master(fcn, x0);
%       [x, f, exitflag, output, jac] = nleqs_master(fcn, x0, opt);
%       x = nleqs_master(problem);
%               where problem is a struct with fields: fcn, x0, opt
%               and all fields except 'fcn' and 'x0' are optional
%       x = nleqs_master(...);
%       [x, f] = nleqs_master(...);
%       [x, f, exitflag] = nleqs_master(...);
%       [x, f, exitflag, output] = nleqs_master(...);
%       [x, f, exitflag, output, jac] = nleqs_master(...);
%
%   Example: (problem from https://www.chilimath.com/lessons/advanced-algebra/systems-non-linear-equations/)
%       function [f, J] = f1(x)
%       f = [  x(1)   + x(2) - 1;
%             -x(1)^2 + x(2) + 5    ];
%       if nargout > 1
%           J = [1 1; -2*x(1) 1];
%       end
%
%       problem = struct( ...
%           'fcn',    @(x)f1(x), ...
%           'x0',       [0; 0], ...
%           'opt',      struct('verbose', 2) ...
%       );
%       [x, f, exitflag, output, jac] = nleqs_master(problem);
%
%   See also NLEQS_NEWTON, NLEQS_CORE, NLEQS_FD_NEWTON, NLEQS_FSOLVE,
%   NLEQS_GAUSS_SEIDEL, FSOLVE.

%   MP-Opt-Model
%   Copyright (c) 2010-2020, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MP-Opt-Model.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/mp-opt-model for more info.

%%----- input argument handling  -----
%% gather inputs
if nargin == 1 && isstruct(fcn) %% problem struct
    p = fcn;
    fcn = p.fcn;
    x0 = p.x0;
    if isfield(p, 'opt'),   opt = p.opt;    else,   opt = [];   end
else                            %% individual args
    if nargin < 3
        opt = [];
    end
end

%% default options
if ~isempty(opt) && isfield(opt, 'alg') && ~isempty(opt.alg)
    alg = opt.alg;
else
    alg = 'DEFAULT';
end
if strcmp(alg, 'DEFAULT')
    alg = 'NEWTON';
end

%%----- call the appropriate solver  -----
switch alg
    case 'NEWTON'               %% use Newton's method solver
        nleqs_fcn = @nleqs_newton;
    case 'FD'                   %% use fast-decoupled Newton's method solver
        nleqs_fcn = @nleqs_fd_newton;
    case 'FSOLVE'               %% use fsolve
        nleqs_fcn = @nleqs_fsolve;
    case 'GS'                   %% use Gauss-Seidel solver
        nleqs_fcn = @nleqs_gauss_seidel;
    case 'CORE'                 %% use core solver
        nleqs_fcn = @(f, x, o)nleqs_core(opt.core_sp, f, x, o);
    otherwise
        error('nleqs_master: ''%s'' is not a valid algorithm code', alg);
end
[varargout{1:nargout}] = nleqs_fcn(fcn, x0, opt);

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function [compartmentReactions] = findRxnFromCompartment(model, compartment)
% Finds all the reactions and their identifiers in a compartment of interest.
%
% USAGE:
%
%    [compartmentReactions] = findRxnFromCompartment(model,Compartment)
%
% INPUTS:
%    model:                     COBRA model strcture
%    compartment:               compartment of interest (e.g.: '[m]', '[n]', '[e]', etc.)
%
% OUTPUT:
%    compartmentMetabolites:    List of reactions in the compartment of interest
%
% .. Authors:
%       - written by Diana El Assal 01/06/16
%       - rewritten by Uri David Akavia 6-Jul-2018

if (length(compartment) == 1)
    compartment = ['[' compartment ']'];
end
% Find mets in this compartment
compartmentMets = ~cellfun(@isempty, strfind(model.mets, compartment));
% Find reactions that involve the above mets
compartmentRxns = model.rxns(any(model.S(compartmentMets, :)));
compartmentReactions = [compartmentRxns, printRxnFormula(model, 'rxnAbbrList', compartmentRxns, 'printFlag', false)];

author: opencobra

repo: cobratoolbox


text:
function [error,Reallignedsource,transform]=ICPmanu2weigthed(target,source,d2)

% This function rotates, translates and scales a 3D pointcloud "source" of N*3 size (N points in N rows, 3 collumns for XYZ)
% to fit a similar shaped point cloud "target" again of N by 3 size with a
% specifc weigth given to a surface are on the source mesh defined by d2
%
% The output shows the minimized value of dissimilarity measure in "error", the transformed source data set and the
% transformation, rotation, scaling and translation in transform.T, transform.b and transform.c such that
% Reallignedsource = b*source*T + c;

index=1;
[errortemp(index,:),Reallignedsourcetemp,transform]=ICPmanu_allignweigthed(target,source,d2);
d=errortemp(index,:);

[errortemp(index+1,:),Reallignedsourcetemp,transform]=ICPmanu_allignweigthed(target,Reallignedsourcetemp,d2);
index=index+1;
d=errortemp(index,:);

while ((errortemp(index-1,:)-errortemp(index,:)))>0.0000001
[errortemp(index+1,:),Reallignedsourcetemp,transform]=ICPmanu_allignweigthed(target,Reallignedsourcetemp,d2);
index=index+1;
d=errortemp(index,:);

end

error=errortemp(index,:);
[d,Reallignedsource,transform] = procrustes(Reallignedsourcetemp,source);

author: Sable

repo: mcbench-benchmarks


text:
% MP_SP_TO_VTK: Export multipatch results to VTK format for plotting.
%
%  mp_sp_to_vtk (u, space, geometry, gnum, npts, filename, fieldnames, [option], [lambda_lame, mu_lame])
%
% INPUT:
%
%     u:           vector of dof weights
%     space:       object representing the space of discrete functions (see sp_bspline)
%     geometry:    geometry structure (see geo_load)
%     gnum:        array that relates the local numbering on each patch with the global one
%     npts:        number of points along each parametric direction where to evaluate
%     filename:    name of the output file.
%     fieldnames:  how to name the saved variables in the vtk file
%     options:     cell array with the fields to plot
%                   accepted options are 'value' (default), 'gradient',
%                   and for vectors also 'curl', 'divergence', 'stress'
%     lambda_lame: function handle to the first Lame coefficient (only needed to compute 'stress')
%     mu_lame:     function handle for the second Lame coefficient (only needed to compute 'stress')
%
% OUTPUT:
%
%    none
%
% Copyright (C) 2010 Carlo de Falco, Rafael Vazquez
% Copyright (C) 2011, 2012, 2015 Rafael Vazquez
%
%    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/>.

function mp_sp_to_vtk (u, space, geometry, gnum, npts, filename, fieldname, varargin)

  if (isa (space, 'sp_multipatch'))
    warning ('For a space of the class SP_MULTIPATCH, we use the method SP_TO_VTK in the class, instead of the (deprecated) MP_SP_TO_VTK')
    sp_to_vtk (u, space, geometry, npts, filename, fieldname, varargin{:});
    return
  end

  str1 = cat (2,'<?xml version="1.0"?> \n', ...
'<VTKFile type="Collection" version="0.1"> \n', ...
'<Collection> \n');

  str2 = cat (2, '<DataSet part="%d" file="%s.vts"/> \n');

  str3 = cat (2, ...
'</Collection>\n', ...
'</VTKFile> \n');

  if (length (filename) < 4 || ~strcmp (filename(end-3:end), '.pvd'))
    pvd_filename = cat (2, filename, '.pvd');
  else
    pvd_filename = filename;
    filename = filename (1:end-4);
  end

  fid = fopen (pvd_filename, 'w');
  if (fid < 0)
    error ('mp_sp_to_vtk: could not open file %s', pvd_filename);
  end

  fprintf (fid, str1);
  ind = union (find (filename == '/', 1, 'last'), find (filename == '\', 1, 'last')) + 1;
  if (isempty (ind)); ind = 1; end
  for iptc = 1:numel(geometry)
    filename_patch_without_path = cat (2, filename(ind:end), '_', num2str (iptc));
    filename_patch = cat (2, filename, '_', num2str (iptc));
    fprintf (fid, str2, iptc, filename_patch_without_path);
    sp_to_vtk (u(abs(gnum{iptc})).*sign(gnum{iptc})', space{iptc}, geometry(iptc), npts, ...
                           filename_patch, fieldname, varargin{:})
  end
  fprintf (fid, str3);

  fclose (fid);

end

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes


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

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

% Last Modified by GUIDE v2.5 19-Feb-2011 00:22:12

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

% Choose default command line output for sr_gui
handles.mouse_pressed=0;
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% This sets up the initial plot - only do when we are invisible
% so window can get raised using sr_gui.
if strcmp(get(hObject,'Visible'),'off')
    plot(rand(5));
end

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

% --- Outputs from this function are returned to the command line.
function varargout = sr_gui_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;

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

h=waitbar(0,'Registering images...');
for id=2:length(handles.images)
    clear timage;
    for color=1:3
        timage(:,:,color)=register_image(double(handles.images{1}(:,:,color)),double(handles.images{id}(:,:,color)));

    end
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);
guidata(hObject,handles);
frame_slider_Callback(hObject, [], handles)

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

% --------------------------------------------------------------------
function LoadMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to LoadMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
folder = uigetdir;
files=dir(sprintf('%s/*.jpg',folder));
tmp=dir(sprintf('%s/*.JPG',folder));
files(length(files)+1:length(files)+length(tmp))=tmp;

handles.images=[];
h=waitbar(0,'Loading images...');
for id=1:length(files)
    handles.images{id}=double(imread(sprintf('%s/%s',folder,files(id).name)))/255;
%     for color=1:3
%         timage(:,:,color)=double(flipud(handles.images{id}(:,:,color)'));
%     end
    if length(size(handles.images{id}))==2 % expand grey scale image to color image format
        t=handles.images{id};
        t=zeros([size(handles.images{id}) 3]);
        t(:,:,1)=handles.images{id};
        t(:,:,2)=handles.images{id};
        t(:,:,3)=handles.images{id};
        handles.images{id}=t;
    end
    waitbar(id/length(files),h);
%     handles.images{id}=timage;
end
delete(h);

% for color=1:3
%     timage(:,:,color)=double(flipud(handles.images{1}(:,:,color)'));
% end
% images{1}=timage;

% handle.ImageAxes
axes(handles.ImageAxes);
hold off;
imshow(handles.images{1});
hold on;
set(handles.FrameSlider,'min',1);
set(handles.FrameSlider,'max',length(handles.images));
set(handles.FrameSlider,'value',1);
set(handles.frame_title,'string','Frame 1');
title('Frame 1');
guidata(hObject,handles);

% if ~isequal(folder, 0)
%     open(file);
% end

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

% --------------------------------------------------------------------
function CloseMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to CloseMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...
                     ['Close ' get(handles.figure1,'Name') '...'],...
                     'Yes','No','Yes');
if strcmp(selection,'No')
    return;
end

delete(handles.figure1)

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

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

set(hObject, 'String', {'plot(rand(5))', 'plot(sin(1:0.01:25))', 'bar(1:.5:10)', 'plot(membrane)', 'surf(peaks)'});

% --- Executes on slider movement.
function FrameSlider_Callback(hObject, eventdata, handles)
% hObject    handle to FrameSlider (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
axes(handles.ImageAxes);
hold off;
imshow(handles.images{round(get(hObject,'value'))});
hold on;
%set(handles.frame_title,'string',sprintf('Frame %d',round(get(hObject,'value'))));
title(sprintf('Frame %d',round(get(hObject,'value'))));

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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on mouse motion over figure - except title and menu.
function figure1_WindowButtonMotionFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pos=get(handles.ImageAxes,'currentpoint');
pos=pos(1,1:2);
if inrange(pos,handles.ImageAxes)
    if isfield(handles,'mouse_pressed')
        if handles.mouse_pressed
           if isfield(handles,'last_box')
                if ishandle(handles.last_box)
                    delete(handles.last_box);
                end
           end
           axes(handles.ImageAxes);
           handles.last_box=drawbox(handles.start_pos,pos);
           guidata(hObject,handles);
        end
    end

end

function h=drawbox(p1,p2)
x=[p1(1) p2(1) p2(1) p1(1) p1(1)];
y=[p1(2) p1(2) p2(2) p2(2) p1(2)];
h=plot(x,y);

% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

pos=get(handles.ImageAxes,'currentpoint');
pos=pos(1,1:2);
if inrange(pos,handles.ImageAxes)
    handles.start_pos=pos;
    handles.mouse_pressed=1;
end
guidata(hObject,handles);

%     handles.tmp_box=drawbox(
% if (pos(1) >=0 & pos(1) <=

function flag=inrange(pos,h)
s=size(get(findobj(h,'type','image'),'cdata'));

if (pos(1)>=1) && (pos(2) >=1) && (pos(2) <= s(1)) && (pos(1) <= s(2))
    flag=1;
else
    flag=0;
end

% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure1_WindowButtonUpFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pos=get(handles.ImageAxes,'currentpoint');
pos=pos(1,1:2);

if inrange(pos,handles.ImageAxes)
    handles.mouse_pressed=0;
    handles.end_pos=pos;
    guidata(hObject,handles);
end

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

% Hints: contents = get(hObject,'String') returns BilinearProjectionPopup contents as cell array
%        contents{get(hObject,'Value')} returns selected item from BilinearProjectionPopup
p1(1)=min([handles.start_pos(1),handles.end_pos(1)]);
p1(2)=min([handles.start_pos(2),handles.end_pos(2)]);
p2(1)=max([handles.start_pos(1),handles.end_pos(1)]);
p2(2)=max([handles.start_pos(2),handles.end_pos(2)]);
p1=round(p1); p2=round(p2);
imobj=findobj(handles.ImageAxes,'type','image');
cdata=get(imobj,'cdata');
fid=round(get(handles.FrameSlider,'value'));
cdata=handles.images{fid};
imclip=cdata(p1(2):p2(2),p1(1):p2(1),:);

contents=get(hObject,'String');
figure;
switch contents{get(hObject,'value')}
    case 'zoom 1x'
        imshow(imclip);
        title('zoom 1x');
    case 'zoom 2x'
        imclip=bilinear_interp(double(imclip));
        imshow(imclip);
        title('zoom 2x');
    case 'zoom 4x'
        imclip=bilinear_interp(double(imclip));
        imclip=bilinear_interp(imclip);
        imshow(imclip);
        title('zoom 4x');
end

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

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

function [p1,p2]=get_clip_range(handles)
p1(1)=min([handles.start_pos(1),handles.end_pos(1)]);
p1(2)=min([handles.start_pos(2),handles.end_pos(2)]);
p2(1)=max([handles.start_pos(1),handles.end_pos(1)]);
p2(2)=max([handles.start_pos(2),handles.end_pos(2)]);
p1=round(p1); p2=round(p2);

% --- Executes on button press in SRBWButton.
function SRBWButton_Callback(hObject, eventdata, handles)
% hObject    handle to SRBWButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[p1,p2]=get_clip_range(handles);
for id=1:length(handles.images)
    t2{id}=handles.images{id}(p1(2):p2(2),p1(1):p2(1),1)*255;
end
h=waitbar(0,'Running super-resolution for red component...');
image=sr_bw(t2,h,0,1)/255;
delete(h);
figure; imshow(image); title('super resolution image');

% --- Executes on button press in SRColorButton.
function SRColorButton_Callback(hObject, eventdata, handles)
% hObject    handle to SRColorButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[p1,p2]=get_clip_range(handles);
h=waitbar(0,'Running super-resolution for all three components...');
for color=1:3
    for id=1:length(handles.images)
        t2{id}=handles.images{id}(p1(2):p2(2),p1(1):p2(1),color)*255;
    end
    image{color}=sr_bw(t2,h,(color-1)/3,1/3)/255;
end
delete(h);
tmpimg=zeros([size(image{color}) 3]);
for color=1:3
    tmpimg(:,:,color)=image{color};
end
figure; imshow(tmpimg); title('super resolution image');

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

h=waitbar(0,'Registering images...');
for id=2:length(handles.images)
    clear timage;
    timage=register_color_image(double(handles.images{1}), double(handles.images{id}));
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);
guidata(hObject,handles);
FrameSlider_Callback(hObject, [], handles)

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

% Hint: get(hObject,'Value') returns toggle state of CaptureFramesButton

if get(hObject,'value') % starting capturing
   fprintf('starting capturing...');
   handles.images=[];
   vid=videoinput('winvideo',1,'YUY2_320x240');
   vid.ReturnedColorSpace='rgb';
   fid=1;
   axes(handles.ImageAxes);
   hold off;
   while (get(hObject,'value'))
       handles.images{fid}=double(getsnapshot(vid))/255;
       imshow(handles.images{fid});
       title(sprintf('Frame %d',fid));
       fid=fid+1;
   end
   hold on;
   set(handles.FrameSlider,'min',1);
   set(handles.FrameSlider,'max',length(handles.images));
   set(handles.FrameSlider,'value',length(handles.images));
   guidata(hObject, handles);
else
   fprintf('stoping capturing...');
end

% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over CaptureFramesButton.
function CaptureFramesButton_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to CaptureFramesButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

folder = uigetdir;
h=waitbar(0,'Saving images...');
for id=1:length(handles.images)
    imwrite(handles.images{id},sprintf('%s/%d.JPG',folder,id),'quality',100);
    waitbar(id/length(handles.images),h);
end
delete(h);

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

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

h=waitbar(0,'Rotating images...');
for id=1:length(handles.images)
    clear timage;
    for color=1:3
        timage(:,:,color)=double(flipud(handles.images{id}(:,:,color)'));
    end
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);

% handle.ImageAxes
axes(handles.ImageAxes);
hold off;
imshow(handles.images{1});
hold on;
% set(handles.FrameSlider,'min',1);
% set(handles.FrameSlider,'max',length(handles.images));
set(handles.FrameSlider,'value',1);
set(handles.frame_title,'string','Frame 1');
title('Frame 1');
guidata(hObject,handles);

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

h=waitbar(0,'Rotating images...');
for id=1:length(handles.images)
    clear timage;
    for color=1:3
        timage(:,:,color)=double(flipud(handles.images{id}(:,:,color))');
    end
    handles.images{id}=timage;
    waitbar(id/length(handles.images),h);
end
delete(h);

axes(handles.ImageAxes);
hold off;
imshow(handles.images{1});
hold on;
set(handles.FrameSlider,'value',1);
set(handles.frame_title,'string','Frame 1');
title('Frame 1');
guidata(hObject,handles);

% --------------------------------------------------------------------
function DeleteMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to DeleteMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
fid=round(get(handles.FrameSlider,'value'));
handles.images(fid)=[];
if fid > length(handles.images)
    fid=length(handles.images);
end
set(handles.FrameSlider,'value',fid);
set(handles.FrameSlider,'max',length(handles.images));
axes(handles.ImageAxes);
hold off;
imshow(handles.images{fid});
hold on;
title(sprintf('Frame %d',fid));
guidata(hObject,handles);

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

popupmessage('help.txt');

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


text:
function fname = dtiGetFilenameInDT6(dt6File,strname)
%
%  fname = dtiGetFilenameInDT6(dt6File,strname)
%
%Author: AJS
%Purpose:
%   Get a filename in the dt6 file.  This is here because we may expect
%   standard file naming conventions.  Currently, we expect that the files
%   are relative to the subject directory.
%
% HISTORY:
%  2007.07.20 AJS: wrote it.

% Filenames are stored relative to the subject directory
subjDir = dtiGetSubjDirInDT6(dt6File);

% Filenames are stored relative to the homeDir that is stored
tempdt6 = load(dt6File);

if strcmp(strname,'homeDir')
    fname = tempdt6.files.homeDir;
elseif(isfield(tempdt6,'files')&&isfield(tempdt6.files,strname))
    fname = fullfile(subjDir,getfield(tempdt6.files,strname));
else
    fname = [];
end

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function ebcdic = ch_to_ebcdic ( ch )

%*****************************************************************************80
%
%% CH_TO_EBCDIC converts a character to EBCDIC.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 March 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character CH, the ASCII character.
%
%    Output, character EBCDIC, the corresponding EBCDIC character, or a
%    blank character if no correspondence holds.
%
  ic = ch;

  iebcdic = ic_to_iebcdic ( ic );

  if ( iebcdic ~= -1 )
    ebcdic = iebcdic;
  else
    ebcdic = ' ';
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% Black-Scholes implied vol
%
% sigma=impvol(C,S,K,r,t,T,q,tol)
%
% C: call price (scalar or vector)
% S: Stock price (scalar or vector)
% K: Strike price (scalar or vector)
% r: Interest rate (scalar or vector)
% t: Time now (scalar or vector)
% T: Maturity date (scalar or vector)
% [q]: Dividend yield (scalar or vector). Default=0;
% [tol]: Tolerance. Default=1e-6

function sigma=impvol(C,S,K,r,t,T,q,tol)

T=T-t;

if nargin<8
    tol=1e-6;
end

if nargin<7 || isempty(q)
    q=0;
end

F=S*exp((r-q).*T);
G=C.*exp(r.*T);

alpha=log(F./K)./sqrt(T);
beta=0.5*sqrt(T);

% Now we need to solve G=F Phi(d1)- K Phi(d2) where
% d1=alpha/sigma+beta and d2=alpha/sigma-beta

a=beta.*(F+K);
b=sqrt(2*pi)*(0.5*(F-K)-G);
c=alpha.*(F-K);

disc=max(0,b.^2-4*a.*c);

sigma0=(-b+sqrt(disc))./(2*a);

sigma=NewtonMethod(sigma0);

    function s1=NewtonMethod(s0)

        s1=s0;
        count=0;
        f=@(x) call(S,K,r,x,0,T,q)-C;
        fprime=@(x) call_vega(S,K,r,x,0,T,q);

        max_count=1e3;

        while max(abs(f(s1)))>tol && count<max_count
            count=count+1;

            s0=s1;
            s1=s0-f(s0)./fprime(s0);
        end

        if max(abs(f(s1)))>tol
            disp('Newton method did not converge')
        end
    end

end


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

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

  fx_vec = [ ...
     0.8646647167633873E+00, ...
     0.9996645373720975E+00, ...
     0.9999999847700203E+00, ...
     0.999999999999987E+00, ...
     0.8646647167633873E+00, ...
     0.3934693402873666E+00, ...
     0.1992625970831920E+00, ...
     0.1175030974154046E+00, ...
     0.7688365361336422E-01 ];

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

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

  if ( n_data < 0 )
    n_data = 0;
  end

  n_data = n_data + 1;

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

  return
end


text:
function opt = mpoption_info_mosek(selector)
%MPOPTION_INFO_MOSEK  Returns MATPOWER option info for MOSEK.
%
%   DEFAULT_OPTS = MPOPTION_INFO_MOSEK('D')
%   VALID_OPTS   = MPOPTION_INFO_MOSEK('V')
%   EXCEPTIONS   = MPOPTION_INFO_MOSEK('E')
%
%   Returns a structure for MOSEK options for MATPOWER containing ...
%   (1) default options,
%   (2) valid options, or
%   (3) NESTED_STRUCT_COPY exceptions for setting options
%   ... depending on the value of the input argument.
%
%   This function is used by MPOPTION to set default options, check validity
%   of option names or modify option setting/copying behavior for this
%   subset of optional MATPOWER options.
%
%   See also MPOPTION.

%   MATPOWER
%   Copyright (c) 2014-2016, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

if nargin < 1
    selector = 'D';
end
if have_feature('mosek')
    switch upper(selector)
        case {'D', 'V'}     %% default and valid options
            opt = struct(...
                'mosek',        struct(...
                    'lp_alg',       0, ...
                    'max_it',       0, ...
                    'gap_tol',      0, ...
                    'max_time',     0, ...
                    'num_threads',  0, ...
                    'opts',         [], ...
                    'opt_fname',    '', ...
                    'opt',          0 ...
                ) ...
            );
        case 'E'            %% exceptions used by nested_struct_copy() for applying
            opt = struct(...
                'name',         { 'mosek.opts' }, ...
                'check',        0 ...
                );
%                 'copy_mode',    { @mosek_options } ...
        otherwise
            error('mpoption_info_mosek: ''%s'' is not a valid input argument', selector);
    end
else
    opt = struct([]);       %% MOSEK is not available
end


text:
function triangle_io_test02 ( )

%*****************************************************************************80
%
%% TRIANGLE_IO_TEST02 gets the example element data and writes it to a file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 October 2014
%
%  Author:
%
%    John Burkardt
%
  element_filename = 'example.ele';

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TRIANGLE_IO_TEST02:\n' );
  fprintf ( 1, '  Get example element data, write to a triangle element file.\n' );
%
%  Get element example size.
%
  [ element_num, element_order, element_att_num ] = ...
    triangle_element_size_example ( );
%
%  Print the sizes.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of elements = %d\n', element_num );
  fprintf ( 1, '  Order of elements = %d\n', element_order );
  fprintf ( 1, '  Number of element attributes = %d\n', element_att_num );
%
%  Get the data.
%
  [ element_node, element_att ] = triangle_element_data_example ( element_num, ...
    element_order, element_att_num );
%
%  Print some of the data.
%
  i4mat_transpose_print_some ( element_order, element_num, element_node, ...
    1, 1, element_order, 10, '  Node connectivity of first 10 elements:' );

  r8mat_transpose_print_some ( element_att_num, element_num, element_att, ...
    1, 1, element_att_num, 10, '  Attributes for first 10 elements:' ) ;
%
%  Write the node information to node file.
%
  triangle_element_write ( element_filename, element_num, element_order, ...
    element_att_num, element_node, element_att );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Element data written to file "%s"\n', element_filename );

  return
end


text:
function y = cumGamma(x, a, b)

% CUMGAMMA Cumulative distribution for gamma.
% FORMAT
% DESC computes the cumulative gamma distribution.
% ARG x : input value.
% RETURN p : output probability.
%
% SEEALSO :  gammainc, gamma
%
% COPYRIGHT : Neil D. Lawrence, 2008

% NDLUTIL

y = gammainc(x*b, a);

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function neqn = p19_neqn ( )

%*****************************************************************************80
%
%% P19_NEQN returns the number of equations for problem P19.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer NEQN, the number of equations.
%
  neqn = 4;

  return
end


text:
function Problem = ITERrun_optimizer(Problem,Constraints,Objectives,Spec)

weightings = Objectives.weightings;
if ~any(weightings)
    beep;
    disp('*********** No objective(s) to minimize. ***********')
    return
end

Prob = pre_process(Problem);

GenObjFn = @(X,objtype)...
    EVALobjective(X,Problem,Objectives,Spec,Constraints,objtype);

Prob.nonlcon = @(X) EVALnonlcons(X,Problem,Constraints,Spec);

choice = txtmenu('Choose optimizer to run',...
    {' Return / up menu\n\n\t\tRecommended global search:'
    'Multi-objective genetic algorithm'
    'Genetic algorithm\n\n\t\tRecommended local search:'
    'Nelder-Mead simplex search\n\n\t\tOther search methods:'
    'Steepest descent (fmincon)'
    'Pattern search'
    'Particle swarm'});

if any(choice==[1:2 4:5])
    GUIflag = get_yes_or_no('Leave and open optimization tool GUI? Y/[N]: ',false);
end

if (nnz(weightings) == 1) && (choice == 1) % only one objective for multi
    beep; disp('Only one objective. Using single-objective GA');
    choice = 2;
end

switch choice
    case 0
        return
    case 5 % pattern search
        methodstr = 'Pat. search';
        Prob.objective = @(X) GenObjFn(X,'Single');
        Prob.options = psoptimset(Prob.options,...
            'PlotFcns',{@psplotbestf @psplotmeshsize @psplotbestx});
        Prob.solver = 'patternsearch';
        if GUIflag
            optimtool(Prob);
            disp('Hit F5 to continue when done with GUI');
            keyboard;
        else
            [sol,fval] = patternsearch(Prob);
            Problem = single_solution_postprocess(Problem,sol,fval);
        end

    case 6 % particle swarm
        disp('Not supported')
        return

    case 1 %gamulti
        methodstr = 'MO GA';
        Prob.solver = 'gamultiobj';
        Prob.fitnessfcn = @(X) GenObjFn(X,'MultiPen');
        Prob.options.PlotFcns = {@gaplotstopping @gaplotpareto};

        if GUIflag
            optimtool(Prob);
            disp('Hit F5 to continue when done with GUI')
            keyboard;
        else

            [sol,fval,~,~,population,scores] = ...
                gamultiobj(Prob.fitnessfcn,Prob.nvars,...
                [],[],[],[],Prob.lb,Prob.ub,...
                Prob.options);
            save
            Problem = SELECTind_from_pop(Problem,Constraints,Objectives...
                ,Spec,sol,fval,population,scores);
        end

    case 2 %ga alone
        methodstr = 'GA';
        %set up problem
        Prob.solver = 'ga';
        Prob.fitnessfcn = @(X) GenObjFn(X,'SinglePen');
        Prob.options.PlotFcns = {@gaplotbestf @gaplotbestindiv...
            @gaplotscores @gaplotstopping};

        if GUIflag
            optimtool(Prob);
            disp('Hit F5 to continue when done with GUI')
            keyboard;
        else
            [sol,fval] = ga...
                (Prob.fitnessfcn,Prob.nvars,[],[],[],[],...
                Prob.lb,Prob.ub,[],Prob.options);
            Problem = single_solution_postprocess(Problem,sol,fval);
        end

    case 4 %fmincon
        methodstr = 'fmincon';
        Prob.options = optimset(Prob.options,...
            'TolFun', 1e-5,'TolX', 1e-5,'TolCon',1e-7,...
            'PlotFcns', {@optimplotx @optimplotfval ...
            @optimplotconstrviolation @optimplotstepsize});
        Prob.solver = 'fmincon';
        Prob.objective = @(X) GenObjFn(X,'Single');

        if GUIflag
            optimtool(Prob);
            disp('Hit F5 to continue when done with GUI')
            keyboard;
        else
            [sol,fval] = fmincon(...
                Prob.objective,Prob.x0,...
                [],[],[],[],Prob.lb,Prob.ub,...
                Prob.nonlcon,Prob.options);
            Problem = single_solution_postprocess(Problem,sol,fval);
        end

    case 3 %nelder mead
        methodstr = 'NM';
        Prob.options = optimset(Prob.options,...
            'Tolcon', 1e-6,'TolX', 1e-3,...
            'PlotFcns', {@optimplotx @optimplotfval});
        Prob.objective = @(X) GenObjFn(X,'Single');
        if get_yes_or_no('X0 feasible? [Y]/N: ',true)
            strictness = 'superstrict';
        else strictness = [];
        end

        [sol, fval, ~, optimizer_output] = ...
            optimize(Prob.objective, Prob.x0,...
            Prob.lb, Prob.ub, [],[],[],[],...
            Prob.nonlcon,strictness, Prob.options);

        jnkinfeasible = any(optimizer_output.constrviolation.nonl_ineq{1});
        if jnkinfeasible
            disp('Solution not feasible')
            disp('Constraint violoation:')
            disp(optimizer_output.constrviolation.nonl_ineq{2})
        else
            disp('Solution feasible')
        end

        Problem = single_solution_postprocess(Problem,sol,fval);

end

save(['Autosaves\OptimizerRun' num2str(fix(clock),'%02d') '.mat'])

if get_yes_or_no('Save result to History.xls? [Y]/N: ',true)
    ITERsave_hist(Problem,Constraints,Objectives,Spec,methodstr);
end

end

function Problem = pre_process(Problem)
activeX = Problem.activeX;

Problem.x0 = Problem.x0(activeX);
Problem.nvars = nnz(activeX);
Problem.lb = Problem.lb(activeX);
Problem.ub = Problem.ub(activeX);
Problem.XLabels=Problem.XLabels(activeX);

Problem.Bineq = Problem.bineq;
Problem.Beq = Problem.beq;
Problem.LB = Problem.lb;
Problem.UB = Problem.ub;

%set standard options
Problem.options = gaoptimset('PopulationSize',50,'Generations',50,...
    'TimeLimit',3600*1.5,'StallGenLimit',25,'StallTimeLimit',3600*.5,...
    'TolFun',1e-3,'TolCon',1e-4,...
    'Display','iter',...
    'InitialPopulation',Problem.x0');
Problem.options.TolX = 1e-3;
end

function Problem = single_solution_postprocess(Problem,sol,fval)
% let em know that it's done
beep;pause(.5);beep;pause(.5);beep;pause(.5);beep;pause(.5);beep;pause(.5);

% populate full X vector
solX = Problem.x0;
solX(Problem.activeX) = sol;

fprintf('New objective value: %f\n',fval)
if get_yes_or_no('Replace X0 with optimizer solution? [Y]/N: ',true)
    Problem.x0 = solX;
end
end


text:
function [pkx_final, cluster_final, LogL_final] = LCGMM(X, k, W, options)
% Local Consistent Gaussian Mixture Model (LCGMM)
%
% where
%   X
% Notation:
% X ... (nSmp x mFea)  observed data matrix
%       nSmp  ... number of samples
%       mFea  ... number of features
%
% K     ... number of clusters
% W     ... weight matrix of the affinity graph
%
% options ... Structure holding all settings
%
% You only need to provide the above four inputs.
%
% pkx ... P(z|x)
% R ... covariance matrix
% mu ... mean
%
%
% References:
% [1] Jialu Liu, Deng Cai, Xiaofei He, "Gaussian Mixture Model with
% Local Consistency", AAAI 2010.
% [2] Jialu Liu, "Notes on Local Consistent Gaussian Mixture Model(LCGMM)",
% Online available at http://relau.com/jialuliu/technical_notes/LCGMM.pdf
% [accessed 27-Dec-2011].
%
%   version 2.0 --Dec/2011
%   version 1.0 --Dec/2009
%
%   Written by Jialu Liu (remenberl AT gmail.com)
%              Deng Cai (dengcai AT gmail.com)
%
ZERO_OFFSET = 1e-200;

differror = 1e-7;
if isfield(options,'error')
    differror = options.error;
end

lambda = 0.1;
if isfield(options,'lambda')
    lambda = options.lambda;
end

nRepeat = 5;
if isfield(options,'nRepeat')
    nRepeat = options.nRepeat;
end

maxIter = 100;
if isfield(options,'maxIter')
    maxIter = options.maxIter;
end

minIterOrig = 5;
if isfield(options,'minIter')
    minIterOrig = options.minIter;
end
minIter = minIterOrig-1;

meanFitRatio = 0.1;
if isfield(options,'meanFitRatio')
    meanFitRatio = options.meanFitRatio;
end
meanFitControl = 1;
if isfield(options,'meanFitControl')
    meanFitControl = options.meanFitControl;
end

if ~isfield(options,'InitWay')
    options.InitWay = 'kmeans';
end

show = 0;
if isfield(options,'show')
    show = options.show;
end

debug = 0;
if isfield(options,'debug')
    debug = options.debug;
end

% init mixture
[nSmp mFea] = size(X);

if lambda > 0
    DCol = full(sum(W,2));
    D = spdiags(DCol,0,nSmp,nSmp);
    L = D - W;
end

[cluster,pkx,LogL] = GMM_init(X,k,options);
meanFit = LogL/10;

tryNo = 0;
selectInit = 1;
nIter = 0;
while tryNo < nRepeat
    tryNo = tryNo+1;
    maxErr = 1;
    retry = 0;
    while(maxErr > differror || maxErr==-1)
        % EM iteration
        alertFlag = 0;
        for kidx=1:k
            % compute pi
            cluster(kidx).pb = sum(pkx(:,kidx));
            if cluster(kidx).pb < 1e-20
                retry = 1;
                break;
            end
            % compute Tk
            if lambda > 0
                Tk = 1 - lambda * sum(bsxfun(@minus, pkx(:,kidx), pkx(:,kidx)') .* W, 2) ./ (pkx(:,kidx) + ZERO_OFFSET);
            else
                Tk = ones(nSmp, 1);
            end

            if min(Tk) < 0 && alertFlag == 0 && debug == 1
                alertFlag = 1;
                disp('The covariance matrix might not be positive semidefinate since lambda is too big such that some value of Tik is negative.');
            end

            % compute mean
            cluster(kidx).mu = ((pkx(:,kidx) .* Tk)' * X) / cluster(kidx).pb;

            % compute covariance matrix
            Y1 = X-repmat(cluster(kidx).mu,nSmp,1);
            Y2 = bsxfun(@times,sqrt(pkx(:,kidx) .* Tk), Y1);
            R = (Y2'*Y2) /cluster(kidx).pb;
            %for elemetns in Tk which are negative
            Y3 = bsxfun(@times,sqrt(pkx(:,kidx) .* (-(Tk<0) .* Tk)), Y1);
            R = R - 2 * (Y3'*Y3) /cluster(kidx).pb;

            %
            clear Y2;
            R = max(R,R');

            detR = det(R);
            if detR <= 0
                retry = 1;
                break;
            end

            cluster(kidx).cov = R;
            const = -(mFea*log(2*pi) + log(detR))/2;

            Y2 = R\Y1';
            Y2 = -Y2'/2;
            pkx(:,kidx) = dot(Y1,Y2,2)+const;
            clear Y1 Y2 R;
        end

        if retry
            break;
        end

        llmax=max(pkx,[],2);
        pkx =exp( pkx-repmat(llmax,1,k) );
        pkx = pkx.*repmat([cluster(:).pb],nSmp,1);
        ss = sum(pkx,2);
        llnew = sum(log(ss)+llmax);
        pkx = pkx./(repmat(ss,1,k));

        % compute new likelihood
        if lambda > 0
            llnew = llnew - sum(sum((log(pkx' + ZERO_OFFSET) * L).* pkx')) * lambda / 2;
        end

        LogL = [LogL llnew];
        %
        nIter = nIter + 1;

        meanFit = meanFitRatio*meanFit + (1-meanFitRatio)*llnew;
        maxErr = (llnew-meanFit)/meanFit;
        if show
            if length(LogL) > 1
                disp(['tryNo: ',num2str(tryNo),' Iteration: ',num2str(nIter),' LogL: ',num2str(LogL(end)),' deltaLogL: ',num2str(LogL(end)-LogL(end-1)),' maxErr:',num2str(maxErr)]);
            else
                disp(['tryNo: ',num2str(tryNo),' Iteration: ',num2str(nIter),' LogL: ',num2str(LogL(end)),' maxErr:',num2str(maxErr)]);
            end
        end
        if nRepeat > 1 && selectInit
            maxErr = 1;
        end
        if ~meanFitControl
            maxErr = 1;
        end
        if nIter > minIter
            if selectInit
                maxErr = 0;
            else
                if nIter >= maxIter
                    maxErr = 0;
                end
            end
        end
    end

    if retry && ~(tryNo == nRepeat && nIter >= nIter_final)
        tryNo = tryNo - 1;
        [cluster,pkx,LogL] = GMM_init(X,k,options);
        meanFit = LogL/10;
        nIter = 0;
        continue;
    end

    if tryNo == 1
        pkx_final = pkx;
        cluster_final = cluster;
        LogL_final = LogL;
        nIter_final = nIter;
    else
        if LogL(end) > LogL_final(end)
            pkx_final = pkx;
            cluster_final = cluster;
            LogL_final = LogL;
            nIter_final = nIter;
        end
    end

    if selectInit
        if tryNo < nRepeat
            [cluster,pkx,LogL] = GMM_init(X,k,options);
            meanFit = LogL/10;
            nIter = 0;
        else
            tryNo = tryNo - 1;
            selectInit = 0;
            pkx = pkx_final;
            cluster = cluster_final;
            LogL = LogL_final;
            nIter = nIter_final;
            meanFit = LogL(end)/10;
        end
    end
end

function [cluster,pkx,llnew] = GMM_init(X,k,options)
    ZERO_OFFSET = 1e-200;
    [nSmp, mFea] = size(X);
    if strcmpi(options.InitWay,'kmeans')
        kmeansres = litekmeans(X,k,'maxIter',10);
        residx = unique(kmeansres);
        for kidx=1:k
            smpidx = kmeansres==residx(kidx);
            cluster(kidx).mu = mean(X(smpidx,:),1);
            cluster(kidx).pb = 1/k;
        end
    else
        permutation = randperm(nSmp);
        nSmpClass = floor(nSmp/k);
        for kidx=1:k
            cluster(kidx).mu = mean(X(permutation((kidx-1)*nSmpClass+1:kidx*nSmpClass),:),1);
            cluster(kidx).pb = 1/k;
        end
    end

    R = (nSmp-1)*cov(X)/nSmp;
    R = max(R,R');

    % EM iteration

    pkx=zeros(nSmp,k);
    detR = det(R);
    if detR <= 0
        error('The covariance matrix is not positive definite. Use PCA to reduce the dimensions first!');
    end
    const = -(mFea*log(2*pi) +log(detR))/2;
    for kidx=1:k
        Y1=X-repmat(cluster(kidx).mu,nSmp,1);
        Y2 = R\Y1';
        Y2 = -Y2'/2;
        pkx(:,kidx) = dot(Y1,Y2,2)+const;
        clear Y1 Y2;
    end
    clear R;
    llmax=max(pkx,[],2);
    pkx =exp( pkx-repmat(llmax,1,k) );
    pkx = pkx.*repmat([cluster(:).pb],nSmp,1);
    ss = sum(pkx,2);
    llnew = sum(log(ss)+llmax);
    pkx = pkx./(repmat(ss,1,k));

author: ZJULearning

repo: MatlabFunc


text:
function params = hlp_getDefaultArglist(prefix)
% params = hlp_getDefaultArglist(prefix)
% Returns a cell array of default arguments for finputcheck. The set of
% parameters depends on the specific prefix ('est','hlp','viz','pop')
%
% This function will be deprecated in the beta release

if ~ischar(prefix)
    help(hlp_getDefaultParams);
    error('input argument must be a prefix string (est,hlp,viz,pop)');
end

switch lower(prefix)
    case 'pre'
        params = {
            'resample',         'real'         []                0;              ...                     % new sampling rate
            'components',       'integer'      []               [];              ...
            'newtlims',         'real'         []               [];              ...                     % seconds
            'filter',           'cell'         {}               {};              ...                     % {low-edge hi-edge 'eegfilt'}
            'detrend',          'boolean'      []                0;              ...
            'normalize',        ''             {'ensemble','time',{'time','ensemble'},''}   '';    ...   % 'time' | 'ensemble' | 'both'
            'center',           'boolean'      []                0;              ...                     % remove the mean of each series
            'diff',             'integer'      [0 10]            0;              ...                     % number of times to difference
            'verb',             'integer'      [0 2]             1;              ...                     % verbosity level
            'DO_JACKET',        'boolean'      []                0;              ...                     % use jacket (GPU parallel)
            'newtrials',        'integer'      []               [];              ...                     % list of trials to include
            'badsegments',      'real'         []               [];              ...                     % K x 2 matrix of [lo hi] intervals (seconds) of data within ea. trial to set to nan
            'equalizetrials',   'boolean'      {0 1}             0;              ...                     % equalize the number of trials between two conditions
            };
    case 'est'
        params = {                                                               ...
            'algorithm',          ''           {'vieira-morf','arfit'}     'vieira-morf'; ...            % which algorithm to use for model fitting
            'winStartIdx',        'real'       []               [];              ...                     % vector of sample points (start of windows) at which to estimate windowed VAR model
            'morder',             'real'       []               [];              ...                     % VAR model order
            'winlen',             'real'       []               0.5;             ...                     % window length (sec)
            'winstep',            'real'       []               0.03;            ...                     % window step size (sec)
            'epochTimeLims',      'real'       []               [];              ...                     % time range to analyze (sec) where 0 = event time
            'prctWinToSample',    'real'       [0 100]          100;             ...                     % percent of time windows to randomly select
            'verb',               'real'       [0 2]            2;               ...                     % verbosity level (0=no output, 1=text, 2=gui)
            'timer'               'boolean'    []               0;               ...                     % estimate time required to fit model
            'normalize',          ''           {'ensemble','time',{'time','ensemble'},''}   '';    ...   % normalization 'time' | 'ensemble' | 'both'
            'icselector',         ''           {'sbc','aic','fpe','hq'}   {'sbc','aic'}; ...             % information criteria to use for selecting model order
            'detrend',            ''           {} [] ...
            };
    case 'hlp'
        params = {};
    case 'stat'
        params = {};
    case 'vis'
        params = {};
end

repo: REST


text:
function determ = fibonacci1_determinant ( n, f1, f2 )

%*****************************************************************************80
%
%% FIBONACCI1_DETERMINANT returns the determinant of the FIBONACCI1 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Input, real F1, F2, the first two elements of the sequence
%    that will generate the Fibonacci sequence.
%
%    Output, real DETERM, the determinant.
%
  if ( n == 1 )
    determ = 1.0;
  elseif ( n == 2 )
    determ = -1.0;
  else
    determ = 0.0;
  end

  return
end


text:
% =========================================================================
% =========================================================================
% ================================CHESS=================================
% =========================================================================
% =========================================================================
%
% Author:
%   Muhammad Suleman Shafqat
%   Started on:     19Jan, 2011 (1200hrs)
%   Completed on:   20Jan, 2011 (1130hrs)
%
% Version:
%   01
%
% ---Functions---------Used for
%   Chess               main function
%   playerturn          player's turn
%   checkfp             check final position, it checks position and kills
%   wholoses            to check who loses and if no body return (loses=0)
%   reqmark             converts black to white backgrounds if necessary
%   whichpiece          reads the selected piece and converts it from icon to integer
%
% ---Structures----------Used for
%
%   h                   structure for varialbes
%   ha                  global for components of GUI
%
% ---Variables----------Used for
%
%   box                 to represent position of pieces
%   ipr                 initial position in row
%   ipc                 initial position in column
%   fpr                 final position in row
%   fpc                 final position in column
%   r                   row number of selected button
%   c                   column number of selected button
%   background            to upload a background of board
%   bg                  background image is uploaded here
%   plrmark             an axis to show whose turn is this
%   check               binary variable to check whether a turn is correct or not
%   loses               checked after each turn, whether anybody loses or not
%   plr                 player who needs to turn
%   otherplr            other player
%   ed                  eventdata
% =========================================================================

% simple chess:
%       started on 19/1/2011 at 1200hrs
%       ended on 20/1/2011 at 1130hrs
% changing into symbols:
%       started on 28/1/2011 and completed by 1230hrs
function varargout = CHESS_on_MATLAB(varargin)
% CHESS M-file for CHESS.fig
% Last Modified by GUIDE v2.5 28-Jan-2011 12:16:36
% Begin initialization code
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @CHESS_OpeningFcn, ...
                   'gui_OutputFcn',  @CHESS_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

% --- Executes just before CHESS is made visible.
function CHESS_OpeningFcn(hObj, ed, h, varargin)
% Choose default command line output for CHESS
h.output = hObj;
global ha
clc
% initialization gui components
ha(1)  = h.plrturn;
ha(11) = h.box11;ha(12) = h.box12;ha(13) = h.box13;ha(14) = h.box14;
ha(15) = h.box15;ha(16) = h.box16;ha(17) = h.box17;ha(18) = h.box18;
ha(21) = h.box21;ha(22) = h.box22;ha(23) = h.box23;ha(24) = h.box24;
ha(25) = h.box25;ha(26) = h.box26;ha(27) = h.box27;ha(28) = h.box28;
ha(31) = h.box31;ha(32) = h.box32;ha(33) = h.box33;ha(34) = h.box34;
ha(35) = h.box35;ha(36) = h.box36;ha(37) = h.box37;ha(38) = h.box38;
ha(41) = h.box41;ha(42) = h.box42;ha(43) = h.box43;ha(44) = h.box44;
ha(45) = h.box45;ha(46) = h.box46;ha(47) = h.box47;ha(48) = h.box48;
ha(51) = h.box51;ha(52) = h.box52;ha(53) = h.box53;ha(54) = h.box54;
ha(55) = h.box55;ha(56) = h.box56;ha(57) = h.box57;ha(58) = h.box58;
ha(61) = h.box61;ha(62) = h.box62;ha(63) = h.box63;ha(64) = h.box64;
ha(65) = h.box65;ha(66) = h.box66;ha(67) = h.box67;ha(68) = h.box68;
ha(71) = h.box71;ha(72) = h.box72;ha(73) = h.box73;ha(74) = h.box74;
ha(75) = h.box75;ha(76) = h.box76;ha(77) = h.box77;ha(78) = h.box78;
ha(81) = h.box81;ha(82) = h.box82;ha(83) = h.box83;ha(84) = h.box84;
ha(85) = h.box85;ha(86) = h.box86;ha(87) = h.box87;ha(88) = h.box88;

%uploading symbols of chess pieces to structure 'h'
h.blackpawn1=imread(strcat('pieces\blackpawn1','.png'));
h.blackpawn2=imread(strcat('pieces\blackpawn2','.png'));
h.whitepawn1=imread(strcat('pieces\whitepawn1','.png'));
h.whitepawn2=imread(strcat('pieces\whitepawn2','.png'));
h.blackrook1=imread(strcat('pieces\blackrook1','.png'));
h.blackrook2=imread(strcat('pieces\blackrook2','.png'));
h.whiterook1=imread(strcat('pieces\whiterook1','.png'));
h.whiterook2=imread(strcat('pieces\whiterook2','.png'));
h.blackbishop1=imread(strcat('pieces\blackbishop1','.png'));
h.blackbishop2=imread(strcat('pieces\blackbishop2','.png'));
h.whitebishop1=imread(strcat('pieces\whitebishop1','.png'));
h.whitebishop2=imread(strcat('pieces\whitebishop2','.png'));
h.blackknight1=imread(strcat('pieces\blackknight1','.png'));
h.blackknight2=imread(strcat('pieces\blackknight2','.png'));
h.whiteknight1=imread(strcat('pieces\whiteknight1','.png'));
h.whiteknight2=imread(strcat('pieces\whiteknight2','.png'));
h.blackqueen1=imread(strcat('pieces\blackqueen1','.png'));
h.blackqueen2=imread(strcat('pieces\blackqueen2','.png'));
h.whitequeen1=imread(strcat('pieces\whitequeen1','.png'));
h.whitequeen2=imread(strcat('pieces\whitequeen2','.png'));
h.blackking1=imread(strcat('pieces\blackking1','.png'));
h.blackking2=imread(strcat('pieces\blackking2','.png'));
h.whiteking1=imread(strcat('pieces\whiteking1','.png'));
h.whiteking2=imread(strcat('pieces\whiteking2','.png'));
h.black=imread(strcat('pieces\black','.png'));
h.white=imread(strcat('pieces\white','.png'));
% deletion of extra rows and colomns
h.blackpawn1(:,60,:)=[];
h.blackpawn2(:,60,:)=[];
h.whitepawn2(:,60,:)=[];
h.blackrook1(:,60,:)=[];
h.blackrook2(:,60,:)=[];
h.whiterook1(:,60,:)=[];
h.whiterook2(:,60,:)=[];
h.blackbishop1(:,60,:)=[];
h.blackbishop2(:,60,:)=[];
h.whitebishop1(:,60,:)=[];
h.whitebishop2(:,60,:)=[];
h.blackknight2(:,60,:)=[];
h.whiteknight2(:,60,:)=[];
h.whitequeen2(:,60,:)=[];
h.black(:,60,:)=[];
h.blackrook1(60,:,:)=[];
h.blackrook2(60,:,:)=[];
h.whiterook1(60,:,:)=[];
h.whiterook2(60,:,:)=[];
h.blackbishop1(60,:,:)=[];
h.blackbishop2(60,:,:)=[];
h.whitebishop1(60,:,:)=[];
h.whitebishop2(60,:,:)=[];
h.blackknight1(60,:,:)=[];
h.blackknight2(60,:,:)=[];
h.whiteknight1(60,:,:)=[];
h.whiteknight2(60,:,:)=[];
h.blackqueen1(60,:,:)=[];
h.whitequeen2(60,:,:)=[];
h.blackking1(60,:,:)=[];
h.blackking2(60,:,:)=[];
h.whiteking1(60,:,:)=[];
h.whiteking2(60,:,:)=[];
h.black(60,:,:)=[];
h.white(60,:,:)=[];

% initializing box;  8x8 box
% rook=2
% horse=3
% bishop=4
% queen=5
% king=10
% pawn=1
h.box=[ ...
    2  3  4  5  10 4  3  2 ; ...
    1  1  1  1  1  1  1  1 ; ...
    0  0  0  0  0  0  0  0  ; ...
    0  0  0  0  0  0  0  0  ; ...
    0  0  0  0  0  0  0  0  ; ...
    0  0  0  0  0  0  0  0  ; ...
    -1 -1 -1 -1 -1 -1 -1 -1 ; ...
    -2 -3 -4 -5 -10 -4 -3 -2  ];
% position variables
h.ipr=0;
h.ipc=0;
h.fpr=0;
h.fpc=0;
h.r=0;
h.c=0;
% showing whose turn......initially player one's turn it can be changed
h.plr=1;
set(ha(1),'CData',h.blackking2);
i=2;
% now initializing figure with player marks
for x=1:8
    for y=1:8
% required when to convert pieces from numbers to uploaded symbols
        if h.box(x,y)==1
            if i==1
                mark=h.blackpawn1;
                i=2;
            elseif i==2
                mark=h.blackpawn2;
                i=1;
            end
        elseif h.box(x,y)==-1
            if i==1
                mark=h.whitepawn1;
                i=2;
            elseif i==2
                mark=h.whitepawn2;
                i=1;
            end
        elseif h.box(x,y)==2
            if i==1
                mark=h.blackrook1;
                i=2;
            elseif i==2
                mark=h.blackrook2;
                i=1;
            end
        elseif h.box(x,y)==-2
            if i==1
                mark=h.whiterook1;
                i=2;
            elseif i==2
                mark=h.whiterook2;
                i=1;
            end
        elseif h.box(x,y)==3
            if i==1
                mark=h.blackknight1;
                i=2;
            elseif i==2
                mark=h.blackknight2;
                i=1;
            end
        elseif h.box(x,y)==-3
            if i==1
                mark=h.whiteknight1;
                i=2;
            elseif i==2
                mark=h.whiteknight2;
                i=1;
            end
        elseif h.box(x,y)==4
            if i==1
                mark=h.blackbishop1;
                i=2;
            elseif i==2
                mark=h.blackbishop2;
                i=1;
            end
        elseif h.box(x,y)==-4
            if i==1
                mark=h.whitebishop1;
                i=2;
            elseif i==2
                mark=h.whitebishop2;
                i=1;
            end
        elseif h.box(x,y)==5
            if i==1
                mark=h.blackqueen1;
                i=2;
            elseif i==2
                mark=h.blackqueen2;
                i=1;
            end
        elseif h.box(x,y)==-5
            if i==1
                mark=h.whitequeen1;
                i=2;
            elseif i==2
                mark=h.whitequeen2;
                i=1;
            end
        elseif h.box(x,y)==10
            if i==1
                mark=h.blackking1;
                i=2;
            elseif i==2
                mark=h.blackking2;
                i=1;
            end
        elseif h.box(x,y)==-10
            if i==1
                mark=h.whiteking1;
                i=2;
            elseif i==2
                mark=h.whiteking2;
                i=1;
            end
        else
            if i==1
                mark=h.black;
                i=2;
            elseif i==2
                mark=h.white;
                i=1;
            end
        end
        rc=x*10+y;
        set(ha(rc),'CData',mark);
    end
%     first row starting from white next row starting from black
    if i==1
        i=2;
    else i=1;
    end

end
%set(CHESS,'Visible','on')
% Update h structure
guidata(hObj, h);

function varargout = CHESS_OutputFcn(hObj, ed, h)
% Get default command line output from h structure
varargout{1} = h.output;

% --- Executes on button press in exit.
function exit_Callback(hObj, ed, h)
% used to close the game anytime
close(gcbf)

% --- Executes during object creation, after setting all properties.
function plrturn_CreateFcn(hObj, ed, h)
if ispc && isequal(get(hObj,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObj,'BackgroundColor','white');
end

% --- Executes on button press in concede.
function concede_Callback(hObj, ed, h)
if h.plr==2
    msgbox('CHESS KING','Winner','custom',h.blackking2)
elseif h.plr==1
    msgbox('CHESS KING','Winner','custom',h.whiteking1)
end
close(gcbf);

function box11_Callback(hObj, ed, h)
global ha
h.r=1;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box12_Callback(hObj, ed, h)
global ha
h.r=1;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box13_Callback(hObj, ed, h)
global ha
h.r=1;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box14_Callback(hObj, ed, h)
global ha
h.r=1;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box15_Callback(hObj, ed, h)
global ha
h.r=1;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box16_Callback(hObj, ed, h)
global ha
h.r=1;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box17_Callback(hObj, ed, h)
global ha
h.r=1;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box18_Callback(hObj, ed, h)
global ha
h.r=1;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

function box21_Callback(hObj, ed, h)
global ha
h.r=2;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box22_Callback(hObj, ed, h)
global ha
h.r=2;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box23_Callback(hObj, ed, h)
global ha
h.r=2;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box24_Callback(hObj, ed, h)
global ha
h.r=2;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box25_Callback(hObj, ed, h)
global ha
h.r=2;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box26_Callback(hObj, ed, h)
global ha
h.r=2;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box27_Callback(hObj, ed, h)
global ha
h.r=2;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box28_Callback(hObj, ed, h)
global ha
h.r=2;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

function box31_Callback(hObj, ed, h)
global ha
h.r=3;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box32_Callback(hObj, ed, h)
global ha
h.r=3;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box33_Callback(hObj, ed, h)
global ha
h.r=3;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box34_Callback(hObj, ed, h)
global ha
h.r=3;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box35_Callback(hObj, ed, h)
global ha
h.r=3;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box36_Callback(hObj, ed, h)
global ha
h.r=3;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box37_Callback(hObj, ed, h)
global ha
h.r=3;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box38_Callback(hObj, ed, h)
global ha
h.r=3;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

function box41_Callback(hObj, ed, h)
global ha
h.r=4;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box42_Callback(hObj, ed, h)
global ha
h.r=4;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box43_Callback(hObj, ed, h)
global ha
h.r=4;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box44_Callback(hObj, ed, h)
global ha
h.r=4;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box45_Callback(hObj, ed, h)
global ha
h.r=4;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box46_Callback(hObj, ed, h)
global ha
h.r=4;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box47_Callback(hObj, ed, h)
global ha
h.r=4;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box48_Callback(hObj, ed, h)
global ha
h.r=4;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

function box51_Callback(hObj, ed, h)
global ha
h.r=5;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box52_Callback(hObj, ed, h)
global ha
h.r=5;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box53_Callback(hObj, ed, h)
global ha
h.r=5;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box54_Callback(hObj, ed, h)
global ha
h.r=5;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box55_Callback(hObj, ed, h)
global ha
h.r=5;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box56_Callback(hObj, ed, h)
global ha
h.r=5;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box57_Callback(hObj, ed, h)
global ha
h.r=5;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box58_Callback(hObj, ed, h)
global ha
h.r=5;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

function box61_Callback(hObj, ed, h)
global ha
h.r=6;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box62_Callback(hObj, ed, h)
global ha
h.r=6;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box63_Callback(hObj, ed, h)
global ha
h.r=6;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box64_Callback(hObj, ed, h)
global ha
h.r=6;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box65_Callback(hObj, ed, h)
global ha
h.r=6;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box66_Callback(hObj, ed, h)
global ha
h.r=6;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box67_Callback(hObj, ed, h)
global ha
h.r=6;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box68_Callback(hObj, ed, h)
global ha
h.r=6;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

function box71_Callback(hObj, ed, h)
global ha
h.r=7;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box72_Callback(hObj, ed, h)
global ha
h.r=7;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box73_Callback(hObj, ed, h)
global ha
h.r=7;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box74_Callback(hObj, ed, h)
global ha
h.r=7;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box75_Callback(hObj, ed, h)
global ha
h.r=7;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box76_Callback(hObj, ed, h)
global ha
h.r=7;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box77_Callback(hObj, ed, h)
global ha
h.r=7;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box78_Callback(hObj, ed, h)
global ha
h.r=7;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

function box81_Callback(hObj, ed, h)
global ha
h.r=8;h.c=1;
h=playerturn(ha,h);
guidata(hObj,h);

function box82_Callback(hObj, ed, h)
global ha
h.r=8;h.c=2;
h=playerturn(ha,h);
guidata(hObj,h);

function box83_Callback(hObj, ed, h)
global ha
h.r=8;h.c=3;
h=playerturn(ha,h);
guidata(hObj,h);

function box84_Callback(hObj, ed, h)
global ha
h.r=8;h.c=4;
h=playerturn(ha,h);
guidata(hObj,h);

function box85_Callback(hObj, ed, h)
global ha
h.r=8;h.c=5;
h=playerturn(ha,h);
guidata(hObj,h);

function box86_Callback(hObj, ed, h)
global ha
h.r=8;h.c=6;
h=playerturn(ha,h);
guidata(hObj,h);

function box87_Callback(hObj, ed, h)
global ha
h.r=8;h.c=7;
h=playerturn(ha,h);
guidata(hObj,h);

function box88_Callback(hObj, ed, h)
global ha
h.r=8;h.c=8;
h=playerturn(ha,h);
guidata(hObj,h);

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


text:
function c8_i_test ( )

%*****************************************************************************80
%
%% C8_I_TEST tests C8_I.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 February 2015
%
%  Author:
%
%    John Burkardt
%
  seed = 123456678;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'C8_I_TEST\n' );
  fprintf ( 1, '  C8_I computes the imaginary unit I.\n' );
  fprintf ( 1, '\n' );
  c1 = c8_i ( );
  fprintf ( 1, '  C1 = C8_I ( ) = (%g,%g)\n', real ( c1 ), imag ( c1 ) );

  c2 = c1 * c1;
  fprintf ( 1, '  C2 = C1 * C1 = (%g,%g)\n', real ( c2 ), imag ( c2 ) );

  return
end


text:
function net = res_finetune_init(imdb, n)
net = sprintf('imagenet-resnet-%d-dag', n);

if  ischar(net),
  net_path = fullfile('data','models',[net '.mat']);
  if ~exist(net_path,'file'),
    fprintf('Downloading model (%s) ...', net) ;
    vl_xmkdir(fullfile('data','models')) ;
    urlwrite(fullfile('http://www.vlfeat.org/matconvnet/models', ...
      [net '.mat']), net_path) ;
    fprintf(' done!\n');
  end
  net = dagnn.DagNN.loadobj(load(net_path));
end

net.meta.trainOpts.weightDecay = 0.0001 ;
net.meta.trainOpts.momentum = 0.9;
net.meta.trainOpts.batchSize = 256 ;
net.meta.classes.name = imdb.meta.classes;
net.meta.classes.description = imdb.meta.classes;

% remove 'prob'
net.removeLayer(net.layers(end).name);

[h,w,in,out] = size(zeros(net.layers(end).block.size));
out = numel(net.meta.classes.name);
% remove 'fc'
lName = net.layers(end).name;
net.removeLayer(net.layers(end).name);

pName = net.layers(end).name;
block = dagnn.Conv('size', [h,w,in,out], 'hasBias', true, ...
                   'stride', 1, 'pad', 0);
net.addLayer(lName, block, pName, lName, {[lName '_f'], [lName '_b']});
%net.params(net.layers(end).paramIndexes(1)).value = init_weight(opts, h, w, in, out, 'single');
%net.params(net.layers(end).paramIndexes(2)).value = zeros(out, 1, 'single');
p = net.getParamIndex(net.layers(end).params) ;
params = net.layers(end).block.initParams() ;
params = cellfun(@gather, params, 'UniformOutput', false) ;
[net.params(p).value] = deal(params{:}) ;

lName = net.layers(end).name;
net.addLayer('softmax', dagnn.SoftMax(), lName, 'softmax');
net.addLayer('loss', dagnn.Loss('loss', 'log'), {'softmax', 'label'}, 'loss');
net.addLayer('error', dagnn.Loss('loss', 'classerror'), {'softmax','label'}, 'error') ;
net.addLayer('error5', dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...
  {'softmax','label'}, 'error5') ;

net.meta.augmentation.rgbVariance = zeros(0,3) ;
net.meta.augmentation.transformation = 'stretch' ;

end

repo: ResNet-Matconvnet


text:
function list = translateList(list, trList1, trList2)
% Translate a list of identifiers (either numerical or cell array) using a dictionary
%
% USAGE:
%
%     list = translateList(list, trList1, trList2)
%
% INPUTS:
%    list:       original list
%    trList1:    list of elemets to be changed
%    trList2:    list of elements to be changed into
%
% OUTPUTS:
%    list:       list after changes
%
% EXAMPLE:
%
%    % Define original list
%    list = {'a', 'b', 'c'}
%
%    % Define dictionary
%    trList1 = {'b', 'c'}
%    trList2 = {'B', 'C'}
%
%    newList = translateList(list, trList1, trList2);
%
%    % returns
%    newList = {'a', 'B', 'C'};

[isInList, listInd] = ismember(list, trList1);

list(isInList) = trList2(listInd(listInd ~= 0));