text:
classdef chebtech1 < chebtech
%CHEBTECH1   Approximate smooth functions on [-1,1] with Chebyshev interpolants.
%
%   Class for approximating smooth functions on the interval [-1,1]
%   using function values at 1st-kind Chebyshev points and coefficients of the
%   corresponding 1st-kind Chebyshev series expansion.
%
% Constructor inputs:
%   CHEBTECH1(OP) constructs a CHEBTECH1 object from the function handle OP. OP
%   should be vectorized (i.e., accept a vector input) and ouput a vector of
%   the same length. CHEBTECH1 objects allow for array-valued construction
%   (i.e., of array-valued function), in which case OP should accept a vector
%   of length N and return a matrix of size NxM, where M is number of columns
%   of the multi -valued function.
%
%   CHEBTECH1(OP, DATA) constructs a CHEBTECH2 using the additional data
%   supplied in the DATA structure.  Fields currently recognized are:
%     DATA.VSCALE    (Default:  0)
%     DATA.HSCALE    (Default:  1)
%         The constructor builds a CHEBTECH1 with 'happiness' (see
%         HAPPINESSCHECK.m) relative to the maximum of the given vertical scale
%         DATA.VSCALE and the (column-wise) infinity norm of the sampled
%         function values of OP, and the fixed horizontal scale DATA.HSCALE.
%   If any fields in DATA are empty or not supplied, or if DATA itself is empty
%   or not supplied, appropriate default values are set.
%
%   CHEBTECH1(OP, DATA, PREF) overrides the default behavior with that given by
%   the preference structure PREF.
%
%   CHEBTECH1(VALUES, ...) returns a CHEBTECH1 object which interpolates the
%   values in the columns of VALUES at 1st-kind Chebyshev points and
%   CHEBTECH1({VALUES, COEFFS}, ... ) uses the Chebyshev coefficients passed in
%   COEFFS rather than computing them. If COEFFS are passed, the resulting
%   CHEBTECH1 is always deemed 'happy'.
%
% Examples: % Basic construction: f = chebtech1(@(x) sin(x))
%
%   % Construction with preferences:
%   p.sampleTest = 0; % See CHEBTECH.TECHPREF for details
%   f = chebtech1(@(x) sin(x), [], [], p)
%
%   % Array-valued construction:
%   f = chebtech1(@(x) [sin(x), cos(x), exp(x)])
%
% See also CHEBTECH, CHEBTECH.TECHPREF, CHEBPTS, HAPPINESSCHECK, REFINE.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CHEBTECH1 Class Description:
%
% The CHEBTECH1 class represents smooth functions on the interval [-1,1] using
% function values at 1st-kind Chebyshev points and coefficients of the
% corresponding 1st-kind Chebyshev series expansion.
%
% The constructor is supplied with a handle that evaluates a given function on
% an increasingly fine Chebyshev 1st-kind grid (see REFINE.m) until the
% representation is deemed 'happy' (see HAPPINESSCHECK). The resulting
% object can be used to evaluate and operate on the input function.
%
% More information can be found in the CHEBTECH class definition.
%
% Class diagram: [<<CHEBTECH>>] <-- [CHEBTECH1]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% CLASS CONSTRUCTOR:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = false )
        function obj = chebtech1(op, data, pref)
            % Parse inputs.
            if ( (nargin == 0) || isempty(op) )
                % Return an empty CHEBTECH1 on null input:
                return
            end

            if ( (nargin < 2) || isempty(data) )
                    data = struct();
            end

            if ( (nargin < 3) || isempty(pref) )
                pref = chebtech.techPref();
            else
                pref = chebtech.techPref(pref);
            end

            data = chebtech.parseDataInputs(data, pref);

            % Force nonadaptive construction if PREF.FIXEDLENGTH is numeric and
            % we're not using contour integrals.
            if ( ~(isnumeric(op) || iscell(op)) && ...
                    ~isnan(pref.fixedLength) && ~pref.useTurbo )
                % Evaluate op on the Chebyshev grid of given size:
                op = feval(op, chebtech1.chebpts(pref.fixedLength));
            end

            % Actual construction takes place here:
            [obj, values] = populate(obj, op, data, pref);

            if ( isnumeric(op) || iscell(op) )
                % Set length of obj to PREF.FIXEDLENGTH (if it is non-trivial).
                if ( ~isnan(pref.fixedLength ) )
                    obj = prolong(obj, pref.fixedLength);
                end

                % No need to error check when constructing from discrete data.
                return
            elseif ( obj.ishappy )
                % Use contour integrals ("turbo" mode) if requested.
                if ( pref.useTurbo )
                    obj = constructorTurbo(obj, op, pref);
                end

                % No need to error check if we are happy:
                return
            end

            % Check for NaNs (if not happy):
            if ( any(isnan(obj.coeffs(:))) )
                % Here we throw an error if NaNs were encountered anywhere.
                error('CHEBFUN:CHEBTECH1:chebtech1:nanEval', ...
                    'Function returned NaN when evaluated.')
            end
        end
    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% STATIC METHODS:
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods ( Access = public, Static = true )

        % Aliasing:
        coeffs = alias(coeffs, m)

        % Angles of Chebyshev points. (i.e., acos(chebpts(n))
        t = angles(n);

        % Evaluate a Chebyshev interpolant using proper barycentric formula:
        out = bary(x, values)

        % Compute Chebyshev barycentric weights:
        w = barywts(n)

        % Compute Chebyshev points (x) and optionally quadrature (w)
        % and barycentric (v) weights.
        [x, w, v, t] = chebpts(n)

        % Tensor product grid of Chebyshev points in 1D, 2D or 3D:
        out = tensorGrid(N, dom)

        % Convert coefficients to values:
        values = coeffs2vals(coeffs)

        % Make a CHEBTECH1 (constructor shortcut):
        f = make(varargin);

        % Compute Chebyshev quadrature weights:
        w = quadwts(n)

        % Refinement function for CHEBTECH1 construction (evaluates OP on grid):
        [values, points, giveUp] = refine(op, values, pref)

        % Return the value-based discretization class which uses CHEBTECH1:
        function disc = returnValsDisc()
            disc = @chebcolloc1;
        end

        % Convert values to coefficients:
        coeffs = vals2coeffs(values)

    end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function r = sqr(a)
%SQR          Taylor (elementwise) square  sqr(a)
%

% written  05/21/09     S.M. Rump
% modified 08/26/12     S.M. Rump  global variables removed
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  K1 = getappdata(0,'INTLAB_TAYLOR_ORDER') + 1;

  r = a;
  r.t(1,:) = sqr(a.t(1,:));
  for j=2:K1
    r.t(j,:) = sum(a.t(1:j,:).*a.t(j:-1:1,:),1);
  end

  if rndold
    setround(rndold)
  end

repo: OpenMAS


text:
function square_symq_rule_test01 ( degree, n )

%*****************************************************************************80
%
%% SQUARE_SYMQ_RULE_TEST01 calls SQUARESYMQ for a quadrature rule of given order.
%
%  Licensing:
%
%    This code is distributed under the GNU GPL license.
%
%  Modified:
%
%    01 July 2014
%
%  Author:
%
%    Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.
%    This MATLAB version by John Burkardt.
%
%  Reference:
%
%    Hong Xiao, Zydrunas Gimbutas,
%    A numerical algorithm for the construction of efficient quadrature
%    rules in two and higher dimensions,
%    Computers and Mathematics with Applications,
%    Volume 59, 2010, pages 663-676.
%
%  Parameters:
%
%    Input, integer DEGREE, the desired total polynomial degree exactness
%    of the quadrature rule.
%
%    Input, integer N, the number of nodes.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SQUARE_SYMQ_RULE_TEST01\n' );
  fprintf ( 1, '  Symmetric quadrature rule for a square.\n' );
  fprintf ( 1, '  Polynomial exactness degree DEGREE = %d\n', degree );

  area = 4.0;
%
%  Retrieve and print a symmetric quadrature rule.
%
  [ x, w ] = square_symq ( degree, n );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of nodes N = %d\n', n );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     J  W       X       Y\n' );
  fprintf ( 1, '\n' );
  for j = 1 : n
    fprintf ( 1, '  %4d  %14.6g  %14.6g  %14.6g\n', j, w(j), x(1,j), x(2,j) );
  end

  d = sum ( w(1:n) );

  fprintf ( 1, '   Sum  %14.6g\n', d );
  fprintf ( 1, '  Area  %14.6g\n', area );

  return
end

author: johannesgerer

repo: jburkardt-m


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

author: petercorke

repo: robotics-toolbox-matlab


text:
function e = normcdfln(x)
% NORMCDFLN   log of normal cumulative density function.
% More accurate than log(normcdf(x)) when x is small.
% The following is a quick and dirty approximation to normcdfln:
% normcdfln(x) =approx -(log(1+exp(0.88-x))/1.5)^2

% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.

% make e the same shape as x, and inherit any NaNs.
e = x;
t = -6.5;
i = find(x >= t);
if ~isempty(i)
  e(i) = log(normcdf(x(i)));
