text:
%script to reverse the entire network
s = size(original_img);
im_size = [s(1), s(2)];
contrib_cls_person_score = 1;

cls_ind = 3; %16 is person, 1 is background, 3 bike
[val, roi_ind] = max(squeeze(cls_prob(:,cls_ind)));
roi_ind = 73; % 1,9,13,14,19,26,60,102 for 0002.jpg % 83 person, 73 bike for out_0_7

fc7_roi = squeeze(fc7(roi_ind,:));
fc6_roi = squeeze(fc6(roi_ind,:));
pool_5_roi = squeeze(pool_5(roi_ind,:,:,:));
roi = rois(roi_ind,:);

disp('---start reversing the entire network')
contrib_fc7 = reverse_fc(fc7_roi,contrib_cls_person_score,cls_score_weights(:,cls_ind));
contrib_fc6 = reverse_fc(fc6_roi,contrib_fc7,fc7_weights);
contrib_roipool = reverse_fc(flat_reshape(pool_5_roi),contrib_fc6,fc6_weights);
contrib_roipool = reverse_flat_reshape(contrib_roipool, size(pool_5_roi));
disp('---completed contrib_roipool')

contrib_conv5_3 = reverse_roipool(conv5_3, pool_5_roi, contrib_roipool);
disp('---completed reverse roi_pool')

contrib_conv5_2 = reverse_conv(conv5_2, contrib_conv5_3, conv5_3_weights);
contrib_conv5_1 = reverse_conv(conv5_1, contrib_conv5_2, conv5_2_weights);
contrib_pool4 = reverse_conv(pool4, contrib_conv5_1, conv5_1_weights);
disp('---completed reverse conv5')

contrib_conv4_3 = reverse_max_vl(conv4_3, contrib_pool4);
contrib_conv4_2 = reverse_conv(conv4_2, contrib_conv4_3, conv4_3_weights);
contrib_conv4_1 = reverse_conv(conv4_1, contrib_conv4_2, conv4_2_weights);
contrib_pool3 = reverse_conv(pool3, contrib_conv4_1, conv4_1_weights);
disp('---completed reverse conv4')

contrib_conv3_3 = reverse_max_vl(conv3_3, contrib_pool3);
contrib_conv3_2 = reverse_conv(conv3_2, contrib_conv3_3, conv3_3_weights);
contrib_conv3_1 = reverse_conv(conv3_1, contrib_conv3_2, conv3_2_weights);
contrib_pool2 = reverse_conv(pool2, contrib_conv3_1, conv3_1_weights);
disp('---completed reverse conv3')

contrib_conv2_2 = reverse_max_vl(conv2_2, contrib_pool2);
contrib_conv2_1 = reverse_conv(conv2_1, contrib_conv2_2, conv2_2_weights);
contrib_pool1 = reverse_conv(pool1, contrib_conv2_1, conv2_1_weights);
disp('---completed reverse conv2')

contrib_conv1_2 = reverse_max_vl(conv1_2, contrib_pool1);
contrib_conv1_1 = reverse_conv(conv1_1, contrib_conv1_2, conv1_2_weights);
%contrib_img = reverse_conv_original_img(original_img, contrib_conv1_1, conv1_1_weights);
%disp('completed reverse conv1')

%disp('completed contrib of img')
disp('---all completed')

author: zhangqianqianQQ


text:
classdef Stop < simiam.controller.Controller

    properties
        p
    end

    properties (Constant)
        % I/O
        inputs = struct();
        outputs = struct('v', 0, 'w', 0);
    end

    methods

        function obj = Stop()
            obj = obj@simiam.controller.Controller('stop');
        end
    end

    methods

        function outputs = execute(obj, robot, state_estimate, inputs, dt)
            outputs = obj.outputs;
            outputs.v = 0;
            outputs.w = 0;
        end

    end

end

author: jdelacroix

repo: simiam

save_path: github-repos/MATLAB/jdelacroix-simiam


text:
function Reinforce(~, ~, game, player)

%% REPLACE BUTTONS
button1 = findobj('style', 'pushbutton', 'String', 'Reinforce');
button2 = findobj('style', 'pushbutton', 'String', 'Attack');
delete([button1, button2])

ConfirmBtn = ...
uicontrol('style', 'pushbutton', ...
          'Parent', game.figH, ...
          'Units', 'normalized', ...
          'Position', [0.46 0.87, 0.08, 0.03], ...
          'String', 'Confirm', ...
          'Callback', {@ConfirmReinforcements, game, player}); %5

N = numel(game.board);

%% CALCULATE NUMBER OF EXTRA TROOPS
list = zeros(1, N);
for i = 1:N
    occupant = get(game.board(i).Patch, 'UserData');
    list(i) = (occupant(1) == player);
end
n = floor(sum(list)/3);
if n < 3
    n = 3;
end

%% SET BUTTONDWNFCNS
for i = find(list)
    set(game.board(i).Patch, 'ButtonDownFcn', {@ClickToReinforce, game, player})
end

%% SHOW TEXT
str = sprintf('%s, you may add %d troops.', game.names{player}, n);
set(game.txtH, 'String', str, 'UserData', n);

uiwait(game.figH);  %5

%% CONFIRMED!
delete(ConfirmBtn)
uiresume(game.figH) %2

author: Sable

repo: mcbench-benchmarks


text:
function [p, ptt] = rndtest(X, Y, B)
% Randomized (permutation) paired sample test