end
i = find(x < t);
if ~isempty(i)
  x = x(i);
  z = x.^(-2);
  if 0
    % log of asymptotic series for cdf
    % subs(x=-x,asympt(sqrt(2*Pi)*gauss_cdf(-x),x));
    c = [-1 3 -15 105 -945 10395 -135135 2027025 -34459425 654729075];
    y = 0;
    for i = length(c):-1:1
      y = z.*(y + c(i));
    end
    %y = z.*(c(1)+z.*(c(2)+z.*(c(3)+z.*(c(4)+z.*(c(5)+z.*(c(6)+z.*c(7)))))));
    y = log(1+y);
  else
    % asymptotic series for logcdf
    % subs(x=-x,asympt(log(gauss_cdf(-x)),x));
    c = [-1 5/2 -37/3 353/4 -4081/5 55205/6 -854197/7];
    y = z.*(c(1)+z.*(c(2)+z.*(c(3)+z.*(c(4)+z.*(c(5)+z.*(c(6)+z.*c(7)))))));
  end
  e(i) = y -0.5*log(2*pi) -0.5*x.^2 - log(-x);
end

author: andrewssobral

repo: lrslibrary


text:
function L=wfbtlength(Ls,wt,varargin);
%WFBTLENGTH  WFBT length from signal
%   Usage: L=wfbtlength(Ls,wt);
%
%   `wfbtlength(Ls,wt)` returns the length of a Wavelet system that is long
%   enough to expand a signal of length *Ls*. Please see the help on
%   |wfbt| for an explanation of the parameter *wt*.
%
%   If the returned length is longer than the signal length, the signal
%   will be zero-padded by |wfbt| to length *L*.
%
%   In addition, the function accepts flags defining boundary extension
%   technique as in |wfbt|. The returned length can be longer than the
%   signal length only in case of `'per'` (periodic extension).
%
%   See also: wfbt, fwt

% AUTHOR: Zdenek Prusa

complainif_notposint(Ls,'Ls','WFBTLENGTH');

definput.import = {'fwt'};
[flags,kv]=ltfatarghelper({},definput,varargin);

% Initialize the wavelet filters structure
if ~isstruct(wt)
   wt = wfbtinit(wt);
end

if(flags.do_per)
   a = treeSub(wt);
   L = filterbanklength(Ls,a);
else
   L = Ls;
end

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function [lp,dlp] = priorInvGauss(mu,lam,x)

% Univariate Inverse Gaussian hyperparameter prior distribution.
% Compute log-likelihood and its derivative or draw a random sample.
% The prior distribution is parameterized as:
%
%   p(x) = exp(-lam*(x-mu)^2/(2*mu^2*x)) / sqrt(2*pi*x^3/lam)
%
% where mu(1x1) is the mean parameter, lam(1x1) is the scale parameter
% and x(1xN) contains query hyperparameters for prior evaluation.
%
% For more help on design of priors, try "help priorDistributions".
%
% Copyright (c) by Roman Garnett and Hannes Nickisch, 2014-09-08.
%
% See also PRIORDISTRIBUTIONS.M.

if nargin<2, error('mu and lam parameters need to be provided'), end
if ~(isscalar(mu)&&isscalar(lam))
  error('mu and lam parameters need to be scalars'),end
if nargin<3                                                    % return a sample
  n = randn; y = n*n;
  r = mu + mu*(mu*y-sqrt(4*mu*lam*y+mu^2*y^2))/(2*lam);
  z = rand;
  if z<=mu/(mu+r)
    lp = r;
  else
    lp = mu^2/r;
  end
  return
end

lp  = -lam*(x-mu).^2./(2*mu^2*x) - log(2*pi*x.^3/lam)/2;
q = (x-mu)./x;
dlp = -lam*q.*(2-q)/(2*mu^2) - 3./(2*x);
lp(x<0) = -inf; dlp(x<0) = 0;

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text: %% SO3FunComposition

author: mtex-toolbox

repo: mtex

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


text:
erplabver = '9.10';                  % current erplab version
erplabrel = '16-Feb-2023';             % DOB
erplabdeveloper = 'Simmons&Zhang';
%ColorB = [170 180 195]/255;          % old background color (until version 3)
%ColorB = [0.9216 0.8353 0.6078];     % background color for version 4
%ColorB = [0.7020 0.7647 0.8392];     % background color since version 4.0.0.3
%ColorB = [0.9804 0.8118 0.5529];     % background color since version 4.0.0.11
ColorB       = [0.7020 0.77 0.85];     % background color since version 4.0.0.12
ColorF       = [0.02 0.02 0.02];       % foreground color since version 4.0.2.0
errorColorF  = [0 0 0];                % foreground color for error window
errorColorB  = [0.6824 1 0.6353];      % background color for error window
fontunitsGUI = 'pixels';

set(0,'Units','pixels')
thisscreen = get(0, 'ScreenSize');
if thisscreen(4)>=1440
    fontsizeGUI = 12; % high resolution display (eg Retina)
else
    fontsizeGUI = 11;
end

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab


text:
function [cY,mY,ng] = motion_metrics(Y,bnd,batch_size,var_name)

% computes several metrics for the quantitative assessment of the registration

% INPUTS
% Y:            registered time series in a loaded or memory mapped array
% bnd:          number of pixels to be exluded to avoid NaN effects
%                   [x_beg,x_end,y_be,y_end,z_beg,z_end]
% batch_size:   size of batch to be read for memory mapped files
% var_name:     in case of memory mapped files use this variable

% OUTPUTS
% cY:           correlation coefficient of each frame with the mean
% mY:           mean image
% ng:           norm of gradient of mean image

if nargin == 1 || isempty(bnd); bnd = zeros(6,1); end
if nargin < 3|| isempty(batch_size); batch_size = 1000; end

memmap = isobject(Y);

if memmap
    if ~exist('var_name','var')
        try sizY = size(Y,'Y'); var_name = 'Y'; catch; sizY = size(Y,'M'); var_name = 'M'; end
    end
else
    sizY = size(Y);
end

dimsY = length(sizY);
nd = dimsY - 1;
d = prod(sizY(1:end-1));
T = sizY(end);

if isscalar(bnd); bnd = ones(2*(dimsY-1),1)*bnd; end
if dimsY == 3; sizY(3) = 1; bnd(5:6) = 0; end

if memmap
    cY = zeros(T,1);
    mY = zeros(sizY(1:end-1));

    for t = 1:batch_size:T
        y_temp = single(load_data(Y,t,batch_size));
        sy = size(y_temp,ndims(y_temp));
        delta = nanmean(y_temp,ndims(y_temp));
        mY = mY*(t-1)/(t+sy-1) + sy*delta/(t+sy-1);
    end

    m_temp = mY(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6));
    mYr = m_temp(:);
    for t = 1:batch_size:T
        y_temp = single(load_data(Y,t,batch_size));
        sy = size(y_temp,ndims(y_temp));
        if nd == 2; y_temp = y_temp(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),:); end
        if nd == 3; y_temp = y_temp(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6),:); end
        Yr = reshape(y_temp,[],sy);
        if any(any(isnan(Yr))) || any(isnan(mYr));
            cY(t:min(t+batch_size-1,T)) = corr(Yr,mYr,'rows','p');
        else
            cY(t:min(t+batch_size-1,T)) = corr(Yr,mYr);
        end
    end
else
    Y = single(Y);
    nd = ndims(Y)-1;
    mY = nanmean(Y,nd+1);
    if nd == 2
        Yr = Y(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),:);
        mYr = mY(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4));
    else
        Yr = Y(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6),:);
        mYr = mY(bnd(1)+1:sizY(1)-bnd(2),bnd(3)+1:sizY(2)-bnd(4),bnd(5)+1:sizY(3)-bnd(6));
    end
    Yr = reshape(Yr,[],T);
    mYr = mYr(:);
    if any(any(isnan(Yr))) || any(isnan(mYr));
        cY = corr(Yr,mYr,'rows','p');
    else
        cY = corr(Yr,mYr);
    end
end

if ismatrix(mY);
    [gx,gy] = gradient(mY);
    ng = norm(sqrt(gx.^2+gy.^2),'fro');
elseif ndims(Y)-1 == 3;
    [gx,gy,gz] = gradient(mY);
    ng = sqrt(sum(gx(:).^2+gy(:).^2+gz(:).^2));
end

    function y_temp = load_data(X,t,batch_size)
        lY = min(T-t+1,batch_size);
        if ~memmap
            y_temp = reshape(X(d*(t-1) + (1:d)),[sizY(1:end-1),lY]);
        else
            if strcmp(var_name,'Y')
                if dimsY == 3
                    y_temp = double(X.Y(:,:,t:t+lY-1));
                else
                    y_temp = double(X.Y(:,:,:,t+lY-1));
                end
            elseif strcmp(var_name,'M')
                if dimsY == 3
                    y_temp = double(X.M(:,:,t+lY-1));
                else
                    y_temp = double(X.M(:,:,:,t+lY-1));
                end
            else
                error('unknown variable name')
            end
        end
    end
end

author: flatironinstitute

repo: NoRMCorre


text:
function[varargout]=vswap(varargin)
%VSWAP  VSWAP(X,A,B) replaces A with B in numeric array X.
%
%   VSWAP(X,A,B) replaces A with B in numeric array X.  A and B may be
%   numbers, NAN, +/- INF, NAN+SQRT(-1)*NAN, or INF+SQRT(-1)*INF.
%
%   Note that X may also be a cell array of numeric arrays.
%
%   [Y1,Y2,...YN]=VSWAP(X1,X2,...XN,A,B) also works.
%
%   VSWAP(X1,X2,...XN,A,B); with no output arguments overwrites the
%   original input variables.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2001--2015 J.M. Lilly --- type 'help jlab_license' for details

if strcmpi(varargin{1}, '--t')
  vswap_test,return
end

a=varargin{end-1};
b=varargin{end};

for i=1:length(varargin)-2
  x=varargin{i};
  varargout{i}=swapnum_loop(x,a,b);
end

eval(to_overwrite(nargin-2))

function[x]=swapnum_loop(x,a,b)
if iscell(x)
    for i=1:length(x)
        x{i}=swapnum1(x{i},a,b);
    end
else
    x=swapnum1(x,a,b);
end

function[x]=swapnum1(x,a,b)

if isfinite(a)
    bool=(x==a);
else
  if isnan(a)
       if isnan(imag(a))
            bool=isnan(real(x))&isnan(imag(x));
       else
            bool=isnan(x);
       end
  elseif isinf(a)
       if isinf(imag(a))
          bool=isinf(real(x))&isinf(imag(x));
       else
          if a>0
              bool=(isinf(x)&x>0);
          else
              bool=(isinf(x)&x<0);
          end
       end
   end
end

%Convert booleans to double
x=double(x);
x(bool)=b;

function[]=vswap_test
x=(1:10);
ans1=[2 (2:10)];
reporttest('VSWAP num case', aresame(vswap(x,1,2),ans1))

x=[nan (1:10)];
ans1=(0:10);
reporttest('VSWAP nan case', aresame(vswap(x,nan,0),ans1))

x=[nan*(1+sqrt(-1)) nan inf 1:10];
ans1=[0 nan inf 1:10];
reporttest('VSWAP complex nan case', aresame(vswap(x,nan+sqrt(-1)*nan,0),ans1))

x=[inf*(1+sqrt(-1)) nan inf 1:10];
ans1=[0 nan inf 1:10];
reporttest('VSWAP complex inf case', aresame(vswap(x,inf+sqrt(-1)*inf,0),ans1))

x=[nan*(1+sqrt(-1)) nan -inf 1:10];
ans1=[nan*(1+sqrt(-1)) nan 0 1:10];
reporttest('VSWAP negative inf case', aresame(vswap(x,-inf,0),ans1))

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab


text:
function DoTrajK(handles)

global VObj;
global VMag;
global VCtl;
global VSig;
global VCoi;

%preserve VObj VMag & VCoi
VTmpObj=VObj;
VTmpMag=VMag;
VTmpCoi=VCoi;

handles.Simuh=guidata(handles.Simuh.SimuPanel_figure);
DoDisableButton([],[],handles.Simuh);
%% Do K-Space Traj
try
    % Read tab parameters
    fieldname=fieldnames(handles.Attrh2);
    for i=1:length(fieldname)/2
        try
            eval(['TK.' fieldname{i*2} '=[' get(handles.Attrh2.(fieldname{i*2}),'String') '];']);
        catch me
            TAttr=get(handles.Attrh2.(fieldname{i*2}),'String');
            eval(['TK.' fieldname{i*2} '=''' TAttr{get(handles.Attrh2.(fieldname{i*2}),'Value')}  ''';']);
        end
    end

    % Prescan config
    DoPreScan(handles.Simuh);

    % Create SpinWatcher VOtk, VMtk & VCtk
    VOtk=VObj;
    VOtk.SpinNum=1;
    VOtk.TypeNum=1;
    VOtk.Rho=1;
    VOtk.T1=1;
    VOtk.T2=0.1;
    VOtk.T2Star=0.01;
    VOtk.XDim=1;
    VOtk.YDim=1;
    VOtk.ZDim=1;
    VOtk.Mx= 0;
    VOtk.My= 0;
    VOtk.Mz= 1;

    % Gradient Grid
    VMtk=VMag;
    VMtk.Gxgrid=0;
    VMtk.Gygrid=0;
    VMtk.Gzgrid=0;
    VMtk.dB0=0;
    VMtk.dWRnd=0;
    VMtk.FRange=1;

    % Coil
    VCtk=VCoi;
    VCtk.TxCoilmg=1;
    VCtk.TxCoilpe=0;
    VCtk.TxCoilNum=1;
    VCtk.RxCoilx=1;
    VCtk.RxCoily=0;
    VCtk.RxCoilNum=1;

    %% Spin execution
    VObj=VOtk;
    VMag=VMtk;
    VCoi=VCtk;

    % Generate Pulse line
    DoPulseGen(handles);

    % Simulation Process
    try
        VCtl.CS=double(VObj.ChemShift*VCtl.B0);
        VCtl.RunMode=int32(0); % Image scan
        VCtl.MaxThreadNum=int32(handles.Simuh.CPUInfo.NumThreads);
        DoDataTypeConv(handles.Simuh);
        DoScanAtCPU; % global (VSeq,VObj,VCtl,VMag,VCoi,VVar,VSig) are needed
    catch me
        error_msg{1,1}='ERROR!!! Scan process aborted.';
        error_msg{2,1}=me.message;
        errordlg(error_msg);
        %recover VObj
        VObj=VTmpObj;
        VMag=VTmpMag;
        VCoi=VTmpCoi;
        return;
    end
catch me
    error_msg{1,1}='ERROR!!! Spin execution process aborted.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);
    %recover VObj
    VObj=VTmpObj;
    VMag=VTmpMag;
    VCoi=VTmpCoi;
    return;
end

Kx=VSig.Kx;
Ky=VSig.Ky;
Kz=VSig.Kz;

%recover VObj
VObj=VTmpObj;
VMag=VTmpMag;
VCoi=VTmpCoi;

pause(0.1);

switch TK.RenderMode
    case 'VTK'
        % VTK 3D rendering
        switch TK.RenderPoint
            case 'off'
                DoKSpaceTrajVTK([Kx(:)';Ky(:)';Kz(:)'],ones(size(Kx(:)'))*1,0);
            case 'on'
                DoKSpaceTrajVTK([Kx(:)';Ky(:)';Kz(:)'],ones(size(Kx(:)'))*1,1);
        end
    case 'Matlab'
        % Matlab 3D plot
        figure('Color','k');
        switch TK.RenderPoint
            case 'off'
                Ktraj=plot3(Kx(:),Ky(:),Kz(:),'w-');
                grid on;
            case 'on'
                Ktraj=quiver3(Kx(:),Ky(:),Kz(:),[diff(Kx(:));0],[diff(Ky(:));0],[diff(Kz(:));0],'w-');
                set(Ktraj,'AutoScale','off');
        end

                set(gca,'Color','k','xcolor','c','ycolor','c','zcolor','c');
        set(gca,'ydir','reverse');
        xlabel('Kx','Color','w');
        ylabel('Ky','Color','w');
        zlabel('Kz','Color','w');
        title('K-space Traj.','Color','w');
end

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function out = upSample(im, nLevels, filt)
% out = upSample(im, nLevels, [filt])
%
% Upsamples the image im by the integer nLevels.
% The upsampled image is blurred and edges are
% dealt with by zero-padding.
%
% The blurring is done with the filter kernel specified by filt
% (default = [.125 .5 .75 .5 .125]'), which should be a vector
% (applied separably as a 1D convolution kernel in X and Y),
% or a matrix (applied as a 2D convolution kernel)
%
% 99.08.16 RFD wrote it, based on upBlur (and helpful
%				comments from DJH)

if nLevels ~= fix(nLevels)
   error('nLevels must be an integer!!!');
end

if ~exist('filt', 'var')
	% default filter for post-upsample convolution
	filt = sqrt(2)*namedFilter('binom5');
end

% use a little recursion to deal with upsample steps > 2
if nLevels > 1
  im = upSample(im, nLevels-1);
end
if (nLevels >= 1)
   if (any(size(im)==1))
      if (size(im,1)==1)
         filt = filt';
      end
      out = upConv(im, filt, 'zero',(size(im)~=1)+1);
   else
      % First, upsample and blur down cols...
      out = upConv(im, filt, 'zero', [2 1]);
		% Then, upsample and blur across rows...
      out = upConv(out, filt', 'zero', [1 2]);
   end
else
   out = im;
end

return

%%% Debug/test

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function L = ge(p1,p2)
%PREAL/GE Overloaded GE (>=) operator for class preal.

global useUnitsFlag

if ~(useUnitsFlag) % If physunits is disabled...
    L=ge(double(p1),double(p2)); % ... treat as double.
    return
end

p1=preal(p1);
p2=preal(p2);
tol=0.001;
if isscalar(p1)
    p1=preal(p1.value*ones(size(p2)),p1.units);
elseif isscalar(p2)
    p2=preal(p2.value*ones(size(p1)),p2.units);
elseif ndims(p1)==ndims(p2)&size(p1)==size(p2)
    % do nothing
else
    error('Array dimensions must agree')
end

L=false(size(p1));
for k=1:numel(L)
    if any(abs(p1(k).units-p2(k).units)>tol)
        error('Attempt to compare dimensionally inconsistent preals')
    end
    L(k)=ge(p1(k).value,p2(k).value);
end

author: Sable

repo: mcbench-benchmarks


text:
%  Figure 10.18      Feedback Control of Dynamic Systems, 5e
%                        Franklin, Powell, Emami
%
%  fig10_18.m is a script to generate Fig 10.18,
%  the symmetric  rootlocus for the LQR symmetric rootlocus
%  compensator of the satellite position control, non-collocated case

% parameter values
m=[1, 0.1]; k=[0, 0.091] ; d=[0, 0.0036]; k1=[0, 0.4];
% call model
[f,g,h,j] = twomass(m,k,d);
s=[f, g;h, 0];r=[0*g;1]; n=s\r;nx=n(1:4);nu=n(5);
% call model
[f1,g,h,j] = twomass(m,k1,d);
% Form G(s)G(-s) in state-space
a=[f, 0*f;
-h'*h, -f'];
b=[g;0*g];
c=[0*h, g'];
d=[0];

hold off; clf;
sysGG=ss(a,b,c,d);
rlocus(sysGG);
grid;
v=[-2 2 -1.5 1.5];axis(v);
title('Fig. 10.18 Symmetric rootlocus for the satellite')


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

% Last Modified by GUIDE v2.5 17-Dec-2019 09:16:07

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

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = AnnotationUI_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 selection change in classesList.
function classesList_Callback(hObject, eventdata, handles)
% hObject    handle to classesList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns classesList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from classesList

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

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

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

% Hints: contents = cellstr(get(hObject,'String')) returns fileNamesList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from fileNamesList

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

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

% --- Executes on button press in showMarkersCheckBox.
function showMarkersCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to showMarkersCheckBox (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 showMarkersCheckBox

% --- Executes on button press in laxCheckBox.
function laxCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to laxCheckBox (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 laxCheckBox

% --- Executes on button press in layCheckBox.
function layCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to layCheckBox (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 layCheckBox

% --- Executes on button press in lazCheckBox.
function lazCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to lazCheckBox (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 lazCheckBox

% --- Executes on button press in energyCheckBox.
function energyCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to energyCheckBox (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 energyCheckBox

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

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

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

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

% Hints: contents = cellstr(get(hObject,'String')) returns signalsList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from signalsList

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

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

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

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

% Hints: contents = cellstr(get(hObject,'String')) returns signalComputerList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from signalComputerList

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

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

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

% --- Executes on button press in peaksCheckBox.
function peaksCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to peaksCheckBox (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 peaksCheckBox

% --- Executes on button press in myCheckbox.
function myCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to myCheckbox (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 myCheckbox

% --- Executes on key press with focus on mainFigure or any of its controls.
function mainFigure_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to mainFigure (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in showRangesCheckBox.
function showRangesCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to showRangesCheckBox (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 showRangesCheckBox

% --- Executes on button press in showEventsCheckBox.
function showEventsCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to showEventsCheckBox (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 showEventsCheckBox

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

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

% --- Executes on button press in selectAllCheckBox.
function selectAllCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to selectAllCheckBox (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 selectAllCheckBox

% --- Executes on button press in loadVideoCheckBox.
function loadVideoCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to loadVideoCheckBox (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 loadVideoCheckBox

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

% --- Executes on button press in synchronizeVideoCheckBox.
function synchronizeVideoCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to synchronizeVideoCheckBox (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 synchronizeVideoCheckBox

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

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

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

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

% --- Executes on button press in suggestAnnotationsCheckBox.
function suggestAnnotationsCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to suggestAnnotationsCheckBox (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 suggestAnnotationsCheckBox

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

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

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function img = im_crop(ori, p, out_size)
    %% crop part of the image according to the given bounding box coordinates
    %% for out-of-boundary part, just use an constance value
    sz = size(ori);
    p(1) = floor(p(1)); p(2) = floor(p(2));
    p(3) = ceil(p(3)); p(4) = ceil(p(4));
    img = ((ones(p(4), p(3), 3) * 120));

    x1 = round(p(1) - p(3) / 2);
    y1 = round(p(2) - p(4) / 2);
    x2 = x1 + p(3) - 1;
    y2 = y1 + p(4) - 1;
    crop_x1 = max(1, -x1 + 2); x1 = max(1, x1);
    crop_y1 = max(1, -y1 + 2); y1 = max(1, y1);
    crop_x2 = min(p(3), p(3) + sz(2) - x2); x2 = min(x2, sz(2));
    crop_y2 = min(p(4), p(4) + sz(1) - y2); y2 = min(y2, sz(1));
    img( crop_y1 : crop_y2, crop_x1 : crop_x2, :) = ori(y1 : y2, x1 : x2, :);

    if nargin > 2
        img = imresize(img, [out_size, out_size], 'Antialiasing', false);
    end
end

author: flyers

repo: drone-tracking


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% strtsw.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function s = strtsw(smax,level,f)
% updates the record list for starting a new sweep and computes the
% lowest level containing non-split boxes

% Input:
% smax         depth of search
% level(1:nboxes)  levels of these boxes (level(j) = 0 if box j has
%              already been split)
% f(1:nboxes)  their function values at the base vertices

% Output:
% s            lowest level with record(s) ~= 0

function s = strtsw(smax,level,f)
global nboxes record
% nboxes       number of boxes not in the `shopping basket'
% record(1:smax-1)  vector pointing to the best non-split box at each
%              level; record(s) = 0 if there is no non-split box at
%              level s (record list)

% initialization
record = zeros(smax-1,1);
s = smax;
for j = 1:nboxes
  if level(j) > 0
    if level(j) < s
      s = level(j);
    end
    if ~record(level(j))
      record(level(j)) = j;
    elseif f(j) < f(record(level(j)))
      record(level(j)) = j;
    end
  end
end

author: lacerbi

repo: optimviz

save_path: github-repos/MATLAB/lacerbi-optimviz


text:
function [ i, j ] = i4_to_pascal ( k )

%*****************************************************************************80
%
%% I4_TO_PASCAL converts a linear index to Pascal triangle coordinates.
%
%  Discussion:
%
%    We describe the grid points in Pascal's triangle in two ways:
%
%    As a linear index K:
%
%                     1
%                   2   3
%                 4   5   6
%               7   8   9   10
%
%    As elements (I,J) of Pascal's triangle:
%
%                     0,0
%                  1,0   0,1
%               2,0   1,1    0,2
%            3,0   2,1   1,2    0,3
%
%  Example:
%
%     K  I  J
%
%     1  0  0
%     2  1  0
%     3  0  1
%     4  2  0
%     5  1  1
%     6  0  2
%     7  3  0
%     8  2  1
%     9  1  2
%    10  0  3
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 April 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer K, the linear index of the (I,J) element.
%    1 <= K.
%
%    Output, integer I, J, the Pascal indices.
%
  if ( k <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4_TO_PASCAL - Fatal error!\n' );
    fprintf ( 1, '  K must be positive.\n' );
    error ( 'I4_TO_PASCAL - Fatal error!' );
  end

  d = i4_to_pascal_degree ( k );

  j = k - ( d * ( d + 1 ) ) / 2 - 1;
  i = d - j;

  return
end


text:
function outputFormatOK = changeCbMapOutput(outputFormat)
%changeCbMapOutput sets the output format for drawCbMap. Displays
%outputFormat if no inputs provided.
%
% outputFormatOK = changeCbMapOutput(outputFormat)
%
%OPTIONAL INPUT
% outputFormat      drawCbMap render format
%                   {'svg', 'matlab', 'java'} (java not implemented)
%OUTPUT
% outputFormatOK    True if output format set properly, else false.
%
%

global CB_MAP_OUTPUT

%% List output format if no inputs
if nargin <1
    outputFormatOK = 0;
    fprintf('CB map output set to : %s\n',CB_MAP_OUTPUT);
    return;
end

%% List supported output here
supportedOutput = {'matlab','svg'};

%% Set CB_MAP_OUTPUT if outputFormat is supported
if any(strcmpi(outputFormat,supportedOutput))
    CB_MAP_OUTPUT = outputFormat;
    outputFormatOK = 1;
else
    warning([outputFormat ' is not a supported render format.']);
    outputFormatOK = 0;
end

author: opencobra

repo: cobratoolbox


text:
%Device Device enumeration for the brick
%
% Notes::
% - Collection of enumeration constants used for the brick

classdef Device < uint8
    enumeration
         % motor definitions (found in c_output.c => NOS DATA8)
         MotorA (1)
         MotorB (2)
         MotorC (4)
         MotorD (8)
         % braking (found in c_output.c)
         Coast (0)
         Brake (1)
         % sensor ports (found in c_output.c)
         Port1 (0)
         Port2 (1)
         Port3 (2)
         Port4 (3)
         % LED patterns (found in bytecodes.h)
         LedBlack (0)
         LedGreen (1)
         LedRed   (2)
         LedOrange (3)
         LedGreenFlash (4)
         LedRedFlash (5)
         LedOrangeFlash (6)
         LedGreenPulse (7)
         LedRedPulse (8)
         LedOrangePulse (9)
         % colors (found in bytecodes.h)
         NoColor (0)
         BlackColor (1)
         BlueColor (2)
         GreenColor (3)
         YellowColor (4)
         RedColor (5)
         WhiteColor (6)
         BrownColor (7)
         % ultrasonic sensor definitions (found in types.html)
         Ultrasonic (30)
         USDistCM (0)
         USDistIN (1)
         USListen (2)
         % gyro sensor definitions (found in types.html)
         Gyro (32)
         GyroAng (0)
         GyroRate (1)
         % touch sensor definitions (found in types.html)
         Touch (16)
         Pushed (0)
         Bumps (1)
         % color sensor definitions (found in types.html)
         Color (29)
         ColReflect (0)
         ColAmbient (1)
         ColColor (2)
    end
end


text:
function [res, fusion] = imMergeEnclosedRegions(lbl, varargin)
% Merge regions within a label image, based on an inclusion criteria.
%
%   Merge regions in an image. Criterion is a inclusion criterion: if a
%   region is mostly within the convex image of a neighbor region, then the
%   two region merge.
%
%	See Also
%	  imMergeRegions, imRAG
%

% ------
% Author: David Legland
% e-mail: david.legland@inrae.fr
% INRAE - BIA Research Unit - BIBS Platform (Nantes)
% Created: 2021-09-17,    using Matlab 9.9.0.1570001 (R2020b) Update 4
% Copyright 2021 INRAE.

%   HISTORY
%   17/08/2004 create as independant function, and merge 2D and 3D cases
%   17/09/2021 rename as imMergeEnclosedRegions

%% Parse input arguments

% create default structuring element
se = zeros([3 3 3]);
se(1,2,2) = 1;
se(3,2,2) = 1;
se(2,:,:) = [0 1 0;1 1 1;0 1 0];

verbose = true;
while length(varargin) > 1
    name = varargin{1};
    if strcmp(name, 'verbose')
        verbose = varargin{2};
    else
        error('Can not interpret input option: %s', name);
    end
    varargin(1:2) = [];
end

%% Initialisations

% init
res = lbl;

% compute adjacency graph
% (use a wrong node list, because of memory problems, but dont really need
% it)
if verbose
    disp('compute adjacency graph');
end
lastLabel = double(max(lbl(:)));
nodes = [(1:lastLabel)';(1:lastLabel)'];
edges = imRAG(lbl);

% compute volume of each cell
if verbose
    disp('compute area');
end
area = zeros(lastLabel, 1);
for i = 1:lastLabel
    area(i) = sum(lbl(:)==i);
end

% init fusion information
fusion = [];

for i = 1:lastLabel
    if verbose
        disp(sprintf('cell: %d/%d', i, lastLabel)); %#ok<DSPS>
    end

    % check:
    %   1 - cell still exist
    %   2 - cell is large enough (as some problem can occur in convexImage)
    if area(i) < 10
        continue;
    end

    % compute convex image of current cell
    im = imConvexImage(lbl==i);

    % find neighbours
    neigh = unique(edges(edges(:,1)==i | edges(:,2)==i, 1:2));
    neigh = neigh(neigh~=i);

    mergeFlag = false;
    for i2 = 1:length(neigh)
        % compute area
        common = sum(im(:)&res(:) == neigh(i2));
        if common / area(neigh(i2)) > .7
            disp(sprintf('fusion of regions %d and %d', i, neigh(i2))); %#ok<DSPS>

            % update RAG and fusion process information
            [nodes, edges] = grMergeNodes(nodes, edges, [i neigh(i2)]);
            fusion(size(fusion, 1)+1, 1:2) = [i neigh(i2)]; %#ok<AGROW>

            % update result image
            res(res==neigh(i2)) = i;
            mergeFlag = true;
        end
    end

    % fill in the space between merged regions
    if mergeFlag
        res(imerode(imclose(res==i, se), se)) = i;
    end
end

function [nodes, edges] = grMergeNodes(nodes, edges, mnodes)
% Merge two (or more) nodes in a graph.
%
% Usage:
%   [NODES2 EDGES2] = grMergeNodes(NODES, EDGES, NODE_INDS)
%   NODES and EDGES are wo arrays representing a graph, and NODE_INDS is
%   the set of indices of the nodes to merge.
%   The nodes corresponding to indices in NODE_INDS are removed from the
%   list, and edges between two nodes are removed.
%
%   Example: merging of labels 1 and 2
%   Edges:         Edges2:
%   [1 2]           [1 3]
%   [1 3]           [1 4]
%   [1 4]           [3 4]
%   [2 3]
%   [3 4]
%

refNode = mnodes(1);
mnodes = mnodes(2:length(mnodes));

% replace merged nodes references by references to refNode
edges(ismember(edges, mnodes))=refNode;

% remove "loop edges" from and to reference node
edges = edges(edges(:,1) ~= refNode | edges(:,2) ~= refNode, :);

% format output
edges = sortrows(unique(sort(edges, 2), 'rows'));

author: mattools

repo: matImage

save_path: github-repos/MATLAB/mattools-matImage


text:
function [B, L, N, A] = imBoundaryContours(bin, varargin)
%IMBOUNDARYCONTOURS Extract polygonal contours of a binary image.
%
%   CNTS = imBoundaryContours(BIN)
%   Computes a set of contours corresponding to the structures in binary
%   image BIN. The result CNTS is a cell array of polygons, each polygon
%   being a N-by-2 array containing the vertex coordinates.
%
%   This function is mainly a wrapper to the 'bwboundaries' function, that
%   returns the resulting set of contours in a different format.
%
%
%   Example
%     % draw the polygon corresponding to a single region
%     img = imread('circles.png');
%     polys = imContours(img);
%     figure; imshow(img); hold on;
%     drawPolygon(polys, 'r')
%
%   See also
%     bwboundaries, imcontour, imOtsuThreshold, imContourLines
%     contourMatrixToPolylines (MatGeom toolbox)
%

% ------
% Author: David Legland
% e-mail: david.legland@inrae.fr
% Created: 2012-07-27,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2012 INRA - Cepia Software Platform.

% check input image is binary
if ~isempty(varargin)
    error('Requires input image to be binary.');
end

% call the native bwboundaries function
[B, L, N, A] = bwboundaries(bin);

% object boundaries
for i = 1:N
    bnd = B{i};
    B{i} = bnd(:, [2 1]);
end

% hole boundaries
for i = N+1:length(B)
    bnd = B{i};
    B{i} = bnd([1 end:-1:2], [2 1]);
end


text:
%kMSD 'calculates mean square displacement '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros MSD.pane file
%
% Parameters:
% InputFile: i1 'Vector input (time along Z)', required: 'First Input data object'
% OutputFile: msd 'MSD', required: 'MSD for each vector series'
% OutputFile: events 'Events', required: 'The valid number of events (i >0)'
% OutputFile: allmsd 'All MSD', required: 'Mean square deviation of all valid positions'
%
% Example: [msd, events, allmsd] = kMSD(i1, {'i1','';'msd','';'events','';'allmsd',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% MSD - calculates mean square displacement
%
%  DESCRIPTION
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1996-2003, Rainer Heintzmann,  All rights reserved.
%

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

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

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function camBV2Scheme(bval_filename,bvec_filename,scheme_filename)
%Converts mrVIsta b-values and vectors to the camino scheme format
%
%   camBV2Scheme(bval_filename,bvec_filename,scheme_filename)
%
%
% (c) Stanford Vista, Sherbondy, 2010

bvec_opt = [' -bvecfile ' bvec_filename];
bval_opt = [' -bvalfile ' bval_filename];

% First, guess at what units the bvals are in as camino expects kg,s,m
% units or specifically s/m^2 and we often get them in two other standard
% forms, e.g., b=800 (s/mm^2) or b = 0.8 (ms/micron^2)
b = dlmread(bval_filename);
if any(b>100)
    bscale = '1E6';
else
    bscale = '1E9';
end

xform_opt = [' -bscale ' bscale ' -flipz -flipy -flipx '];

% Has to be scheme2 format so lets strip any provided extension
[pathstr, name, ext] = fileparts(scheme_filename);
scheme_filename = fullfile(pathstr,[name '.scheme2']);
scheme_opt = [' > ' scheme_filename];

cmd = ['fsl2scheme' bvec_opt bval_opt xform_opt  scheme_opt];

display(cmd);
system(cmd,'-echo');

return


text:
function y = pochhammer(x,n)
% pochhammer(x,n) returns the rising log-factorial log(gamma(x+n)/gamma(x))
% Named after the corresponding Mathematica function.
%
% pochhammer.c provides a faster implementation.

if 0 && length(x) == 1 && all(n < 100)
  nmax = full(max(max(n)));
  t(1) = 0;
  y = 0;
  for i = 1:nmax
    y = y + log(x);
    t(i+1) = y;
    x = x + 1;
  end
  y = t(n+1);
  % workaround matlab's silly rules for matrix indexing
  if cols(n) == 1 & rows(y) == 1
    y = y';
  end
  return
end
if issparse(n)
  y = sparse(rows(n),cols(n));
else
  y = zeros(size(n));
end
i = (n > 0);
if length(x) == 1
  y(i) = gammaln(x+n(i)) - gammaln(x);
else
  y(i) = gammaln(x(i)+n(i)) - gammaln(x(i));
end

author: FuzhenZhuang

repo: Transfer-Learning-Toolkit


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

% Last Modified by GUIDE v2.5 08-Feb-2004 17:48:07

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @test1_export_OpeningFcn, ...
                   'gui_OutputFcn',  @test1_export_OutputFcn, ...
                   'gui_LayoutFcn',  @test1_export_LayoutFcn, ...
                   'gui_Callback',   []);
if nargin
   if isstr(varargin{1})
       gui_State.gui_Callback = str2func(varargin{1});
   elseif varargin{1}==gcbo
       gui_State.gui_Callback = str2func([varargin{1}.Tag, '_', varargin{end}]);
   end
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 test1_export is made visible.
function test1_export_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 test1_export (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

if strcmp(get(hObject,'Visible'),'off')
    initialize_gui(hObject, handles);
end

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

% --- Outputs from this function are returned to the command line.
function varargout = test1_export_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 during object creation, after setting all properties.
function density_CreateFcn(hObject, eventdata, handles)
% hObject    handle to density (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background, change
%       'usewhitebg' to 0 to use default.  See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% Hints: get(hObject,'String') returns contents of density as text
%        str2double(get(hObject,'String')) returns contents of density as a double
density = str2double(get(hObject, 'String'));
if isnan(density)
    set(hObject, 'String', 0);
    errordlg('Input must be a number','Error');
end

handles.metricdata.density = density;
guidata(hObject,handles)

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

% Hint: edit controls usually have a white background, change
%       'usewhitebg' to 0 to use default.  See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

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

% Hints: get(hObject,'String') returns contents of volume as text
%        str2double(get(hObject,'String')) returns contents of volume as a double
volume = str2double(get(hObject, 'String'));
if isnan(volume)
    set(hObject, 'String', 0);
    errordlg('Input must be a number','Error');
end

handles.metricdata.volume = volume;
guidata(hObject,handles)

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

% Hint: edit controls usually have a white background, change
%       'usewhitebg' to 0 to use default.  See ISPC and COMPUTER.

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

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

% --- Executes on button press in english.
function english_Callback(hObject, eventdata, handles)
% hObject    handle to english (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 english

set(handles.english, 'Value', 1);
set(handles.si, 'Value', 0);

set(handles.text4, 'String', 'lb/cu.in');
set(handles.text5, 'String', 'cu.in');
set(handles.text6, 'String', 'lb');

% --- Executes on button press in si.
function si_Callback(hObject, eventdata, handles)
% hObject    handle to si (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 si

set(handles.english, 'Value', 0);
set(handles.si, 'Value', 1);

set(handles.text4, 'String', 'kg/cu.m');
set(handles.text5, 'String', 'cu.m');
set(handles.text6, 'String', 'kg');

% --- 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)

mass = handles.metricdata.density * handles.metricdata.volume;
set(handles.mass, 'String', mass);

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

initialize_gui(gcbf, handles);

function initialize_gui(fig_handle, handles)
handles.metricdata.density = 0;
handles.metricdata.volume  = 0;

set(handles.density, 'String', handles.metricdata.density);
set(handles.volume,  'String', handles.metricdata.volume);
set(handles.mass, 'String', 0);

set(handles.english, 'Value', 1);
set(handles.si,      'Value', 0);

set(handles.text4, 'String', 'lb/cu.in');
set(handles.text5, 'String', 'cu.in');
set(handles.text6, 'String', 'lb');

% Update handles structure
guidata(handles.figure1, handles);

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

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

% --- Creates and returns a handle to the GUI figure.
function h1 = test1_export_LayoutFcn(policy)
% policy - create a new figure or use a singleton. 'new' or 'reuse'.

persistent hsingleton;
if strcmpi(policy, 'reuse') & ishandle(hsingleton)
    h1 = hsingleton;
    return;
end

appdata = [];
appdata.GUIDEOptions = struct(...
    'active_h', [], ...
    'taginfo', struct(...
    'figure', 2, ...
    'pushbutton', 9, ...
    'text', 15, ...
    'edit', 6, ...
    'frame', 4, ...
    'radiobutton', [], ...
    'axes', []), ...
    'override', 0, ...
    'release', 13, ...
    'resize', 'on', ...
    'accessibility', 'callback', ...
    'mfile', 1, ...
    'callbacks', 1, ...
    'singleton', 1, ...
    'syscolorfig', 1, ...
    'blocking', 0, ...
    'lastSavedFile', 'D:\book\matlab\3e\rev1\chap9\test1.m');
appdata.UsedByGUIData_m = struct(...
    'figure1', [], ...
    'text1', [], ...
    'pushbutton1', 102.001098632813, ...
    'output', []);
appdata.lastValidTag = 'figure1';

h1 = figure(...
'PaperUnits',get(0,'defaultfigurePaperUnits'),...
'Color',[0.831372549019608 0.815686274509804 0.784313725490196],...
'Colormap',[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 1;0.125 1 0.9375;0.1875 1 0.875;0.25 1 0.8125;0.3125 1 0.75;0.375 1 0.6875;0.4375 1 0.625;0.5 1 0.5625;0.5625 1 0.5;0.625 1 0.4375;0.6875 1 0.375;0.75 1 0.3125;0.8125 1 0.25;0.875 1 0.1875;0.9375 1 0.125;1 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0],...
'Dockable','on',...
'IntegerHandle','off',...
'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...
'MenuBar','none',...
'Name','test1',...
'NumberTitle','off',...
'PaperPosition',get(0,'defaultfigurePaperPosition'),...
'PaperSize',[20.98404194812 29.67743169791],...
'PaperType',get(0,'defaultfigurePaperType'),...
'Position',[544 488 361 121],...
'Renderer',get(0,'defaultfigureRenderer'),...
'RendererMode','manual',...
'Resize','on',...
'CreateFcn', {@local_CreateFcn, 'test1_export(''figure1_CreateFcn'',gcbo,[],guidata(gcbo))', appdata} ,...
'HandleVisibility','callback',...
'Tag','figure1',...
'UserData',[],...
'Behavior',get(0,'defaultfigureBehavior'),...
'Visible','off');

appdata = [];
appdata.lastValidTag = 'frame3';

h2 = uicontrol(...
'Parent',h1,...
'CData',[],...
'ListboxTop',0,...
'Position',[222 41 132 71],...
'String',{  '' },...
'Style','frame',...
'Tag','frame3',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'frame2';

h3 = uicontrol(...
'Parent',h1,...
'ListboxTop',0,...
'Position',[10 10 202 102],...
'String',{  '' },...
'Style','frame',...
'CreateFcn', {@local_CreateFcn, 'test1_export(''frame2_CreateFcn'',gcbo,[],guidata(gcbo))', appdata} ,...
'Tag','frame2',...
'Behavior',get(0,'defaultuicontrolBehavior'));

appdata = [];
appdata.lastValidTag = 'text1';

h4 = uicontrol(...
'Parent',h1,...
'CData',[],...
'HorizontalAlignment','right',...
'ListboxTop',0,...
'Position',[17 82 60 15],...
'String','Density(D):',...
'Style','text',...
'Tag','text1',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'text2';

h5 = uicontrol(...
'Parent',h1,...
'CData',[],...
'HorizontalAlignment','right',...
'ListboxTop',0,...
'Position',[17 51 60 15],...
'String','Volume(V):',...
'Style','text',...
'Tag','text2',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'density';

h6 = uicontrol(...
'Parent',h1,...
'BackgroundColor',[1 1 1],...
'Callback','test1_export(''density_Callback'',gcbo,[],guidata(gcbo))',...
'HorizontalAlignment','right',...
'ListboxTop',0,...
'Position',[85 80 70 21],...
'String','0',...
'Style','edit',...
'CreateFcn', {@local_CreateFcn, 'test1_export(''density_CreateFcn'',gcbo,[],guidata(gcbo))', appdata} ,...
'Tag','density',...
'Behavior',get(0,'defaultuicontrolBehavior'));

appdata = [];
appdata.lastValidTag = 'volume';

h7 = uicontrol(...
'Parent',h1,...
'BackgroundColor',[1 1 1],...
'Callback','test1_export(''volume_Callback'',gcbo,[],guidata(gcbo))',...
'HorizontalAlignment','right',...
'ListboxTop',0,...
'Position',[85 49 70 21],...
'String','0',...
'Style','edit',...
'CreateFcn', {@local_CreateFcn, 'test1_export(''volume_CreateFcn'',gcbo,[],guidata(gcbo))', appdata} ,...
'Tag','volume',...
'Behavior',get(0,'defaultuicontrolBehavior'));

appdata = [];
appdata.lastValidTag = 'english';

h8 = uicontrol(...
'Parent',h1,...
'Callback','test1_export(''english_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[232 83 115 15],...
'String','English Unit System',...
'Style','radiobutton',...
'Value',1,...
'Tag','english',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'si';

h9 = uicontrol(...
'Parent',h1,...
'Callback','test1_export(''si_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[232 52 115 15],...
'String','S.I. Unit System',...
'Style','radiobutton',...
'Tag','si',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'mass';

h10 = uicontrol(...
'Parent',h1,...
'Callback','guidetemplate1(''mass_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...
'Enable','inactive',...
'HorizontalAlignment','right',...
'ListboxTop',0,...
'Position',[85 16 66 15],...
'String','0',...
'Style','text',...
'CreateFcn', {@local_CreateFcn, 'test1_export(''mass_CreateFcn'',gcbo,[],guidata(gcbo))', appdata} ,...
'Tag','mass',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'));

appdata = [];
appdata.lastValidTag = 'text3';

h11 = uicontrol(...
'Parent',h1,...
'CData',[],...
'HorizontalAlignment','right',...
'ListboxTop',0,...
'Position',[17 16 60 15],...
'String','Mass(D*V):',...
'Style','text',...
'Tag','text3',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'pushbutton1';

h12 = uicontrol(...
'Parent',h1,...
'Units','characters',...
'Callback','test1_export(''pushbutton1_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...
'ListboxTop',0,...
'Position',[41.5 -0.0625 10.1666666666667 1.3125],...
'String','Calculate',...
'Tag','pushbutton1',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'pushbutton2';

h13 = uicontrol(...
'Parent',h1,...
'Callback','test1_export(''pushbutton2_Callback'',gcbo,[],guidata(gcbo))',...
'CData',[],...
'ListboxTop',0,...
'Position',[300 20 61 21],...
'String','Reset',...
'Tag','pushbutton2',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'text6';

h14 = uicontrol(...
'Parent',h1,...
'CData',[],...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[165 16 35 15],...
'String','lb',...
'Style','text',...
'Tag','text6',...
'UserData',[],...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'text4';

h15 = uicontrol(...
'Parent',h1,...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[165 82 40 15],...
'String','lb/cu.in',...
'Style','text',...
'Tag','text4',...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'text5';

h16 = uicontrol(...
'Parent',h1,...
'HorizontalAlignment','left',...
'ListboxTop',0,...
'Position',[165 51 35 15],...
'String','cu.in',...
'Style','text',...
'Tag','text5',...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'text13';

h17 = uicontrol(...
'Parent',h1,...
'ListboxTop',0,...
'Position',[18 104 54 15],...
'String','Measures',...
'Style','text',...
'Tag','text13',...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'text14';

h18 = uicontrol(...
'Parent',h1,...
'ListboxTop',0,...
'Position',[230 104 30 15],...
'String','Units',...
'Style','text',...
'Tag','text14',...
'Behavior',get(0,'defaultuicontrolBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

appdata = [];
appdata.lastValidTag = 'axes1';

h19 = axes(...
'Parent',h1,...
'Units','characters',...
'Position',[28.5 -0.0625 8.33333333333333 3.125],...
'CameraPosition',[0.5 0.5 9.16025403784439],...
'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),...
'Color',get(0,'defaultaxesColor'),...
'ColorOrder',get(0,'defaultaxesColorOrder'),...
'LooseInset',[7.82166666666667 0.831875 5.71583333333333 0.5671875],...
'XColor',get(0,'defaultaxesXColor'),...
'YColor',get(0,'defaultaxesYColor'),...
'ZColor',get(0,'defaultaxesZColor'),...
'Tag','axes1',...
'Behavior',get(0,'defaultaxesBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

h20 = get(h19,'title');

set(h20,...
'Parent',h19,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.490000000000001 1.15 1.00005459937205],...
'VerticalAlignment','bottom',...
'HandleVisibility','off',...
'Behavior',struct());

h21 = get(h19,'xlabel');

set(h21,...
'Parent',h19,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.490000000000001 -0.53 1.00005459937205],...
'VerticalAlignment','cap',...
'HandleVisibility','off',...
'Behavior',struct());

h22 = get(h19,'ylabel');

set(h22,...
'Parent',h19,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[-0.69 0.47 1.00005459937205],...
'Rotation',90,...
'VerticalAlignment','bottom',...
'HandleVisibility','off',...
'Behavior',struct());

h23 = get(h19,'zlabel');

set(h23,...
'Parent',h19,...
'Color',[0 0 0],...
'HorizontalAlignment','right',...
'Position',[-3.43 2.41 1.00005459937205],...
'HandleVisibility','off',...
'Behavior',struct(),...
'Visible','off');

appdata = [];
appdata.lastValidTag = 'axes2';

h24 = axes(...
'Parent',h1,...
'Units','characters',...
'Position',[33.1666666666667 -0.0625 8.33333333333333 3.125],...
'CameraPosition',[0.5 0.5 9.16025403784439],...
'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),...
'Color',get(0,'defaultaxesColor'),...
'ColorOrder',get(0,'defaultaxesColorOrder'),...
'LooseInset',[7.82166666666667 0.831875 5.71583333333333 0.5671875],...
'XColor',get(0,'defaultaxesXColor'),...
'YColor',get(0,'defaultaxesYColor'),...
'ZColor',get(0,'defaultaxesZColor'),...
'Tag','axes2',...
'Behavior',get(0,'defaultaxesBehavior'),...
'CreateFcn', {@local_CreateFcn, '', appdata} );

h25 = get(h24,'title');

set(h25,...
'Parent',h24,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.49 1.15 1.00005459937205],...
'VerticalAlignment','bottom',...
'HandleVisibility','off',...
'Behavior',struct());

h26 = get(h24,'xlabel');

set(h26,...
'Parent',h24,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[0.49 -0.53 1.00005459937205],...
'VerticalAlignment','cap',...
'HandleVisibility','off',...
'Behavior',struct());

h27 = get(h24,'ylabel');

set(h27,...
'Parent',h24,...
'Color',[0 0 0],...
'HorizontalAlignment','center',...
'Position',[-0.69 0.47 1.00005459937205],...
'Rotation',90,...
'VerticalAlignment','bottom',...
'HandleVisibility','off',...
'Behavior',struct());

h28 = get(h24,'zlabel');

set(h28,...
'Parent',h24,...
'Color',[0 0 0],...
'HorizontalAlignment','right',...
'Position',[-3.99 2.41 1.00005459937205],...
'HandleVisibility','off',...
'Behavior',struct(),...
'Visible','off');

hsingleton = h1;

% --- Set application data first then calling the CreateFcn.
function local_CreateFcn(hObject, eventdata, createfcn, appdata)

if ~isempty(appdata)
   names = fieldnames(appdata);
   for i=1:length(names)
       name = char(names(i));
       setappdata(hObject, name, getfield(appdata,name));
   end
end

if ~isempty(createfcn)
   eval(createfcn);
end

% --- Handles default GUIDE GUI creation and callback dispatch
function varargout = gui_mainfcn(gui_State, varargin)

%   GUI_MAINFCN provides these command line APIs for dealing with GUIs
%
%      TEST1_EXPORT, by itself, creates a new TEST1_EXPORT or raises the existing
%      singleton*.
%
%      H = TEST1_EXPORT returns the handle to a new TEST1_EXPORT or the handle to
%      the existing singleton*.
%
%      TEST1_EXPORT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in TEST1_EXPORT.M with the given input arguments.
%
%      TEST1_EXPORT('Property','Value',...) creates a new TEST1_EXPORT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before untitled_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to untitled_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".

%   Copyright 1984-2002 The MathWorks, Inc.
%   $Revision: 1.4.6.5 $ $Date: 2003/08/11 16:07:29 $

gui_StateFields =  {'gui_Name'
                    'gui_Singleton'
                    'gui_OpeningFcn'
                    'gui_OutputFcn'
                    'gui_LayoutFcn'
                    'gui_Callback'};
gui_Mfile = '';
for i=1:length(gui_StateFields)
    if ~isfield(gui_State, gui_StateFields{i})
        error('Could not find field %s in the gui_State struct in GUI M-file %s', gui_StateFields{i}, gui_Mfile);
    elseif isequal(gui_StateFields{i}, 'gui_Name')
        gui_Mfile = [getfield(gui_State, gui_StateFields{i}), '.m'];
    end
end

numargin = length(varargin);

if numargin == 0
    % TEST1_EXPORT
    % create the GUI
    gui_Create = 1;
elseif ishandle(varargin{1}) & varargin{1}==gcbo
    % TEST1_EXPORT(ACTIVEX,...)
    vin{1} = gui_State.gui_Name;
    vin{2} = [get(varargin{1}.Peer, 'Tag'), '_', varargin{end}];
    vin{3} = varargin{1};
    vin{4} = varargin{end-1};
    vin{5} = guidata(varargin{1}.Peer);
    feval(vin{:});
    return;
elseif ischar(varargin{1}) & ishandle(varargin{2})
    % TEST1_EXPORT('CALLBACK',hObject,eventData,handles,...)
    gui_Create = 0;
else
    % TEST1_EXPORT(...)
    % create the GUI and hand varargin to the openingfcn
    gui_Create = 1;
end

if gui_Create == 0
    varargin{1} = gui_State.gui_Callback;
    if nargout
        [varargout{1:nargout}] = feval(varargin{:});
    else
        feval(varargin{:});
    end
else
    if gui_State.gui_Singleton
        gui_SingletonOpt = 'reuse';
    else
        gui_SingletonOpt = 'new';
    end

    % Open fig file with stored settings.  Note: This executes all component
    % specific CreateFunctions with an empty HANDLES structure.

    % Do feval on layout code in m-file if it exists
    if ~isempty(gui_State.gui_LayoutFcn)
        gui_hFigure = feval(gui_State.gui_LayoutFcn, gui_SingletonOpt);
        % openfig (called by local_openfig below) does this for guis without
        % the LayoutFcn. Be sure to do it here so guis show up on screen.
        movegui(gui_hFigure,'onscreen')
    else
        gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt);
        % If the figure has InGUIInitialization it was not completely created
        % on the last pass.  Delete this handle and try again.
        if isappdata(gui_hFigure, 'InGUIInitialization')
            delete(gui_hFigure);
            gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt);
        end
    end

    % Set flag to indicate starting GUI initialization
    setappdata(gui_hFigure,'InGUIInitialization',1);

    % Fetch GUIDE Application options
    gui_Options = getappdata(gui_hFigure,'GUIDEOptions');

    if ~isappdata(gui_hFigure,'GUIOnScreen')
        % Adjust background color
        if gui_Options.syscolorfig
            set(gui_hFigure,'Color', get(0,'DefaultUicontrolBackgroundColor'));
        end

        % Generate HANDLES structure and store with GUIDATA
        guidata(gui_hFigure, guihandles(gui_hFigure));
    end

    % If user specified 'Visible','off' in p/v pairs, don't make the figure
    % visible.
    gui_MakeVisible = 1;
    for ind=1:2:length(varargin)
        if length(varargin) == ind
            break;
        end
        len1 = min(length('visible'),length(varargin{ind}));
        len2 = min(length('off'),length(varargin{ind+1}));
        if ischar(varargin{ind}) & ischar(varargin{ind+1}) & ...
                strncmpi(varargin{ind},'visible',len1) & len2 > 1
            if strncmpi(varargin{ind+1},'off',len2)
                gui_MakeVisible = 0;
            elseif strncmpi(varargin{ind+1},'on',len2)
                gui_MakeVisible = 1;
            end
        end
    end

    % Check for figure param value pairs
    for index=1:2:length(varargin)
        if length(varargin) == index
            break;
        end
        try, set(gui_hFigure, varargin{index}, varargin{index+1}), catch, break, end
    end

    % If handle visibility is set to 'callback', turn it on until finished
    % with OpeningFcn
    gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
    if strcmp(gui_HandleVisibility, 'callback')
        set(gui_hFigure,'HandleVisibility', 'on');
    end

    feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});

    if ishandle(gui_hFigure)
        % Update handle visibility
        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);

        % Make figure visible
        if gui_MakeVisible
            set(gui_hFigure, 'Visible', 'on')
            if gui_Options.singleton
                setappdata(gui_hFigure,'GUIOnScreen', 1);
            end
        end

        % Done with GUI initialization
        rmappdata(gui_hFigure,'InGUIInitialization');
    end

    % If handle visibility is set to 'callback', turn it on until finished with
    % OutputFcn
    if ishandle(gui_hFigure)
        gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
        if strcmp(gui_HandleVisibility, 'callback')
            set(gui_hFigure,'HandleVisibility', 'on');
        end
        gui_Handles = guidata(gui_hFigure);
    else
        gui_Handles = [];
    end

    if nargout
        [varargout{1:nargout}] = feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
    else
        feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
    end

    if ishandle(gui_hFigure)
        set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);
    end
end

function gui_hFigure = local_openfig(name, singleton)

% openfig with three arguments was new from R13. Try to call that first, if
% failed, try the old openfig.
try
    gui_hFigure = openfig(name, singleton, 'auto');
catch
    % OPENFIG did not accept 3rd input argument until R13,
    % toggle default figure visible to prevent the figure
    % from showing up too soon.
    gui_OldDefaultVisible = get(0,'defaultFigureVisible');
    set(0,'defaultFigureVisible','off');
    gui_hFigure = openfig(name, singleton);
    set(0,'defaultFigureVisible',gui_OldDefaultVisible);
end


text:
function SaveXMLParams(topNode,filename,name)

if nargin < 3,
  name = 'params';
end

docNode = com.mathworks.xml.XMLUtils.createDocument(name);
toc = docNode.getDocumentElement;
att = fieldnames(topNode);
for ndx = 1:numel(att)
  toc.appendChild(createXMLNode(docNode,att{ndx},topNode.(att{ndx})));
end
xmlwrite(filename,docNode);

author: kristinbranson

repo: JAABA


text:
function y = callback_dct_wavelets(x, dir, options)

% callback_dct_wavelets - callback for union of DCT and Wavelets dictionary
%
%   y = callback_dct_wavelets(x, dir, options);
%
%   Copyright (c) 2008 Gabriel Peyre

options.remove_lowfreq = 0;
if not(isfield(options, 'dct_type'))
    options.dct_type = 'redundant';
end
if dir==+1
    y = callback_localdct(x{1}, dir, options) + callback_atrou({x{2:end}}, dir, options);
%    y = y/2;
elseif dir==-1
    yd = callback_localdct(x,dir,options);
    yw = callback_atrou(x,dir,options);
    y = { yd, yw{:}};
else
    error('Pseudo inverse not implemented');
end

author: gpeyre

repo: matlab-toolboxes


text:
function [Rob,Sen,Raw,Lmk,Obs,Tim] = createSlamStructures(Robot,Sensor,Time,Opt)

% CREATESLAMSTRUCTURES  Initialize SLAM data structures from user data.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

global Map

% Create robots and controls
Rob = createRobots(Robot);

% Create sensors
[Sen,Raw] = createSensors(Sensor);

% Install sensors in robots
[Rob,Sen] = installSensors(Rob,Sen);

% Create Landmarks and non-observables
Lmk = createLandmarks(Opt);

% Create Map - empty
Map = createMap(Rob,Sen,Opt);

% Initialize robots and sensors in Map
Rob = initRobots(Rob);
Sen = initSensors(Sen);

% Create Observations (matrix: [ line=sensor , colums=landmark ])
Obs = createObservations(Sen,Opt);

% Create time variables
Tim = createTime(Time);

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

%   # START GPL LICENSE

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

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

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
function [ y, next ] = p26_equil ( neqn, next )

%*****************************************************************************80
%
%% P26_EQUIL returns equilibrium solutions of problem p26.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Input, integer NEXT, the index of the previous
%    equilibrium, which should be 0 on first call.
%
%    Output, real Y(NEQN), the "next" equilibrium solution, if any.
%
%    Output, integer NEXT, the index of the current equilibrium,
%    or 0 if there are no more.
%
  if ( next == 0 )
    next = 1;
    y(1:neqn,1) = 0.0;
  else
    next = 0;
    y = [];
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
cd lib/mex_files;
make_linux
cd ../..
addpath ./demo
addpath ./lib/m_files
addpath ./lib/mex_files

repo: Aero-matlab


text:
function hypercube_monte_carlo_test ( )

%*****************************************************************************80
%
%% HYPERCUBE_MONTE_CARLO_TEST tests the HYPERCUBE_MONTE_CARLO library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 January 2014
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'HYPERCUBE_MONTE_CARLO_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the HYPERCUBE_MONTE_CARLO library.\n' );

  hypercube_monte_carlo_test01 ( );
  hypercube_monte_carlo_test02 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'HYPERCUBE_MONTE_CARLO_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


text:
function varargout = mldivide(varargin)
%\   Left divide for DISKFUN objects.
%   MLDIVIDE(F, G) computes left dividison for DISKFUN objects F and G.
%   Only allowed to divide by scalars.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

[varargout{1:nargout}] = mldivide@separableApprox(varargin{:});

end

author: chebfun

repo: chebfun


text:
function [R] = Euler2RotMat(eul)
% [R] = Euler2RotMat(theta_x, theta_y, theta_z)
%
% Stand-in for eul2rotm (built-in function MATLAB Robotics System Toolbox)
% Converts Euler angles [rad] to 3x3 Rotation Matrix
%
% This implementation based on:
% S.M.LaValle, Planning Algorithms, Cambridge University Press, 2006, p.98
% (PDF available here: http://planning.cs.uiuc.edu/ch3.pdf)
% as cited in: http://nghiaho.com/?page_id=846
%
% Inputs:
%   eul = [n x 3] - Euler Rotation Angles
%
% Outputs:
%   R = [3 x 3 x n] - rotation matrix.
%
% Written by Conrad McGreal @ 2019
R = zeros(3,3,size(eul,1)) ;

for i=1:size(eul,1)
    theta_x = eul(i,1) ;
    theta_y = eul(i,2) ;
    theta_z = eul(i,3) ;

    X = [1 0 0
        0 cos(theta_x) -sin(theta_x)
        0 sin(theta_x) cos(theta_x)];

    Y = [cos(theta_y) 0 sin(theta_y)
        0 1 0
        -sin(theta_y) 0 cos(theta_y)];

    Z = [cos(theta_z) -sin(theta_z) 0
        sin(theta_z) cos(theta_z) 0
        0 0 1];

    R(:,:,i) = Z*Y*X;
end

author: MatthewPeterKelly

repo: OptimTraj


text: asCloseAll();

repo: MRiLab


text:
clear
savethis = 1;
ncomp = [4];
niter=1; %number of evaluation of each dataset

for ncompindex = 1:length(ncomp);
    for iterindex=1:niter
        ca;
        data_core = 'D3ptBMrand_N3_offset50_delta10';
        if savethis
            [peval.logfile, peval.fid] = initlogfile;
        end

        paramsVAR %reads the parameters
        datasource = [peval.home '/' peval.data_path '/' peval.data_dir '/' peval.data_file];

        readdata

        % Estimating / subtracting background:
        %         [dpixc, peval]=backgroundestimation(dpixc, peval, p.offset);

        peval.bg=p.offset;
        %         dpixc=bgsubtractbyhand(dpixc,peval);
        peval.ncomp=ncomp(ncompindex);

        % Initialization of W:
        %             winit = init_wmap('rand',peval,double(array2im(dpixc_ind)));
        winit = init_w_general(peval.init_w_method,peval,[p.x_vec, p.y_vec]);
        hinit = init_h_general(peval.init_h_method,peval,[],dpixc);

        dvec=reshape(dpixc,peval.nx*peval.ny,peval.nt);

        % Main computation:
        [res, peval]=peval.fun(peval, dvec,winit, hinit);

        if savethis
            peval = createresname(peval,iterindex);
            saveresults(res, peval, p, [peval.res_path peval.res_dir '/' peval.res_name])
            fclose(peval.fid(2));
        end
    end
    if savethis
        % Saving parametes and logfile into the directory with resuls
        saveparameters(peval,p)
    end
end
% plottingmulti
% plotscattehvsblinkmat