% AUTORIGHTS
% -------------------------------------------------------
% Copyright (C) 2009-2012 Ross Girshick
%
% This file is part of the voc-releaseX code
% (http://people.cs.uchicago.edu/~rbg/latent/)
% and is available under the terms of an MIT-like license
% provided in COPYING. Please retain this notice and
% COPYING if you use this file (or a portion of it) in
% your project.
% -------------------------------------------------------

if nargin < 3
  B = 100000;
end

Z0 = X - Y;
t0 = mean(Z0);
T = length(Z0);

t = mean(repmat(Z0, [1 B]) .* ((rand(T,B) < 0.5) * 2 - 1));

p = 1/B * sum(abs(t0) <= abs(t));

% For comparison:
% p-value from matlab's parametric t-test function
[~, ptt] = ttest(X, Y);

author: rbgirshick

repo: voc-dpm

save_path: github-repos/MATLAB/rbgirshick-voc-dpm


text:
function d=winenvar(n)
%WINENVAR get windows environment variable [D]=(N)
%
% Inputs: N  name of environment variable (e.g. 'temp')
%
% Outputs: D  value of variable or [] is non-existant
%
% Notes: (1) This is WINDOWS specific and needs to be fixed to work on UNIX
%        (2) The search is case insensitive (like most of WINDOWS).
%
% Examples: (1) Open a temporary text file:
%               d=winenar('temp'); fid=fopen(fullfile(d,'temp.txt'),'wt');

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

author: jtkim-kaist

repo: VAD

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


text:
function [opt_vals, opt_ids] = ml_curve_opt(curve, method)
%ML_CURVE_OPT Returns optimal number of clusters from an RSS curve,
% where the optimum is at the "elbow" of the curve. This can be computed
% by two methods: 'derivatives' and 'line'.
%
%   input ----------------------------------------------------------------
%
%       o curve       : (1 x N), number of data points to generate.
%
%       o method      : 'string', method used to compute the 'elbow'
%
%   output ----------------------------------------------------------------
%
%       o opt_vals    : (1 x optimal_values), optimal RSS values.
%
%       o opt_ids     : (1 x optimal_values), optimal RSS index=K.
%

switch(method)
    % %%% Using derivatives
    case 'derivatives'
        % Compute first derivative
        d_curve = [0 diff(curve)];

        % Compute second derivative
        dd_curve = [0 diff(d_curve)];

        % Find maximum values
        [dd_vals, idx] = findpeaks(dd_curve);

        % Peak values
        [~, ids] = sort(dd_vals,'descend');

        % Return first 2 values with significant change
        opt_vals = dd_vals(ids(1:2)); % Maximum values of the second derivative
        opt_ids  = idx(ids(1:2));     % Indices of those maximum values

   % %%%% Using distance to line
    case 'line'

        %# get coordinates of all the points
        nPoints = length(curve);
        allCoord = [1:nPoints;curve]';              %'# SO formatting

        %# pull out first point
        firstPoint = allCoord(1,:);

        %# get vector between first and last point - this is the line
        lineVec = allCoord(end,:) - firstPoint;

        %# normalize the line vector
        lineVecN = lineVec / sqrt(sum(lineVec.^2));

        %# find the distance from each point to the line:
        %# vector between all points and first point
        vecFromFirst = bsxfun(@minus, allCoord, firstPoint);

        %# To calculate the distance to the line, we split vecFromFirst into two
        %# components, one that is parallel to the line and one that is perpendicular
        %# Then, we take the norm of the part that is perpendicular to the line and
        %# get the distance.
        %# We find the vector parallel to the line by projecting vecFromFirst onto
        %# the line. The perpendicular vector is vecFromFirst - vecFromFirstParallel
        %# We project vecFromFirst by taking the scalar product of the vector with
        %# the unit vector that points in the direction of the line (this gives us
        %# the length of the projection of vecFromFirst onto the line). If we
        %# multiply the scalar product by the unit vector, we have vecFromFirstParallel
        scalarProduct = dot(vecFromFirst, repmat(lineVecN,nPoints,1), 2);
        vecFromFirstParallel = scalarProduct * lineVecN;
        vecToLine = vecFromFirst - vecFromFirstParallel;

        %# distance to line is the norm of vecToLine
        distToLine = sqrt(sum(vecToLine.^2,2));

        %# find the maximum
        [opt_vals,opt_ids] = max(distToLine);

end

end

author: epfl-lasa


text:
function [ t_start, y_start ] = p25_start ( neqn )

%*****************************************************************************80
%
%% P25_START returns the starting point for problem p25.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NEQN, the number of equations.
%
%    Output, real T_START, Y_START(NEQN,1), the initial data.
%
  y_start = zeros ( neqn, 1 );

  t_start = 0.0;
  y_start = [ 0.0; 0.0 ];

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function in = scn_mat_conform(in)
% :Usage:
% ::
%
%     function in = scn_mat_conform(in)
%
% sets flipping to 0 (no flip) in SPM2 and adjusts mat file accordingly
% input in spm-style mat file or struct with .mat or .M fields
%
% ..
%    tor wager, dec 06
% ..

    global defaults

    if isstruct(in)
        if isfield(in,'mat')
            in.mat = scn_mat_conform(in.mat);
        end

        if isfield(in,'M')
            in.M = scn_mat_conform(in.M);
        end

        return
    end

    if in(1) < 0
        disp('Warning: Image has negative x voxel size, indicating ''flipped'' in SPM.')
        disp('This will be changed to positive. This program does not do any image flipping.')

        in(1) = abs(in(1));     % voxel size
        in(1,4) = -(in(1,4));   % origin offset
    end

    if isempty(defaults)
        spm_defaults
    end

    if defaults.analyze.flip
        disp('Warning: Setting defaults.analyze.flip to 0.  No flipping.')
        defaults.analyze.flip = 0;
    end

    return

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function [F0,Fz,Fx,Fxz] = getFzxfromSET(F,z,x)

F = sdpvar(F);
F0 = -getbasematrix(F,0);
zvars = getvariables(z);
xvars = getvariables(x);

for i = 1:length(xvars)
    Fx{i} = -getbasematrix(F,xvars(i));
end

for i = 1:length(zvars)
    Fz{i} = -getbasematrix(F,zvars(i));
end

for i = 1:length(xvars)
    for j = 1:length(zvars)
        Fxz{i,j} = -getbasematrix(F,getvariables(x(i)*z(j)));
    end
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function model = ivmOptimiseNoise(model, display, iters);

% IVMOPTIMISENOISE Optimise the noise parameters.
% FORMAT
% DESC optimises the noise parameters in the IVM model.
% ARG model : the model for which the noise parameters are to be
% optimised.
% ARG display : how much to display during optimisation (defaults
% to level 1).
% ARG iters : how many iterations of optimisation to use (defaults
% to 500).
%
% SEEALSO : optimiseParams, defaultOptions, ivmNegLogLikelihood, ivmNegGradientNoise
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005

% IVM

if nargin < 3
  iters = 500;
  if nargin < 2
    display = 1;
  end
end
options = defaultOptions;
if display
  options(1) = 1;
end
options(14) = iters;

model = optimiseParams('noise', 'scg', 'ivmNegLogLikelihood', ...
                       'ivmNegGradientNoise', options, model);

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function varargout = imGradient(img, varargin)
% Compute gradient magnitude of a grayscale image.
%
%   [GX, GY] = imGradient(IMG);
%   [GX, GY, GZ] = imGradient(IMG);
%   Compute the components of the gradient vector of a 2D or a 3D image.
%   The gradient is computed in each orthogonal direction by using
%   normalised Sobel filters.
%   For a 2D image, gradient magnitude and angle can be computed from:
%   GMAG = hypot(GX, GY);
%   GANGLE = atan2(GY, GX);
%
%   GRAD = imGradient(IMG);
%   Compute an image of gradient magnitude. Magnitude is computed as:
%   - hypot(dx, dy) for 2D images
%   - hypot(hypot(dx, dy), dz) for 3D images
%
%   GRAD = imGradient(IMG, SIGMA);
%   Specifies the width of the kernel (2D only). The size of the kernel is
%   determined automatically from the SIGMA.
%
%   GRAD = imGradient(IMG, 'filter', FILTER);
%   Specifies the filter used for computing gradient in the X direction.
%   Note that fspecial('sobel') or fspecial('prewitt') return unnormalized
%   filters for the Y direction (horizontal gradient).
%
%   ... = imGradient(..., OPTION1, OPTION2...);
%   Will use the given set of options when computing the gradient filter.
%   See the documentation of imfilter for details.
%   Default options are 'conv' and 'replicate'.
%
%   Example
%   % display edge strength computed on cameraman picture
%     img = imread('cameraman.tif');
%     grad = imGradient(img);
%     imshow(grad, [0 max(grad(:))]);  colormap parula;
%     % use larger parameter for sigma
%     grad5 = imGradient(img, 5);
%     figure; imshow(grad5, [0 max(grad5(:))]); colormap parula;
%
%   % compute edge direction on rice picture
%     img = imread('rice.png');
%     [dx, dy] = imGradient(img);
%     grad = hypot(dx, dy);
%     theta = atan2(dy, dx);
%     rgb = angle2rgb(theta);     % convert to floating-point rgb
%     bin = grad>20;              % select only salient edges
%     rgb(~bin(:,:, [1 1 1])) = 0;% display salient edges orientation
%     imshow(rgb);
%
%   % Uses a different filter (the same as for the "gradient" function)
%     img = imread('cameraman.tif');
%     grad = imGradient(img, 'filter', [1 0 -1]);
%     imshow(grad, [0 max(grad(:))]);
%
%   See also
%     imLaplacian, imMorphoGradient, imHessian
%     imfilter, fspecial, angle2rgb, gradient

% ------
% Author: David Legland
% e-mail: david.legland@inrae.fr
% Created: 2009-08-19,    using Matlab 7.7.0.471 (R2008b)
% Copyright 2009 INRA - Cepia Software Platform.

% HISTORY
% 2010-01-13 add support for gradient direction and filter options
% 2010-02-16 change output format for 2 output parameters, add support
%   for 3D images, and add psb to change filter.
% 2010-03-03 use convolution by default
% 2010-03-05 return result as double, normalize default filter
% 2010-12-06 use 3D kernel by default for 3D images
% 2013-05-20 add support for variable kernel width (2D only)

%% Parse input arguments

% image dimension
dim = size(img);

% number of dimension of image (do not manage color images)
nd = length(dim);

% check if the width of the kernel is specified
sigma = 0;
if ~isempty(varargin)
    var1 = varargin{1};
    if isnumeric(var1) && isscalar(var1)
        sigma = var1;
        varargin(1) = [];
    end
end

% default filter for gradient: normalised sobel
if nd <= 2
    sx = gradientKernels(sigma);
elseif nd == 3
    sx = gradientKernels3d(sigma);
else
    error('Input image must have 2 or 3 dimensions');
end

% check if another gradient filter is proposed
for i = 1:length(varargin)-1
    if strcmp(varargin{i}, 'filter')
        sx = varargin{i+1};
        varargin(i:i+1) = [];
        break;
    end
end

% default options for computations
varargin = [{'replicate'}, {'conv'}, varargin];

%% Gradient computation

% compute gradients in each main direction
if nd == 2
    % Process 2D Image
    dx = imfilter(double(img), sx, varargin{:});
    dy = imfilter(double(img), sx', varargin{:});

elseif nd == 3
    % Process 3D Image
    sy = permute(sx, [2 3 1]);
    sz = permute(sx, [3 1 2]);
    dx = imfilter(double(img), sx, varargin{:});
    dy = imfilter(double(img), sy, varargin{:});
    dz = imfilter(double(img), sz, varargin{:});
end

%% Format output

% Depending on number of output arguments, returns either the gradient
% module, or each component of the gradient vector.
if nargout == 1
    % compute gradient module
    if nd == 2
        varargout{1} = hypot(dx, dy);
    else
        varargout{1} = hypot(hypot(dx, dy), dz);
    end

else
    % return each component of the vector array
    varargout{1} = dx;
    varargout{2} = dy;
    if nd > 2
        varargout{3} = dz;
    end
end

author: mattools

repo: matImage

save_path: github-repos/MATLAB/mattools-matImage


text:
function [success] = compile_mex(name, files, includes, directory, varargin)
% compile_mex Compile given source files to a MEX function
%
% Compiles or recompiles given source files to a MEX function taking
% into account source files timestamps. Also works in Octave by switching
% to mkoctfile command.
%
% Input:
% - name (string): Name of MEX function.
% - files (cell array): Array of source files.
% - includes (cell array): Optional array of include directories.
% - directory (string): Optional path of target directory.
%
% Output:
% - success (boolean): True if successful.
%

    function datenum = file_timestamp(filename)
        if ~exist(filename, 'file')
            datenum = 0;
            return;
        end;
        file_description = dir(filename);
        datenum = file_description.datenum;
    end

    mexname = fullfile(directory, sprintf('%s.%s', name, mexext));

    if exist(mexname, 'file') == 2 || exist(mexname, 'file') == 3

        function_timestamp = file_timestamp(mexname);

        older = cellfun(@(x) file_timestamp(x) < function_timestamp, files, 'UniformOutput', true);

        if all(older)
            success = true;
            return;
        end;
    end

    mexdebug = get_global_variable('mex_debug', false);

    arguments = {};

    if is_octave()
       arguments{end+1} = '-DOCTAVE';
    else
        arguments{end+1} = '-lut';
    end

    if mexdebug
       arguments{end+1} = '-g';
    end;

    if nargin < 3
        includes = cell(0);
    end

    if nargin < 4
        directory = '';
    end;

    includes = cellfun(@(x) sprintf('-I%s', x), includes, 'UniformOutput', false);

    old_dir = pwd;

    try

        if ~isempty(directory)
            cd(directory)
        end;

        if is_octave()

            [out, status] = mkoctfile('-mex', '-o', name, varargin{:}, includes{:}, files{:}, arguments{:});

            % Clean up mess
            for i = 1:numel(files)
                [pathstr, name, ext] = fileparts(files{i});
                tmpfile = fullfile(directory, [name, '.o']);
                if exist(tmpfile, 'file')
                  delete(tmpfile);
                end
            end

            if status
                error('Compile problem, see compiler output.');
            end;

        else

            mex('-output', name, varargin{:}, includes{:}, files{:}, arguments{:});

        end

        cd(old_dir);

        success = true;

    catch e
        cd(old_dir);
        print_text('ERROR: Unable to compile MEX function: "%s".', e.message);
        success = false;

    end

end

author: votchallenge

repo: toolkit-legacy


text:
function flo_i0 = genFlow(v0g, vig)

[h,w,~] = size(v0g);

minimum_flow_size = 200;         % length of the smaller dimension in the optical flow
DWNSMP = minimum_flow_size/min(h,w);
TAU = 0.2;                       % 0.25; (higher = faster, less accurate)
LAMBDA = 0.15;                   % 0.15; (smaller = smoother)
THETA = 0.3;
NSCALES = 6;                     % 5;
ZFACTOR = 0.5;
NWARPS = 7;                      % 5;
EPSILON = 0.01;
VERBOSE = 0;

flo_i0 = tvl1flow(v0g, vig, DWNSMP, TAU, LAMBDA, THETA,...
                    NSCALES, ZFACTOR, NWARPS, EPSILON, VERBOSE);

flo_i0_original_scale = zeros(h,w,2);
flo_i0_original_scale(:,:,1) = imresize(flo_i0(:,:,1), [h, w], 'bicubic');
flo_i0_original_scale(:,:,2) = imresize(flo_i0(:,:,2), [h, w], 'bicubic');
flo_i0 = flo_i0_original_scale;

flo_i0 = flo_i0/DWNSMP;

author: shuochsu

repo: DeepVideoDeblurring


text:
classdef VideoPlayer < handle

    properties (Access = public)
        delegate;
    end

    properties (Access = private)
        videoPlayerHandle;
        figureHandle;
        timer;
        previousFrame;
    end

    properties (GetAccess = public)
        numFrames;
    end

    properties (Dependent)
        currentFrame;
    end

    methods
        function f = get.currentFrame(obj)
            f = obj.videoPlayerHandle.DataSource.Controls.CurrentFrame;
        end
    end

    methods (Access = public)

        function obj = VideoPlayer(fileName,delegate,windowPosition)
            obj.videoPlayerHandle = implay(fileName);
            if nargin > 2
                obj.videoPlayerHandle.Parent.OuterPosition = windowPosition;
            end

            obj.delegate = delegate;
            obj.figureHandle = obj.videoPlayerHandle.Parent;
            obj.numFrames = str2double(obj.videoPlayerHandle.Visual.VideoInfo.PlaybackInfo.Widgets{2,2});
            obj.figureHandle.KeyPressFcn = @obj.handleKeyPress;
            obj.figureHandle.CloseRequestFcn = @obj.handleWindowClosed;
            obj.timer = timer('TimerFcn', @obj.timerTick,'Period',0.03,'ExecutionMode','fixedRate');
            start(obj.timer);
        end

        function frame = displayFrame(obj,frame)
            if frame > obj.numFrames
                frame = obj.numFrames;
            elseif frame < 1
                frame = 1;
            end
            obj.videoPlayerHandle.DataSource.Controls.jumpTo(double(frame));
            obj.previousFrame = frame;
        end

        function handleKeyPress(obj, ~, event)
            switch event.Key
                case 'leftarrow'
                    obj.videoPlayerHandle.DataSource.Controls.stepBack();
                case 'rightarrow'
                    obj.videoPlayerHandle.DataSource.Controls.stepFwd();
                case 'space'
                    obj.videoPlayerHandle.DataSource.Controls.playPause();
            end
            obj.previousFrame = obj.currentFrame;
            if ~isempty(obj.delegate)
                obj.delegate.handleVideoPlayerFrameChanged(obj.currentFrame);
            end
        end

        function close(obj)
            close(obj.figureHandle);
        end

        function makeForeGround(obj)
            figure(obj.videoPlayerHandle.Parent);
        end
    end

    methods (Access = private)

        function timerTick(obj,~,~)
            if(obj.currentFrame ~= obj.previousFrame)
                obj.previousFrame = obj.currentFrame;
                if ~isempty(obj.delegate)
                    obj.delegate.handleVideoPlayerFrameChanged(obj.previousFrame,obj);
                end
            end
        end

        function handleWindowClosed(obj,~,~)
            stop(obj.timer);
            delete(obj.timer);
            delete(obj.figureHandle);
            if ~isempty(obj.delegate)
                obj.delegate.handleVideoPlayerWindowClosed(obj);
            end
        end
    end
end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function m = p06_m ( )

%*****************************************************************************80
%
%% P06_M returns the number of equations M for problem 6.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 April 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer M, the number of equations.
%
  m = 10;

  return
end


text:
function [on,rt,ac] = spm_ADEM_cue_rt(DEM)
% returns reaction times and accuracy for ADEM_cued_response demo
% FORMAT [on,rt,ac] = spm_ADEM_cue_rt(DEM)
%
% DEM - DEM structure from ADEM_cued_response.m
%
% on  - cue onset
% ac  - accuracy
% rt  - reaction time
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_ADEM_cue_rt.m 4231 2011-03-07 21:00:02Z karl $

% distance from target and cue contrast
%--------------------------------------------------------------------------
n   = length(DEM.M(1).x.a);                   % number of targets
F   = DEM.pU.v{1}((1:2) + 2,:);               % location of finger
L   = DEM.pP.P{1};                            % location of targets
for i = 1:n
    D(i,:) = (F(1,:) - L(1,i)).^2;
    D(i,:) = (F(2,:) - L(2,i)).^2 + D(i,:);   % distance from targets
end
C   = DEM.pU.v{1}((1:n) + 4,:);               % contrast of targets

r   = 1/32;                                   % radius of proximity
c   = diff(C > 1,1,2) > 0;                    % target onset
on  = {};                                     % cue onset
ac  = {};                                     % accuracy
rt  = {};                                     % reaction time

% get performance
%--------------------------------------------------------------------------
for i = 1:n

    on{i} = find(c(i,:));
    for j = 1:length(on{i})
        try

            % minimum distance
            %--------------------------------------------------------------
            d        = D(i,(1:8) + on{i}(j))';
            ac{i}(j) = sqrt(min(d));

            % estimated reaction time
            %--------------------------------------------------------------
            X        = (1:length(d))' - 1;
            B        = pinv([X.^0 X.^1])*log(d);
            rt{i}(j) = (log(r) - B(1))/B(2);

        catch
            ac{i}(j) = NaN;
            rt{i}(j) = NaN;
        end
    end
end

% sort trials (over all targets
%--------------------------------------------------------------------------
on = spm_vec(on); [i j] = sort(on,1,'ascend'); on = on(j);
ac = spm_vec(ac); ac = ac(j);
rt = spm_vec(rt); rt = rt(j);

% remove first trial
%--------------------------------------------------------------------------
on(1) = [];
rt(1) = [];
ac(1) = [];

% convert spatial error to accuracy
%--------------------------------------------------------------------------
ac    = 1./ac;

% convert reaction time to ms
%--------------------------------------------------------------------------
dt    = 64/1000;
rt    = rt*1000*dt;
on    = on*dt;

author: spm


text:
%SFNONCONP1 Shape function driver (first order P1 Lagrange polynomials).
%
%   [ VBASE, NLDOF, XLDOF, SFUN ] = SFNONCONP1( I_EVAL, N_SDIM, N_VERT, I_DOF, XI, AINVJAC, VBASE )
%   Evaluates nonconforming linear (P-1/P1) shape functions with degrees
%   of freedom defined on the cell edges/faces for simplices and interior for
%   quadrilaterals/hexahedrals.
%
%       Input       Value/[Size]           Description
%       -----------------------------------------------------------------------------------
%       i_eval      scalar:  1             Evaluate function values
%                           >1             Evaluate values of derivatives
%       n_sdim      scalar: 2-3            Number of space dimensions
%       n_vert      scalar: 2-8            Number of vertices per cell
%       i_dof       scalar: 1-n_ldof       Local basis function to evaluate
%       xi          [n_sdim(+1)]           Local coordinates of evaluation point
%       aInvJac     [n,n_sdim(+1)*n_sdim]  Inverse of transformation Jacobian
%       vBase       [n]                    Preallocated output vector
%                                                                                .
%       Output      Value/[Size]           Description
%       -----------------------------------------------------------------------------------
%       vBase       [n]                    Evaluated function values
%       nLDof       [4]                    Number of local degrees of freedom on
%                                          vertices, edges, faces, and cell interiors
%       xLDof       [n_sdim,n_ldof]        Local coordinates of local dofs
%       sfun        string                 Function name of called shape function
%
%   See also SF_SIMP_P1NC, SF_DISC1

% Copyright 2013-2022 Precise Simulation, Ltd.

author: precise-simulation

repo: featool-multiphysics


text:
function b = r8mat_l1_inverse ( n, a )

%*****************************************************************************80
%
%% R8MAT_L1_INVERSE inverts a unit lower triangular R8MAT.
%
%  Discussion:
%
%    A unit lower triangular matrix is a matrix with only 1's on the main
%    diagonal, and only 0's above the main diagonal.
%
%    The inverse of a unit lower triangular matrix is also
%    a unit lower triangular matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 October 2005
%
%  Author:
%
%    Original FORTRAN77 version by Albert Nijenhuis, Herbert Wilf.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    A Nijenhuis and H Wilf,
%    Combinatorial Algorithms,
%    Academic Press, 1978, second edition,
%    ISBN 0-12-519260-6.
%
%  Parameters:
%
%    Input, integer N, number of rows and columns in the matrix.
%
%    Input, real A(N,N), the unit lower triangular matrix.
%
%    Output, real B(N,N), the inverse matrix.
%
  for i = 1 : n

    for j = 1 : n

      if ( i < j )
        b(i,j) = 0.0;
      elseif ( j == i )
        b(i,j) = 1.0;
      else
        b(i,j) = -( a(i,1:i-1) * b(1:i-1,j) );
      end

    end
  end

  return
end


text:
function c = ch_cap ( c )

%*****************************************************************************80
%
%% CH_CAP capitalizes a single character.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 April 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character C, the character to capitalize.
%
%    Output, character C, the capitalized character.
%
  if ( 'a' <= c && c <= 'z' )
    c = c + 'A' - 'a';
  end

  c = char ( c );

  return
end


text:
function [ o, x, w ] = epn_lag_01_1 ( n )

%*****************************************************************************80
%
%% EPN_LAG_01_1 implements a precision 1 rule for region EPN_LAG.
%
%  Discussion:
%
%    The rule has order O = 1.
%
%    The rule has precision P = 1.
%
%    EPN is the N-dimensional positive space [0,+oo)^N with exponential
%    or Laguerre weight function:
%
%      w(x(1:n)) = exp ( - sum ( x(1:n) ) )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 January 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the spatial dimension.
%
%    Input, integer O, the order.
%
%    Output, real X(N,O), the abscissas.
%
%    Output, real W(O), the weights.
%
  o = 1;

  expon = 0;
  value1 = ep1_lag_monomial_integral ( expon );
  volume = value1 ^ n;

  expon = 1;
  value2 = ep1_lag_monomial_integral ( expon );

  x = zeros ( n, o );
  w = zeros ( o, 1 );

  k = 0;
%
%  1 point.
%
  k = k + 1;
  x(1:n,k) = value2 / value1;
  w(k) = volume;

  return
end


text:
% Run this in order to construct the results table for the CE-CLM paper
Extract_table_results_68;

file_out = fopen('results/300W_68.txt', 'w');

fprintf(file_out, 'Errors with outline (68 points)\n');
fprintf(file_out, '------------------------------\n');
fprintf(file_out, 'Method\tcomm\tdiff\n');
fprintf(file_out, 'CLNF\t%.2f\t%.2f\n', median(clnf_error_comm)*100, median(clnf_error_ibug)*100);
fprintf(file_out, 'CFAN\t--- \t%.2f\n', median(cfan_error_ibug)*100);
fprintf(file_out, 'DRMF\t%.2f\t%.2f\n', median(drmf_error_comm)*100, median(drmf_error_ibug)*100);
fprintf(file_out, 'CFSS\t%.2f\t%.2f\n', median(cfss_error_comm)*100, median(cfss_error_ibug)*100);
fprintf(file_out, 'TCDCN\t%.2f\t%.2f\n', median(tcdcn_error_comm)*100, median(tcdcn_error_ibug)*100);
fprintf(file_out, '3DDFA\t%.2f\t%.2f\n', median(error_3ddfa_comm)*100, median(error_3ddfa_ibug)*100);
fprintf(file_out, '------------------------------\n');
fprintf(file_out, 'CE-CLM\t%.2f\t%.2f\n', median(ceclm_error_comm)*100, median(ceclm_error_ibug)*100);
fclose(file_out);

Extract_table_results_49;
file_out = fopen('results/300W_49.txt', 'w');

fprintf(file_out, 'Errors without outline (49 points)\n');
fprintf(file_out, '------------------------------\n');
fprintf(file_out, 'Method\tcomm\tdiff\n');
fprintf(file_out, 'CLNF\t%.2f\t%.2f\n', median(clnf_error_comm)*100, median(clnf_error_ibug)*100);
fprintf(file_out, 'SDM \t%.2f\t%.2f\n', median(sdm_error_comm)*100, median(sdm_error_ibug)*100);
fprintf(file_out, 'CFAN\t--- \t%.2f\n', median(cfan_error_ibug)*100);
fprintf(file_out, 'DRMF\t%.2f\t%.2f\n', median(drmf_error_comm)*100, median(drmf_error_ibug)*100);
fprintf(file_out, 'CFSS\t%.2f\t%.2f\n', median(cfss_error_comm)*100, median(cfss_error_ibug)*100);
fprintf(file_out, 'TCDCN\t%.2f\t%.2f\n', median(tcdcn_error_comm)*100, median(tcdcn_error_ibug)*100);
fprintf(file_out, '3DDFA\t%.2f\t%.2f\n', median(error_3ddfa_comm)*100, median(error_3ddfa_ibug)*100);
fprintf(file_out, '------------------------------\n');
fprintf(file_out, 'CE-CLM\t%.2f\t%.2f\n', median(ceclm_error_comm)*100, median(ceclm_error_ibug)*100);

fclose(file_out);

author: TadasBaltrusaitis

repo: OpenFace


text:
function B = dofan(phi, alphaFromTo, alphaStep, tN, tStep)
% Discretization matrix for
% Left-sided Distributed-order fractional derivative
%
% Function "phi", which describes the distribution
% of the order of differentiation, must be given
% as a string with variable "alf", for example:
% '6*alf.*(1-alf)'
%
% (C) Igor Podlubny, 2011

% Suppose the input parameters are given correctly
% (we do not validate the input parameters for now)

% Check if the FEX package 22071 is on your MATLAB path,
% and if it is not there, then require the FEX packages
% 31069 ("requireFEXpackage") and 22071 ("Matrix approach
% to discretization of ODEs and PDEs of arbitrary real order"):
if ~(exist('ban', 'file') == 2 && exist('fan', 'file') == 2 ...
    && exist('ranort', 'file') && exist('eliminator', 'file') == 2)
    P = requireFEXpackage(31069); % "requireFEXpackage"
    P = requireFEXpackage(22071);  % "Matrix approach..."
end

alphas = alphaFromTo(1):alphaStep:alphaFromTo(2);
alphaCount = length(alphas);

alf = alphas;
phik = eval(phi);

% Pre-allocate memory for layers with different orders 'alf'
B = zeros(tN, tN);

for k = 1:alphaCount
    B = B + phik(k) * alphaStep * fan(alf(k), tN, tStep);
end


text:
function a = i4cvv_nset ( mn, a, m, roff, nn, in, jn, vn )

%*****************************************************************************80
%
%% I4CVV_NSET sets items JN(*) from row IN(*) in an I4CVV.
%
%  Discussion:
%
%    An I4CVV is a "vector of vectors" of I4's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer MN, the size of the cell array.
%
%    Input, integer A(MN), the cell array.
%
%    Input, integer M, the number of rows in the array.
%
%    Input, integer ROFF(M+1), the row offsets.
%
%    Input, integer NN, the number of items.
%
%    Input, integer IN(NN), the rows of the items.
%    1 <= IN(*) <= M.
%
%    Input, integer JN(NN), the columns of the items.
%    1 <= JN(*) <= NR(IN(*)).
%
%    Input, integer VN(NN), the new value of items A(IN(*),JN(*)).
%
%    Output, integer A(MN), the cell array.
%
  k = roff(in(1:nn)) + jn(1:nn);
  a(k) = vn(1:nn);

  return
end


text:
function [fx,fy,fz,ft] = computeDerivatives3(in1,in2)
%
% function [fx,fy,fz,ft] = computeDerivatives3(in1,in2)
%
% in1 and in2 are volumes, 3d arrays
%
% [fx,fy,fz,ft] are volumes, derivatives of the volumes

filter = [0.03504 0.24878 0.43234 0.24878 0.03504];
dfilter = [0.10689 0.28461 0.0  -0.28461  -0.10689];

dz1 = convXYsep(convZ(in1,dfilter),filter,filter);
tmp1 = convZ(in1,filter);
dx1 = convXYsep(tmp1,dfilter,filter);
dy1 = convXYsep(tmp1,filter,dfilter);
blur1 = convXYsep(tmp1,filter,filter);

dz2 = convXYsep(convZ(in2,dfilter),filter,filter);
tmp2 = convZ(in2,filter);
dx2 = convXYsep(tmp2,dfilter,filter);
dy2 = convXYsep(tmp2,filter,dfilter);
blur2 = convXYsep(tmp2,filter,filter);

fx=(dx1+dx2)/2;
fy=(dy1+dy2)/2;
fz=(dz1+dz2)/2;
ft=(blur2-blur1);

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function varargout = alldist2(varargin)
% VL_ALLDIST2  Pairwise distances
%  D = VL_ALLDIST2(X,Y) returns the pairwise distance matrix D of the
%  columns of S1 and S2, yielding
%
%    D(i,j) = sum (X(:,i) - Y(:,j)).^2
%
%  VL_ALLDIST2(X) returns the pairwise distance matrix fo the columns of
%  S, yielding
%
%    D(i,j) = sum (X(:,i) - X(:,j)).^2
%
%  VL_ALLDIST2(...,'METRIC') changes the computed distance. Supported
%  values for METRIC are
%
%   METRIC  D(i,j)
%   --------------------------------------------------------
%    LINF   max |X  - Y|
%    L2     sum (X  - Y).^2
%    L1     sum |X  - Y|
%    L0     sum (X ~= Y)
%    CHI2   sum (X  - Y).^2 ./ (X + Y)
%    HELL   sum (X^.5 - Y^.5) .^ 2
%
%  (Notice that the standard definition of chi2 is half of what is
%  computed here).
%
%  VL_ALLDIST2(...,'KERNEL') computes the following 'kernels' K:
%
%   KERNEL  K(i,j)
%   ---------------------------------------------------------
%    KL2    sum X .* Y
%    KL1    sum min (X, Y)
%    KCHI2  2 * sum (X .* Y) ./ (X + Y)
%    KHELL  (X .* Y) .^ 0.5
%
%  The constant are chosen so that D(i,j) = K(i,i) + K(j,j) - 2 K(i,j)
%  where D is the metric corresponding to the kenrel (if the arguments
%  are non-negative vectors). Each kernel can be interpreted as the
%  inner product inducing the corresponding metric in an embedding of
%  the real space into an approrpiate reproducing Kenrel Hilbert
%  space.
%
%  VL_ALLDIST2() supports several storage classes. X and Y must have the
%  same storage class. The sotrage class of D is promoted to reduce
%  the chance of overvlow, but this is not checked.
%
%    X & Y class      D class
%   ---------------------------
%    UINT8            UINT32
%     INT8             INT32
%    UINT16           UINT32
%     INT16            INT32
%    UINT32           UINT32
%     INT32            INT32
%    SINGLE           SINGLE
%    DOUBLE           DOUBLE
%
%  Warning: Both chi2 and kchi2 use integer math when presented with
%  integer data types. This can easily result in zeros where you did
%  not expect them.
%
%  See also: VL_HELP().
[varargout{1:nargout}] = vl_alldist2(varargin{:});

author: yihui-he

repo: panorama

save_path: github-repos/MATLAB/yihui-he-panorama


text:
function x=istft_multi_2(X,nsampl)

% ISTFT_MULTI Multichannel inverse short-time Fourier transform (ISTFT)
% using half-overlapping sine windows.
%
% x=istft_multi(X,nsampl)
%
% Inputs:
% X: nfram x nbin x nchan matrix containing STFT coefficients for nchan
% sources with nbin frequency bins and nfram time frames
% nsampl: number of samples to which the corresponding time-domain signals
% are to be truncated
%
% Output:
% x:  nsampl x nchan matrix containing the corresponding time-domain signals
% If x is a set of signals of length nsampl and X=stft_multi(x), then
% x=istft_multi(X,nsampl).

%%% Errors and warnings %%%
if nargin<2, error('Not enough input arguments.'); end
[nfram,nbin,nchan]=size(X);
if nbin==2*floor(nbin/2), error('The number of frequency bins must be odd.'); end
wlen=2*(nbin-1);

%%% Computing inverse STFT signal %%%
% Defining sine window
win=sin((.5:wlen-.5)/wlen*pi).';

%%% windowing method 1:
swin=ones((nfram+1)*wlen/2,1);
% for t=0:nfram-1,
%     swin(t*wlen/2+1:t*wlen/2+wlen)=swin(t*wlen/2+1:t*wlen/2+wlen)+win.^2;
% end
% swin=sqrt(swin);
%%%
swin(1:wlen/2,1)=win(1:wlen/2);
swin(nfram*wlen/2+1:end,1)=win(wlen/2+1:wlen);

x=zeros((nfram+1)*wlen/2,nchan);
for i=1:nchan,
    for t=0:nfram-1,
        % IFFT
        fframe=[X(t+1,:,i),conj(X(t+1,wlen/2:-1:2,i))];
        frame=real(ifft(fframe)).';
        %%% Overlap-add method 1
        x(t*wlen/2+1:t*wlen/2+wlen,i)=x(t*wlen/2+1:t*wlen/2+wlen,i)+frame.*win./swin(t*wlen/2+1:t*wlen/2+wlen);
%         %%% Overlap-add method 2
%         x(t*wlen/2+1:t*wlen/2+wlen,i)=x(t*wlen/2+1:t*wlen/2+wlen,i)+frame.*win;
    end
end

%%% just for method 2: to keep the energy before and after windowing the same.
% swin=zeros((nfram+1)*wlen/2,1);
% for t=0:nfram-1,
%     swin(t*wlen/2+1:t*wlen/2+wlen)=swin(t*wlen/2+1:t*wlen/2+wlen)+win.^2;
% end
% x=x./swin;

% % Truncation
x=x(1:nsampl,:);
return;

author: ZitengWang

repo: MASP

save_path: github-repos/MATLAB/ZitengWang-MASP


text:
% eeg_bad_channels_script - process files with eeg_bad_channels

clear all;
close all;

path = '/floyd3/psdlw/ptsd-pet/original-scan/';
volt_ext = '.avg';
%var_ext = 'var.asc'; % Not used, assumed to be voltfile.var

elec_path = '/floyd3/psdlw/ptsd-pet/3dd_mean/corrected_elp/';
elec_ext = 'txt';

groups = {'c' 'p'};
subjects = {'01' '02' '03' '04' '05' '06' '07' '08' '09' '10'};
conditions = {'o' 'oac' 'ouc' 'out' 't' 'tac' 'tad' 'tat' 'tuc' 'tud' 'tut'};

for g=1:length(groups),

    for s=1:length(subjects),

        for c = 1:length(conditions),

            subj = strcat(char(groups(g)),char(subjects(s)));
            cond = char(conditions(c));

           [p] = eeg_toolbox_defaults('create');

            p.volt.path = path;
            p.volt.file = strcat(subj,cond,volt_ext);
            p.volt.type = 'Scan3x';

           [p] = eeg_open(p);

            p.elec.path = elec_path;
            p.elec.file = strcat(subj,'_124fit',elec_ext);
            p.elec.type = 'Cartesian';

           [p] = elec_open(p);

           [p] = eeg_bad_channels(p);
        end
    end
end

author: PatternRecognition

repo: OpenBMI


text:
function daub6_scale_plot ( n )

%*****************************************************************************80
%
%% DAUB6_SCALE_PLOT plots the DAUB6 scaling function.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the recursion level.
%
  x = linspace ( 0.0, 6.0, 801 );

  y = daub6_scale ( n, x );

  plot ( x, y, 'LineWidth', 2 );

  grid on
  xlabel ( '<---X--->' );
  ylabel ( '<---Y--->' );
  title ( sprintf ( 'DAUB6 Scale Function, Recursion level n = %d', n ) );

  return
end


text:
function saveinr(vol,fname)
%
% saveinr(vol,fname)
%
% save a surface mesh to INR Format
%
% author: Qianqian Fang, <q.fang at neu.edu>
% date: 2009/01/04
%
% input:
%      vol: input, a binary volume
%      fname: output file name
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

fid=fopen(fname,'wb');
if(fid==-1)
    error('You do not have permission to save mesh files.');
end
dtype=class(vol);
if(islogical(vol) || strcmp(dtype,'uint8'))
   btype='unsigned fixed';
   dtype='uint8';
   bitlen=8;
elseif(strcmp(dtype,'uint16'))
   btype='unsigned fixed';
   dtype='uint16';
   bitlen=16;
elseif(strcmp(dtype,'single'))
   btype='float';
   dtype='float';
   bitlen=32;
elseif(strcmp(dtype,'double'))
   btype='float';
   dtype='double';
   bitlen=64;
else
   error('volume format not supported');
end
header=sprintf(['#INRIMAGE-4#{\nXDIM=%d\nYDIM=%d\nZDIM=%d\nVDIM=1\nTYPE=%s\n' ...
  'PIXSIZE=%d bits\nCPU=decm\nVX=1\nVY=1\nVZ=1\n'],size(vol),btype,bitlen);
header=[header char(10*ones(1,256-4-length(header))) '##}' char(10)];
fwrite(fid,header,'char');
fwrite(fid,vol,dtype);
fclose(fid);

author: fangq


text:
% M-File showing that the RA method of creating the A & B arrays
% gives the same results using the conventional method.
% File:  c:\M_files\short_updates\Matlab_Files\RAconvention.m
% 02/16/07
% See Word file UsingGarray1.doc for background explanations.
clear;clc;
% unit suffixes
u=1e-6;K=1e3;m=1e-3;u=1e-6;p=1e-12;
% component values
R1=5*K;R2=1*K;R3=10*K;
C1=0.1*u;C2=400*p;
Ein=1; % Unity input for (normalized) transfer function
%
% Form W, Q, S, and P arrays:
%
W=[1+R3/R1 1+R3/R1;R2 0];Q=[0 -1/R1;-1 1];S=[Ein/R1;0];P=diag([C1 C2]);
%
% Get A & B arrays using RA method:
%
C=inv(W*P);A=C*Q;B=C*S;
% Display A & B in Command window:
disp('RA Method')
disp(' ')
A
B
disp(' ')
% Using conventional method:
%
disp('Conventional method')
disp(' ')
A=[-1/(R2*C1) 1/(R2*C1);1/(R2*C2) (1/(R1+R3)+1/R2)/C2]
B=[0;(1/(R1+R3))/C2]
%

author: Sable

repo: mcbench-benchmarks


text:
function test06 ( dim_num, level_max )

%*****************************************************************************80
%
%% TEST06 creates a sparse Clenshaw-Curtis grid and writes it to a file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    11 August 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, integer LEVEL_MAX, the level.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST06:\n' );
  fprintf ( 1, '  SPARSE_GRID_CC makes a sparse Clenshaw-Curtis grid.\n' );
  fprintf ( 1, '  Write the data to a set of quadrature files.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  LEVEL_MAX = %d\n', level_max );
  fprintf ( 1, '  Spatial dimension DIM_NUM = %d\n', dim_num );
%
%  Determine the number of points.
%
  point_num = sparse_grid_cfn_size ( dim_num, level_max );

  r(1:dim_num,1) = -1.0;
  r(1:dim_num,2) = +1.0;
%
%  Compute the weights and points.
%
  [ w, x ] = sparse_grid_cc ( dim_num, level_max, point_num );
%
%  Write the data out.
%
  r_filename = sprintf ( 'cc_d%d_level%d_r.txt', dim_num, level_max );
  w_filename = sprintf ( 'cc_d%d_level%d_w.txt', dim_num, level_max );
  x_filename = sprintf ( 'cc_d%d_level%d_x.txt', dim_num, level_max );

  r8mat_write ( r_filename, dim_num, 2,         r );
  r8mat_write ( w_filename, 1,       point_num, w );
  r8mat_write ( x_filename, dim_num, point_num, x );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  R data written to "%s".\n', r_filename );
  fprintf ( 1, '  W data written to "%s".\n', w_filename );
  fprintf ( 1, '  X data written to "%s",\n', x_filename );

  return
end

author: johannesgerer


text:
function p03_title ( )

%*****************************************************************************80
%
%% P03_TITLE prints a title for problem 03.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    None
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'Problem 03\n' );
  fprintf ( 1, '  Name:       QuintSum\n' );
  fprintf ( 1, '              Davis, Rabinowitz, page 370, #3.\n' );
  fprintf ( 1, '  Region:     0 <= X(i) <= 1\n' );
  fprintf ( 1, '  Integrand:  F(X) = ( sum ( X(i) ) )^5\n' );

  return
end


text:
function [in, on] = getDataFromClickedPointsOnAImage(h, num_click, data, display)
    [xv, yv] = ginput(num_click);
    xq = data(1,:);
    yq = data(2,:);
    [in, on] = inpolygon(xq, yq, xv, yv);
    if checkDisplay(display)
        numel(xq(in))
        numel(xq(on))
        current_img_handle = h;
        hold(current_img_handle, 'on');
        plot(xv,yv) % polygon
        hold on
        plot(xq(in),yq(in),'r+') % points inside
        set(get(current_img_handle, 'parent'),'visible','on');% show the current axes
        axis equal
        hold(current_img_handle, 'off');
    end
end

author: UMich-BipedLab


text:
% MFE Toolbox Toolbox
% Version 4.0 28-Oct-2009

author: bashtage

repo: mfe-toolbox


text:
classdef nnpdist < nntest
  properties (TestParameter)
    oneToOne = {false, true}
    noRoot = {false, true}
    p = {.5 1 2 3}
    aggregate = {false, true}
  end
  methods (Test)
    function basic(test,oneToOne, noRoot, p, aggregate)
      if aggregate
        % make it smaller to avoid numerical derivative issues with
        % float
        h = 3 ;
        w = 2 ;
      else
        h = 13 ;
        w = 17 ;
      end
      d = 4 ;
      n = 5 ;
      x = test.randn(h,w,d,n) ;
      if oneToOne
        x0 = test.randn(h,w,d,n) ;
      else
        x0 = test.randn(1,1,d,n) ;
      end
      opts = {'noRoot', noRoot, 'aggregate', aggregate} ;

      y = vl_nnpdist(x, x0, p, opts{:}) ;

      % make sure they are not too close in any dimension as this may be a
      % problem for the finite difference dereivatives as one could
      % approach 0 which is not differentiable for some p-norms

      s = abs(bsxfun(@minus, x, x0)) < test.range*1e-1 ;
      x(s) = x(s) + 5*test.range ;

      dzdy = test.rand(size(y)) ;
      [dzdx, dzdx0] = vl_nnpdist(x,x0,p,dzdy,opts{:}) ;
      test.der(@(x) vl_nnpdist(x,x0,p,opts{:}), x, dzdy, dzdx, test.range * 1e-3) ;
      if oneToOne
        % Pdist does not implement backprop of the bsxfun
        test.der(@(x0) vl_nnpdist(x,x0,p,opts{:}), x0, dzdy, dzdx0, test.range * 1e-3) ;
      end
    end
  end
end

author: guosheng

repo: refinenet

save_path: github-repos/MATLAB/guosheng-refinenet


text:
function test_approx_test05 ( )

%*****************************************************************************80
%
%% TEST_APPROX_TEST05 uses Overhauser spline interpolation on all problems.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 August 2011
%
%  Author:
%
%    John Burkardt
%
  num_dim = 1;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST_APPROX_TEST05\n' );
  fprintf ( 1, '  Overhauser spline interpolation.\n' );

  prob_num = p00_prob_num ( );

  for prob = 1 : prob_num

    title = p00_title ( prob );

    data_num = p00_data_num ( prob );

    [ xdata, ydata ] = p00_dat ( prob, data_num );

    a = xdata(1);
    b = xdata(data_num);

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Problem %d\n', prob );
    fprintf ( 1, '  %s\n', title );
    fprintf ( 1, '\n' );
    fprintf ( 1, '  X   Y\n' );
    fprintf ( 1, '\n' );
%
%  Evaluate the interpolation function.
%
    for i = 1 : data_num - 1

      jmax = 3;

      if ( i == data_num - 1 )
        jhi = jmax;
      else
        jhi = jmax - 1;
      end

      for j = 1 : jhi

        xval = ( ( jmax - j     ) * xdata(i)     ...
               + (        j - 1 ) * xdata(i+1) ) ...
               / ( jmax     - 1 );

        yval = spline_overhauser_val ( num_dim, data_num, xdata, ydata, xval );

        if ( j == 1 || j == 3 )
          mark = '*';
        else
          mark = ' ';
        end

        fprintf ( 1, '  %c  %14g  %14g\n', mark, xval, yval );

      end

    end

  end

  return
end

repo: jburkardt-m


text:
function [ net ] = InitFeatureExtractionNet( net,net1)

net.addLayer('conv1', dagnn.Conv('size', [3,3,3,64], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'input', 'conv_1', {'conv1_f', 'conv1_b'});
net.addLayer('relu1', dagnn.ReLU(), 'conv_1', 'relu_1');

f=net.getParamIndex('conv1_f');
net.params(f).value=net1.layers{1}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv1_b');
net.params(f).value=net1.layers{1}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv2', dagnn.Conv('size', [3,3,64,64], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_1', 'conv_2', {'conv2_f', 'conv2_b'});
net.addLayer('relu2', dagnn.ReLU(), 'conv_2', 'relu_2');

f=net.getParamIndex('conv2_f');
net.params(f).value=net1.layers{3}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv2_b');
net.params(f).value=net1.layers{3}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('pool1', dagnn.Pooling('poolSize', [2,2], 'pad', [0,0,0,0],...
    'stride', [2,2]),'relu_2','pool_1');

%----------------------------------
net.addLayer('conv3', dagnn.Conv('size', [3,3,64,128], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'pool_1', 'conv_3', {'conv3_f', 'conv3_b'});
net.addLayer('relu3', dagnn.ReLU(), 'conv_3', 'relu_3');

f=net.getParamIndex('conv3_f');
net.params(f).value=net1.layers{6}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv3_b');
net.params(f).value=net1.layers{6}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv4', dagnn.Conv('size', [3,3,128,128], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_3', 'conv_4', {'conv4_f', 'conv4_b'});
net.addLayer('relu4', dagnn.ReLU(), 'conv_4', 'relu_4');

f=net.getParamIndex('conv4_f');
net.params(f).value=net1.layers{8}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv4_b');
net.params(f).value=net1.layers{8}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('pool2', dagnn.Pooling('poolSize', [2,2], 'pad', [0,0,0,0],...
    'stride', [2,2]),'relu_4','pool_2');

%------------------------------
net.addLayer('conv5', dagnn.Conv('size', [3,3,128,256], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'pool_2', 'conv_5', {'conv5_f', 'conv5_b'});
net.addLayer('relu5', dagnn.ReLU(), 'conv_5', 'relu_5');

f=net.getParamIndex('conv5_f');
net.params(f).value=net1.layers{11}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv5_b');
net.params(f).value=net1.layers{11}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv6', dagnn.Conv('size', [3,3,256,256], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_5', 'conv_6', {'conv6_f', 'conv6_b'});
net.addLayer('relu6', dagnn.ReLU(), 'conv_6', 'relu_6');

f=net.getParamIndex('conv6_f');
net.params(f).value=net1.layers{13}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv6_b');
net.params(f).value=net1.layers{13}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv7', dagnn.Conv('size', [3,3,256,256], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_6', 'conv_7', {'conv7_f', 'conv7_b'});
net.addLayer('relu7', dagnn.ReLU(), 'conv_7', 'relu_7');

f=net.getParamIndex('conv7_f');
net.params(f).value=net1.layers{15}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv7_b');
net.params(f).value=net1.layers{15}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv8', dagnn.Conv('size', [3,3,256,256], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_7', 'conv_8', {'conv8_f', 'conv8_b'});
net.addLayer('relu8', dagnn.ReLU(), 'conv_8', 'relu_8');

f=net.getParamIndex('conv8_f');
net.params(f).value=net1.layers{17}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv8_b');
net.params(f).value=net1.layers{17}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('pool3', dagnn.Pooling('poolSize', [2,2], 'pad', [0,0,0,0],...
    'stride', [2,2]),'relu_8','pool_3');

net.addLayer('conv9', dagnn.Conv('size', [3,3,256,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'pool_3', 'conv_9', {'conv9_f', 'conv9_b'});
net.addLayer('relu9', dagnn.ReLU(), 'conv_9', 'relu_9');

f=net.getParamIndex('conv9_f');
net.params(f).value=net1.layers{20}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv9_b');
net.params(f).value=net1.layers{20}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv10', dagnn.Conv('size', [3,3,512,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_9', 'conv_10', {'conv10_f', 'conv10_b'});
net.addLayer('relu10', dagnn.ReLU(), 'conv_10', 'relu_10');

f=net.getParamIndex('conv10_f');
net.params(f).value=net1.layers{22}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv10_b');
net.params(f).value=net1.layers{22}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv11', dagnn.Conv('size', [3,3,512,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_10', 'conv_11', {'conv11_f', 'conv11_b'});
net.addLayer('relu11', dagnn.ReLU(), 'conv_11', 'relu_11');

f=net.getParamIndex('conv11_f');
net.params(f).value=net1.layers{24}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv11_b');
net.params(f).value=net1.layers{24}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv12', dagnn.Conv('size', [3,3,512,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_11', 'conv_12', {'conv12_f', 'conv12_b'});
net.addLayer('relu12', dagnn.ReLU(), 'conv_12', 'relu_12');

f=net.getParamIndex('conv12_f');
net.params(f).value=net1.layers{26}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv12_b');
net.params(f).value=net1.layers{26}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('pool4', dagnn.Pooling('poolSize', [2,2], 'pad', [0,0,0,0],...
    'stride', [2,2]),'relu_12','pool_4');

net.addLayer('conv13', dagnn.Conv('size', [3,3,512,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'pool_4', 'conv_13', {'conv13_f', 'conv13_b'});
net.addLayer('relu13', dagnn.ReLU(), 'conv_13', 'relu_13');

f=net.getParamIndex('conv13_f');
net.params(f).value=net1.layers{29}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv13_b');
net.params(f).value=net1.layers{29}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv14', dagnn.Conv('size', [3,3,512,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_13', 'conv_14', {'conv14_f', 'conv14_b'});
net.addLayer('relu14', dagnn.ReLU(), 'conv_14', 'relu_14');

f=net.getParamIndex('conv14_f');
net.params(f).value=net1.layers{31}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv14_b');
net.params(f).value=net1.layers{31}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv15', dagnn.Conv('size', [3,3,512,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_14', 'conv_15', {'conv15_f', 'conv15_b'});
net.addLayer('relu15', dagnn.ReLU(), 'conv_15', 'relu_15');

f=net.getParamIndex('conv15_f');
net.params(f).value=net1.layers{33}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv15_b');
net.params(f).value=net1.layers{33}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('conv16', dagnn.Conv('size', [3,3,512,512], 'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_15', 'conv_16', {'conv16_f', 'conv16_b'});
net.addLayer('relu16', dagnn.ReLU(), 'conv_16', 'relu_16');

f=net.getParamIndex('conv16_f');
net.params(f).value=net1.layers{35}.filters;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

f=net.getParamIndex('conv16_b');
net.params(f).value=net1.layers{35}.biases;
net.params(f).learningRate=0;
net.params(f).weightDecay=0;

net.addLayer('pool5', dagnn.Pooling('poolSize', [2,2], 'pad', [0,0,0,0],...
    'stride', [2,2]),'relu_16','pool_5');

end

repo: CREST-Release


text:
function [i] = plotgp(i, t, sys, y, std)
% Function plots results of simulation or one-step-ahead
% prediction.
%
%% Syntax
% [i] = plotgp(i, t, sys, y, std);
%
%% Description
% In the upper 2/3 of the figure the output together with 95%
% confidence band and target is plotted, in the lower third of the figure
% the error with corresponding 95% confidence band is plotted. Can be used
% to plot in new or currently active figure.
%
% Input:
% * i   ... the figure handle, if i==0 function plots in current figure
% * t   ... the time vector (x-axis)
% * sys ... the target output
% * y   ... the predicted output
% * std ... the predicted standard deviation
%
% Output:
% * i ... the figure handle
%
% See Also:
% plotgpy, plotgpe
%
% Examples:
% demo_example_gp_simulation.m
%
%%
% * Written by Dejan Petelin

% check sizes of vectors
sz = size(t);
if((size(t,1)~=sz(1) | size(sys,1)~=sz(1) |size(y,1)~=sz(1) | size(std,1)~=sz(1))...
        | (size(t,2)~=sz(2) | size(sys,2)~=sz(2) |size(y,2)~=sz(2) | size(std,2)~=sz(2)))
    warning(['figure ', num2str(i), ': vectors: t, tt, y, std must be same size']);
    disp(strcat(['t: ', num2str(size(t))]));
    disp(strcat(['sys: ', num2str(size(sys))]));
    disp(strcat(['y: ', num2str(size(y))]));
    disp(strcat(['std: ', num2str(size(std))]));
    out = -1;
    return;
end

ix_plot = 1:length(t);
% reduce vector if borders are wanted in figure,
% e.g. ixplot = 2:length(t)-1;

xfill = [t(ix_plot); flipdim(t(ix_plot),1)];
yfill = [y(ix_plot)+2*std(ix_plot);flipdim(y(ix_plot)-2*std(ix_plot),1)];

% if i==0 use current axis (figure)
if (i~=0)
figure(i);
end

% upper part of figure: y
subplot(3,1,1:2)
fill(xfill, yfill, [7 7 7]/8, 'EdgeColor', [0 0 0]/8);
hold on
plot(t,y, 'k-', 'LineWidth',1);
plot(t,sys, 'k--', 'LineWidth',2);

hold off
grid on
xlabel('t');
ylabel('y');
title('GP model simulation')
legend('\mu \pm 2\sigma', '\mu', 'system','Location','NorthEast');
AX=axis;
AX(1:2)=[t(1) t(end)];
axis(AX);

% lower part of figure: e
subplot(3,1,3)
xfill = [t(ix_plot); flipdim(t(ix_plot),1)];
yfill = [2*std(ix_plot);zeros(size(std(ix_plot)))];
fill(xfill, yfill, [7 7 7]/8, 'EdgeColor', [0 0 0]/8);

hold on
plot(t,abs(y-sys), 'k-', 'LineWidth',1);
hold off
legend('2\sigma', '|e|', 'Location','NorthEast');
grid
xlabel('t');
ylabel('e');
AX=axis;
AX(1:2)=[t(1) t(end)];
axis(AX);

return

author: Dynamic-Systems-and-GP

repo: GPdyn


text:
% [data, hdr] = opensvl(filename)
%
% Reads a CTF SAM (.svl) file.

function [data, hdr] = read_ctf_svl(filename)

  fid = fopen_or_error(filename, 'rb', 'ieee-be', 'ISO-8859-1');

  % ----------------------------------------------------------------------
  % Read header.
  hdr.identity = fread(fid, 8, '*char')'; % 'SAMIMAGE'
  hdr.version = fread(fid, 1, 'int32'); % SAM file version.
  hdr.setName = fread(fid, 256, '*char')'; % Dataset name.
  hdr.numChans = fread(fid, 1, 'int32');
  hdr.numWeights = fread(fid, 1, 'int32'); % 0 for static image.
  if(hdr.numWeights ~= 0)
    ft_warning('hdr.numWeights ~= 0');
  end

  fread(fid,1,'int32'); % Padding to next 8 byte boundary.

  hdr.xmin = fread(fid, 1, 'double'); % Bounding box coordinates (m).
  hdr.xmax = fread(fid, 1, 'double');
  hdr.ymin = fread(fid, 1, 'double');
  hdr.ymax = fread(fid, 1, 'double');
  hdr.zmin = fread(fid, 1, 'double');
  hdr.zmax = fread(fid, 1, 'double');
  hdr.stepSize = fread(fid, 1, 'double'); % m

  hdr.hpFreq = fread(fid, 1, 'double'); % High pass filtering frequency (Hz).
  hdr.lpFreq = fread(fid, 1, 'double'); % Low pass.
  hdr.bwFreq = fread(fid, 1, 'double'); % Bandwidth
  hdr.meanNoise = fread(fid, 1, 'double'); % Sensor noise (T).

  hdr.mriName = fread(fid, 256, '*char')';
  hdr.fiducial.mri.nas = fread(fid, 3, 'int32'); % CTF MRI voxel coordinates?
  hdr.fiducial.mri.rpa = fread(fid, 3, 'int32');
  hdr.fiducial.mri.lpa = fread(fid, 3, 'int32');

  hdr.SAMType = fread(fid, 1, 'int32'); % 0: image, 1: weights array, 2: weights list.
  hdr.SAMUnit = fread(fid, 1, 'int32');
  % Possible values: 0 coefficients Am/T, 1 moment Am, 2 power (Am)^2, 3 Z,
  % 4 F, 5 T, 6 probability, 7 MUSIC.

  fread(fid, 1, 'int32'); % Padding to next 8 byte boundary.

  if hdr.version > 1
    % Version 2 has extra fields.
    hdr.fiducial.head.nas = fread(fid, 3, 'double'); % CTF head coordinates?
    hdr.fiducial.head.rpa = fread(fid, 3, 'double');
    hdr.fiducial.head.lpa = fread(fid, 3, 'double');
    hdr.SAMUnitName = fread(fid, 32, '*char')';
  % Possible values: 'Am/T' SAM coefficients, 'Am' source strength,
  % '(Am)^2' source power, ('Z', 'F', 'T') statistics, 'P' probability.
  end

  % ----------------------------------------------------------------------
  % Read image data.
  data = fread(fid, inf, 'double');
  fclose(fid);

  % Raw image data is ordered as a C array with indices: [x][y][z], meaning
  % z changes fastest and x slowest.  These x, y, z axes point to ALS
  % (anterior, left, superior) respectively in real world coordinates,
  % which means the voxels are in SLA order.

  % ----------------------------------------------------------------------
  % Post processing.

  % Change from m to mm.
  hdr.xmin = hdr.xmin * 1000;
  hdr.ymin = hdr.ymin * 1000;
  hdr.zmin = hdr.zmin * 1000;
  hdr.xmax = hdr.xmax * 1000;
  hdr.ymax = hdr.ymax * 1000;
  hdr.zmax = hdr.zmax * 1000;
  hdr.stepSize = hdr.stepSize * 1000;

  % Number of voxels in each dimension.
  hdr.dim = [round((hdr.xmax - hdr.xmin)/hdr.stepSize) + 1, ...
    round((hdr.ymax - hdr.ymin)/hdr.stepSize) + 1, ...
    round((hdr.zmax - hdr.zmin)/hdr.stepSize) + 1];

  data = reshape(data, hdr.dim([3, 2, 1]));

  % Build transformation matrix from raw voxel coordinates (indexed from 1)
  % to head coordinates in mm.  Note that the bounding box is given in
  % these coordinates (in m, but converted above).
  % Apply scaling.
  hdr.transform = diag([hdr.stepSize * ones(1, 3), 1]);
  % Reorder directions.
  hdr.transform = hdr.transform(:, [3, 2, 1, 4]);
  % Apply translation.
  hdr.transform(1:3, 4) = [hdr.xmin; hdr.ymin; hdr.zmin] - hdr.stepSize;
  % -step is needed since voxels are indexed from 1.

end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function UseCards(object, ~, inventory, main)

res = get(0, 'ScreenSize');
%% FIGURE WINDOW
handle = ...
    figure('Name', 'Use Cards', ...
           'Units', 'pixels', ...
           'MenuBar', 'none', ...
           'NumberTitle', 'off', ...
           'Position', [res(3:4)/3, 150, 200]);

%% RADIO BUTTONS
str = {'3 x Infantry','3 x Cavallery','3 x Artillery','One of each'};
r = zeros(1,4);
for i = 1:4
    r(i) = uicontrol('style', 'radiobutton', ...
                     'Parent', handle, ...
                     'Units', 'normalized', ...
                     'String', str{i}, ...
                     'FontSize', 12, ...
                     'BackgroundColor', get(handle, 'Color'), ...
                     'Position', [0.1, 0.85 - 0.2 * (i-1), 0.8, 0.1], ...
                     'CallBack', @RadioCallback);
end

%% USE BUTTON
uicontrol('style', 'pushbutton', ...
          'Parent', handle, ...
          'Units', 'normalized', ...
          'String', 'Use', ...
          'FontSize', 12, ...
          'FontWeight', 'bold', ...
          'BackgroundColor', get(handle, 'Color'), ...
          'Position', [0.3, 0.06, 0.4, 0.1], ...
          'CallBack', {@UseBtnCallback, inventory, r, object})

uiwait(handle) %10
uiresume(main); %9

function RadioCallback(button, ~)

r = findobj('Parent', get(button, 'Parent'), 'style', 'radiobutton');
for i = find(r ~= button)
    set(r(i), 'Value', 0);
end

function UseBtnCallback(button, ~, inventory, r, object)

for i = 1:4
    if get(r(i),'Value')
        break
    end
end

%% CHECK INVENTORY IF THIS OPTION IS AVAILABLE
N = [sum(inventory == 1), sum(inventory == 2), sum(inventory == 3)];
ok = ( (i < 4) && sum(inventory == i) >= 3 ) || ( (i == 4) && all(N) );

if ~ok
    uiwait(msgbox('You don''t have these cards.'))
    return
end

set(object, 'UserData', i);
uiresume(get(button, 'Parent')) %10
delete(get(button, 'Parent'))


text:
function [ x, seed ] = pareto_sample ( a, b, seed )

%*****************************************************************************80
%
%% PARETO_SAMPLE samples the Pareto PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real A, B, the parameters of the PDF.
%    0.0 < A.
%    0.0 < B.
%
%    Input, integer SEED, a seed for the random number generator.
%
%    Output, real X, a sample of the PDF.
%
%    Output, integer SEED, an updated seed for the random number generator.
%
  [ cdf, seed ] = r8_uniform_01 ( seed );

  x = pareto_cdf_inv ( cdf, a, b );

  return
end


text:
%kkimpulse 'Generate Object Containing Impulse Value Data'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kimpulse.pane file
%
% Parameters:
% Integer: wsize 'Width ', default: 512: 'Width of impulse value data'
% Integer: wnum 'Num. along Width ', default: 1: 'Number of impulses generated along the width dimension'
% Integer: hsize 'Height ', default: 512: 'Height of impulse value data'
% Integer: hnum 'Num. along Height ', default: 1: 'Number of impulses generated along the height dimension'
% Integer: dsize 'Depth ', default: 1: 'Depth of impulse value data'
% Integer: dnum 'Num. along Depth ', default: 1: 'Number of impulses generated along the depth dimension'
% Integer: tsize 'Time ', default: 1: 'Time of impulse value data'
% Integer: tnum 'Num. along Time ', default: 1: 'Number of impulses generated along the time dimension'
% Integer: esize 'Elements ', default: 1: 'Element dimension of impulse value data'
% Integer: enum 'Num. along Elements ', default: 1: 'Number of impulses generated along the element dimension'
% Integer: wsp 'Width Spacing ', default: 256: 'Spacing between two impulses along the width dimension'
% Integer: woff 'Width Offset ', default: 0: 'Offset of first impulse along width dimension'
% Integer: hsp 'Height Spacing ', default: 256: 'Spacing between two impulses along the height dimension'
% Integer: hoff 'Height Offset ', default: 0: 'Offset of first impulse along height dimension'
% Integer: dsp 'Depth Spacing ', default: 1: 'Spacing between two impulses along the depth dimension'
% Integer: doff 'Depth Offset ', default: 0: 'Offset of first impulse along depth dimension'
% Integer: tsp 'Time Spacing ', default: 1: 'Spacing between two impulses along the time dimension'
% Integer: toff 'Time Offset ', default: 0: 'Offset of first impulse along time dimension'
% Integer: esp 'Element Spacing ', default: 1: 'Spacing between two impulses along the element dimension'
% Integer: eoff 'Element Offset ', default: 0: 'Offset of the first impulse along the element dimension'
% OutputFile: o 'Output', required: 'Output file containing impulse value data'
%
% Example: o = kkimpulse( {'wsize',512;'wnum',1;'hsize',512;'hnum',1;'dsize',1;'dnum',1;'tsize',1;'tnum',1;'esize',1;'enum',1;'wsp',256;'woff',0;'hsp',256;'hoff',0;'dsp',1;'doff',0;'tsp',1;'toff',0;'esp',1;'eoff',0;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kimpulse - Generate Object Containing Impulse Value Data
%
%  DESCRIPTION
% .I kimpulse
% creates a data object with impulses in the value segment. The dimension of the
% object is Width * Height * Depth * Time * Elements. The data type of the
% value segment can be \fBbit, byte, unsigned byte, short, unsigned short,
% integer, unsigned integer, long, unsigned long, float, double, complex"
% and \fBdouble complex".
%
% The value assumed to each impulse can be specified (-fgreal and -fgimag). Both
% the real and imaginary component of the value assumed by the impulse, are
% accepted but the imaginary value is used only when the output type is
% complex or double complex. The value assumed by the background is
% specified by the -bgreal and -bgimag variables. Like the impulse value, the
% imaginary background value is used only when the output type is complex or
% double complex.
%
% The spacing (period) of the impulses can be specified for each of the 5
% dimensions
% of the output object (-wsp -hsp -dsp -tsp & -esp). The number of impulses
% along each dimension can also be specified (-wnum -hnum -dnum -tnum & -enum).
% This parameter is useful if impulses are not desired beyond a certain point in
% each dimension. If the number of impulses specified is greater than the number
% obtained by dividing the size of the object by the spacing between impulses
% then the latter denotes the number of impulses along a dimension.
%
% It is also possible to specify an offset for each of the 5 dimensions. The
% first impulse is generated relative to the offset value specified by the
% variables -woff -hoff -doff -toff -eoff. An error message is generated if
% the offset specified is greater than the size of that dimension.
%
%
%
%  EXAMPLES
% % kimpulse -wsize 512 -hsize 512 -w_off 255 -h_off 255 -w_num 1 -h_num 1 -o example
%
% creates an image example of size 512x512 with an impulse of value 255 in the
% center. The background has the value 0.
%
% % kimpulse -wsize 512 -hsize 512 -w_off 255 -h_off 255 -w_num 2 -h_num 2 -wsp 10 -hsp 20 -o exampl -fgreal 1.0 -bgreal 0.0 -fgimag 0.0 -bgimag 0.5 -type complex
%
% creates a COMPLEX image example of size 512x512 with four impulses of
% value (1.0,0.0). The background has the value (0.0,0.5). The impulses appear
% as an array with one corner at (255,255), with spacing (period) in the W
% direction of 10 and in the H direction of 20.
%
%  "SEE ALSO"
% kgsin(1)
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkimpulse(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kkimpulse(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'wsize', 512;'wnum', 1;'hsize', 512;'hnum', 1;'dsize', 1;'dnum', 1;'tsize', 1;'tnum', 1;'esize', 1;'enum', 1;'wsp', 256;'woff', 0;'hsp', 256;'hoff', 0;'dsp', 1;'doff', 0;'tsp', 1;'toff', 0;'esp', 1;'eoff', 0;'o', '__output'};
maxval={2,2,2,2,2,2,2,2,2,2,2,1,2,1,2,1,2,1,2,1,0};
minval={2,2,2,2,2,2,2,2,2,2,2,1,2,1,2,1,2,1,2,1,0};
istoggle=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0];
was_set=istoggle * 0;
paramtype={'Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','Integer','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; 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 'kimpulse"  '],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function [R]=hist2res(H,fun)
% Evaluates Histogram data
% [R]=hist2res(H)
%
% [y]=hist2res(H,fun)
%	estimates fun-statistic
%
% fun	'mean'	mean
%	'std'	standard deviation
%	'var'	variance
%	'sem'	standard error of the mean
%	'rms'	root mean square
%	'meansq' mean of squares
%	'sum'	sum
%	'sumsq'	sum of squares
%	'CM#'	central moment of order #
%	'skewness' skewness
%	'kurtosis' excess coefficient (Fisher kurtosis)
%
% see also: NaN/statistic
%
% REFERENCES:
% [1] C.L. Nikias and A.P. Petropulu "Higher-Order Spectra Analysis" Prentice Hall, 1993.
% [2] C.E. Shannon and W. Weaver "The mathematical theory of communication" University of Illinois Press, Urbana 1949 (reprint 1963).
% [3] http://www.itl.nist.gov/
% [4] http://mathworld.wolfram.com/

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

%	$Id: hist2res.m 2202 2009-10-27 12:06:45Z schloegl $
%	Copyright (c) 1996-2002,2006 by Alois Schloegl <a.schloegl@ieee.org>
%    	This is part of the BIOSIG-toolbox http://biosig.sf.net/

if strcmp(H.datatype,'HISTOGRAM')

elseif strcmp(H.datatype,'qc:histo')
	HDR = H;
	if isfield(H,'THRESHOLD'),
		TH  = H.THRESHOLD;
	else
		TH = repmat([-inf,inf],HDR.NS,1);
	end;
	HIS = H.HIS;

	% remove overflowing samples
	HIS.N = sumskipnan(HIS.H);
	for k = 1:size(HIS.H,2);
		t = HIS.X(:,min(k,size(HIS.X,2)));
		HIS.H(xor(t<=min(TH(k,:)), t>=max(TH(k,:))),k) = 0;
	end;
	Nnew = sumskipnan(HIS.H);
	R.ratio_lost = 1-Nnew./HIS.N;
	HIS.N = Nnew;

	% scale into physical values
	if H.FLAG.UCAL,
		%t = HIS.X;
		%for k=1:length(HDR.InChanSelect),
		%	HIS.X(:,k) = t(:,min(size(t,2),k))*HDR.Calib(k+1,k)+HDR.Calib(1,k);
		%end;
		HIS.X = [ones(size(HIS.X,1),1),repmat(HIS.X,1,size(HIS.H,2)./size(HIS.X,2))]*H.Calib;
	end;
	H = HIS;
else
        fprintf(2,'ERROR: arg1 is not a histogram\n');
        return;
end;
if nargin<2, fun=[]; end;

global FLAG_implicit_unbiased_estimation;
%%% check whether FLAG was already defined
if exist('FLAG_implicit_unbiased_estimation')~=1,
	FLAG_implicit_unbiased_estimation=[];
end;
%%% set DEFAULT value of FLAG
if isempty(FLAG_implicit_unbiased_estimation),
	FLAG_implicit_unbiased_estimation=logical(1);
end;

sz 	= size(H.H)./size(H.X);
R.N 	= sumskipnan(H.H,1);
R.SUM 	= sumskipnan(H.H.*repmat(H.X,sz),1);
R.SSQ 	= sumskipnan(H.H.*repmat(H.X.*H.X,sz),1);
%R.S3P 	= sumskipnan(H.H.*repmat(H.X.^3,sz),1);	% sum of 3rd power
R.S4P 	= sumskipnan(H.H.*repmat(H.X.^4,sz),1);	% sum of 4th power
%R.S5P 	= sumskipnan(H.H.*repmat(H.X.^5,sz),1);	% sum of 5th power

R.MEAN	= R.SUM./R.N;
R.MSQ   = R.SSQ./R.N;
R.RMS	= sqrt(R.MSQ);
R.SSQ0  = R.SSQ-R.SUM.*R.MEAN;		% sum square of mean removed

if FLAG_implicit_unbiased_estimation,
    n1 	= max(R.N-1,0);			% in case of n=0 and n=1, the (biased) variance, STD and STE are INF
else
    n1	= R.N;
end;

R.VAR  	= R.SSQ0./n1;	     		% variance (unbiased)
R.STD  	= sqrt(R.VAR);		     	% standard deviation
R.SEM  	= sqrt(R.SSQ0./(R.N.*n1)); 	% standard error of the mean
R.SEV	= sqrt(n1.*(n1.*R.S4P./R.N+(R.N.^2-2*R.N+3).*(R.SSQ./R.N).^2)./(R.N.^3)); % standard error of the variance
R.Coefficient_of_variation = R.STD./R.MEAN;

R.CM2	= R.SSQ0./n1;
x       = repmat(H.X,sz) - repmat(R.MEAN,size(H.X,1),1);
R.CM3 	= sumskipnan(H.H.*(x.^3),1)./n1;
R.CM4 	= sumskipnan(H.H.*(x.^4),1)./n1;
%R.CM5 	= sumskipnan(H.H.*(x.^5),1)./n1;

R.SKEWNESS = R.CM3./(R.STD.^3);
R.KURTOSIS = R.CM4./(R.VAR.^2)-3;
R.MAD = sumskipnan(H.H.*abs(x),1)./R.N; % mean absolute deviation

H.PDF = H.H./H.N(ones(size(H.H,1),1),:);
status=warning('off');
R.ENTROPY = -sumskipnan(H.PDF.*log2(H.PDF),1);
warning(status);
R.QUANT = repmat(min(diff(H.X,[],1)),1,size(H.H,2)/size(H.X,2));
R.MAX = max(H.X);
R.MIN = min(H.X);
R.RANGE = R.MAX-R.MIN;

if ~isempty(fun),
        fun=upper(fun);
        if strncmp(fun,'CM',2)
                oo = str2double(fun(3:length(fun)));
                R = sumskipnan(H.PDF.*(x.^oo),1);
    	else
		R = getfield(R,fun);
	end;
end;


text:
function c = diff(c)
   % DIFF differentiate each trace.
   %
   % C = DIFF(C) differentiate each trace through a call to WAVEFORM/DIFF.
   % See WAVEFORM/DIFF for details

   % Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
   % $Date$
   % $Revision$

   c.traces = diff(c.traces);
end

author: geoscience-community-codes

repo: GISMO


text:
function [vec,lmax] = SHMatrix2Vec(A,B)

% [vec,lmax] = SHMatrix2Vec(A,B)
%
% Converts the two coefficient matrices, A and B, to the real
% spherical harmonic coefficient vector. A contains coefficients
% by cos(m*phi) and B contains coefficients by sin(m*phi).
% Inverse of SHMatrix2Vec.

lmax = size(A,1)-1;
vec = SHCreateVec(lmax);

j=0;
for l=0:lmax
    j=j+1;
    vec(j)=A(l+1,1);
    for m=1:l
        j=j+1;
        vec(j)=A(l+1,m+1);
        j=j+1;
        vec(j)=B(l+1,m+1);
    end
end


text:
% mff_exportinfo - export MFF 'info.xml' file from EEGLAB structure
%
% Usage:
%   mff_exportinfo(EEG, mffFile);
%
% Inputs:
%  EEG     - EEGLAB structure
%  mffFile - filename/foldername for the MFF file (MFF file/folder must
%            already exist)

% This file is part of mffmatlabio.
%
% mffmatlabio 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.
%
% mffmatlabio 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 mffmatlabio.  If not, see <https://www.gnu.org/licenses/>.

function EEG = mff_exportinfo(EEG, mffFile)

p = fileparts(which('mff_importsignal.m'));
warning('off', 'MATLAB:Java:DuplicateClass');
javaaddpath(fullfile(p, 'MFF-1.2.2-jar-with-dependencies.jar'));
warning('on', 'MATLAB:Java:DuplicateClass');

mfffactorydelegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
mfffactory         = javaObject('com.egi.services.mff.api.MFFFactory', mfffactorydelegate);

infoType = javaObject('com.egi.services.mff.api.MFFResourceType', javaMethod('valueOf', 'com.egi.services.mff.api.MFFResourceType$MFFResourceTypes', 'kMFF_RT_Info'));
if mfffactory.createResourceAtURI(fullfile(mffFile, 'info.xml'), infoType)
    fprintf('Info.xml file created successfully\n');
else
    fprintf('Info.xml ressource already exist, overwriting\n');
end
info = mfffactory.openResourceAtURI( fullfile(mffFile, 'info.xml'), infoType);

info.setMFFVersion(3);
if ~isfield(EEG.etc, 'recordingtime')
    error('Unknow record time');
end
begTime = mff_encodetime(EEG.etc.recordingtime, EEG.etc.timezone);
info.setRecordTime(begTime);
info.saveResource();


text:
function [major,minor,patchnum,extra]=iso2meshver
%
% [major,minor,patchnum,extra]=iso2meshver
%      or
% v=iso2meshver
%
% get the version number of iso2mesh toolbox
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%
% output:
%    if you ask for a single output:
%      v: a string denotes the current version number; the string is
%       typically in the following format: "major.minor.patch-extra"
%       where major/minor/patch are typically integers, and extra can
%       be an arbitrary string and is optional
%    if you ask for 4 outputs:
%     [major,minor,patchnum,extra] are each field of the version string
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

major=1;
minor=5;
patchnum=0;
extra='$Rev:: 403 $';
extra=regexprep(extra,'[\s$:]', '');

iso2meshvstr=sprintf('%d.%d.%d',major,minor,patchnum);
if(~isempty(extra))
   iso2meshvstr=[iso2meshvstr '-' extra];
end

if(nargout==0)
   fprintf(1,'iso2mesh toolbox version: %s\n',iso2meshvstr);
   clear major;
elseif(nargout==1)
   major=iso2meshvstr;
elseif(nargout~=4)
   error('you need to return either 1 or 4 output variables');
end

repo: REST


text:
addpath("utils\")

config202107311 % config file

n = 100; % run n times
result = zeros(n, 4);

for i = 1:n
    clc
    disp(['i = ' num2str(i)]);
    [result(i,1:2), result(i,3:4)]= wheelslam_func(paras);

end

path   = paras.datapath;
%write_bin([path 'finalresults_' num2str(paras.NPARTICLES) '.bin'], result);

% fp_res  = fopen([path 'finalresultsall.txt'],'a+');
% s_curt  = datestr(now);
% format longG
% fprintf(fp_res,'%s\n', s_curt);
% fprintf(fp_res,'Particles = %d NEFFECTIVE = %d\n', paras.NPARTICLES, paras.NEFFECTIVE);
% fprintf(fp_res,'Gridlen = %.1f mode = %d\n', paras.gridlen, paras.mode);
% fprintf(fp_res,'Disstd    = %.5f  Phistd  = %.5f \n', paras.sigmaDis_scale, paras.sigmaPhi);
% fprintf(fp_res,'RollSampleDis = %.1f    RollSeqDim = %d\n', paras.sampleDis, paras.rollSeqdimension);
% fprintf(fp_res,'RollSeqWindow = %d  CorrCoefThr = %.1f  CorrCoefNumThr = %d\n',paras.conRevisitNumThr,paras.corrCoefThr,paras.corrCoefNumThr);
%
% fprintf(fp_res,'%s\n', 'Mean          [Hor. pos.     heading]');
% fprintf(fp_res,'Wheel-SLAM       %.2f          %.2f\n', mean(result(1:i,1)), mean(result(1:i,2)));
% fprintf(fp_res,'Wheel-INS       %.2f        %.2f\n\n', result(1,3), result(1,4));

figure,
subplot(2,1,1),
plot(result(1:i,3), 'LineWidth', 1.5);hold on;plot(result(1:i,1), 'LineWidth', 1.5);
title([num2str(paras.experiencetime) '-' num2str(paras.experiencenum)]);
ylabel('Hor. RMSE(m)'), xlabel('Test No.');box on, grid on;
legend('Wheel-INS','Wheel-SLAM');
set(gca,'fontsize',10,'fontname','Times');
subplot(2,1,2),
plot(result(1:i,4), 'LineWidth', 1.5);hold on;plot(result(1:i,2), 'LineWidth', 1.5);
ylabel('Heading RMSE(deg)'), xlabel('Test No.');box on, grid on;
set(gca,'fontsize',10,'fontname','Times');

repo: Wheel-SLAM


text:
classdef GemAxesPanel < GemPanel
    % GemAxesPanel GEM control for Matlab panel containing axes
    %
    %     GemAxesPanel inherits from GemPanel, and inclues a GemAxes object
    %
    %
    %     Licence
    %     -------
    %     Part of GEM. https://github.com/tomdoel/gem
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = protected)
        Axes
    end

    properties (SetAccess = protected)
        VisualisationLabel
    end

    methods
        function obj = GemAxesPanel(parent)
            obj = obj@GemPanel(parent);

            obj.Axes = GemAxes(obj);
            obj.AddChild(obj.Axes);
            obj.BackgroundColour = 'white';
        end

        function CreateGuiComponent(obj, position)
            CreateGuiComponent@GemPanel(obj, position);
        end

        function Resize(obj, position)
            Resize@GemPanel(obj, position);
            obj.Axes.Resize(position);
        end

        function handle = GetRenderAxes(obj)
            % Returns a handle to the GEM Axes
            handle = obj.Axes;
        end

        function Clear(obj)
            % Clears the axes and resets the render panel
            obj.GetRenderAxes.Clear;
            obj.VisualisationLabel = [];
        end

        function SetVisualisationLabel(obj, label)
            obj.VisualisationLabel = label;
        end

        function frame = Capture(obj, image_size, orientation)
            drawnow;

            origin = [0.5, 0.5, 0.5];
            image_limit = origin + image_size;
            xlim_image = [min(origin), max(image_limit)];
            ylim_image = xlim_image;

            frame = obj.Axes.Capture(xlim_image, ylim_image);
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
clc;
clear all;
for i=1:200
    I=imread(strcat('\',num2str(i),'.tif'));
    Imatch_L=imread(strcat('',num2str(i),'.tif'));

    I1=I(:,:,1);
    I2=I(:,:,2);
    I3=I(:,:,3);
    I4=I(:,:,4);

    Imatch_1=imresize(Imatch_L(:,:,1),4);
    Imatch_2=imresize(Imatch_L(:,:,2),4);
    Imatch_3=imresize(Imatch_L(:,:,3),4);
    Imatch_4=imresize(Imatch_L(:,:,4),4);

    Jmatch1=imhist(Imatch_1);
    Iout1=histeq(I1,Jmatch1);

    Jmatch2=imhist(Imatch_2);
    Iout2=histeq(I2,Jmatch2);

    Jmatch3=imhist(Imatch_3);
    Iout3=histeq(I3,Jmatch3);

    Jmatch4=imhist(Imatch_4);
    Iout4=histeq(I4,Jmatch4);

    I_out=cat(3,Iout1,Iout2,Iout3,Iout4);

    imwrite(I_out,strcat('',num2str(i),'.tif'))

end

author: thfylsty


text:
% MatrixUser, a multi-dimensional matrix analysis software package
% https://sourceforge.net/projects/matrixuser/
%
% The MatrixUser is a matrix analysis software package developed under Matlab
% Graphical User Interface Developing Environment (GUIDE). It features
% functions that are designed and optimized for working with multi-dimensional
% matrix under Matlab. These functions typically includes functions for
% multi-dimensional matrix display, matrix (image stack) analysis and matrix
% processing.
%
% Author:
%   Fang Liu <leoliuf@gmail.com>
%   University of Wisconsin-Madison
%   Aug-30-2014

% link silder bar and edit for matrix dimension
% update current matrix according to dimension pointer

function MU_linkSliderEditDim(Temp,Event,active_handle,slider_handle,edit_handle,dimFlag)
handles = guidata(active_handle);

% sync silder bar and edit
switch get(active_handle,'Style')
    case 'slider'
        set(edit_handle,'String',num2str(round(get(slider_handle,'Value'))));
        set(slider_handle,'Value',round(get(slider_handle,'Value')));
    case 'edit'
        editValue = round(str2double(get(edit_handle,'String')));
        if editValue<=get(slider_handle,'Max') & editValue>=get(slider_handle,'Min')
            set(slider_handle,'Value',editValue);
            set(edit_handle,'String',editValue);
        else
            set(edit_handle,'String',num2str(round(get(slider_handle,'Value'))));
        end
end

% update current display matrix
handles=MU_update_image(handles.Matrix_display_axes,{handles.TMatrix,handles.Mask},handles,dimFlag);
guidata(handles.MU_matrix_display, handles);

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab