text:
function c = rdivide(a,b)
% function C=rdivide(A,B)
%
% DESCRIPTION
%   Element-by-element right division
%
% INPUTS
%   A: polynomial
%   B: matrix of constants
%
% OUTPUTS
%   C: polynomial, the result of division.
%
% SYNTAX
%   C= A./B
%     A and B must have the same dimensions unless one
%     is a scalar.  Scalars can be divided with anything.
%   C = rdivide(A,B)
%     Function-call form

% 10/22/2002: PJS  Initial Coding

% Promote a to polynomial
a = polynomial(a);
sza = size(a);

% Promote b to polynomial
b = polynomial(b);
szb = size(b);

if isempty(a) || isempty(b)

    if isempty(a) && all(szb==[1 1])
        % empty./scalar = empty(sza)
        c=polynomial(zeros(sza));
        return;
    elseif isempty(b) && all(sza==[1 1])
        % scalar./empty = empty(szb)
        c=polynomial(zeros(szb));
        return;
    elseif all(sza==szb)
        c=polynomial(zeros(sza));
        return;
    else
        error('Matrix dimensions must agree.');
    end

elseif all(sza==szb) || all(sza==[1 1]) || ...
        all(szb==[1 1])

    % Matrix./Matrix
    degidx = find(b.degmat);
    if ~isempty(degidx)
        error('B must be a constant.');
    end
    b = combine(b);
    bcoef = reshape(b.coefficient,b.matdim);
    c = times(a,1./bcoef);
else

    error('Matrix dimensions must agree');
end

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


text:
%% =======================================================================
%  ARDrone Simulation Example: Simulation Baseline Model
%  =======================================================================
%
%  The simulation is used to see the reposnse of the ARDrone to different
%  commands and  inputs.
%  Authors:
%       David Escobar Sanabria -> descobar@aem.umn.edu
%       Pieter J. Mosterman -> pieter.mosterman@mathworks.com
%  =======================================================================

%%
%  Cleaning workspace
bdclose all;
clear all;
clc

%%
% Adding ARDrone library path
addpath ../lib;
%% Simulation parameters

% Flight management system sample time. This is the sample time at which
% the control law is executed.
FMS.Ts = 0.065;

% Time delay due to communication between drone and host computer
timeDelay = FMS.Ts*4;

%% Vehicle model based on linear dynamics

% Loading state space representation of vehicle dynamics
setupARModel;

%%
% Loading list of waypoints
waypoints = getWaypoints() ;

%%
% Simulation time
simDT = 0.005 ;

%%
% Loading Simulink model of ARDrone
ARDroneBaseSim ;

author: Sable

repo: mcbench-benchmarks


text:
function pred = ml_predict(trials, model)
% Make predictions for some data, using some (previously learned) model.
% Prediction = ml_predict(Trials, Model)
%
% This function makes predictions for some given data and a supplied model, as learned using
% ml_train. It dispatches to the appropriate ml_predict* function, depending on what was used to
% train the model.
%
% For each of the N supplied trials, one prediction is produced in the output, which may be in a
% number of different formats, depending on the parameters of the model (which in turn depends on
% the learning function used, its parameters, and the form of the target variables in the training
% data).
%
% The most common format of the prediction is discrete probability distributions per trial, which is
% the output produced by most classifiers. In this case, structed as a 3-element cell array {'disc',
% Probabilities, Classes}, the distributions are returned as a [#Trials x #Classes] matrix in the
% Probabilities entry, which contains the probability for each of a set of classes, per trial. The
% set of classes is associated with set of target values (e.g. -1,+1, or 3,7,5) by the Classes cell
% entry, which is size [#Classes x 1], and is sorted in the same order as in the probability
% distributions (in ascending order of target values), so that Prediction{2}*Prediction{3} would
% give a probability-weighted sum of the possible target values). This format can be mapped into the
% "usual" format of most likely target value per trial via the expression
% Prediction{3}(argmax(Prediction{2}')).
%
% For regression, the most common format is the [NxD] (usually D=1) format of one point estimate per
% trial, since only very few methods can give a posterior probability distribution right now. Other
% formats are primarily provided for more advanced predictors which can give regression outputs as a
% parametric (or even non-parametric) probability distribution per trial, as {distrib,NxP}, or in an
% entirely custom format, as {'struct',{N}}.
%
% In:
%   Trials   : data, [NxF] array (N = number of training instances,F = number of feature dimensions)
%              or in special cases a [UxVxN] array (N... number of training instances, U,V ...
%              number of rows/columns of the feature matrices)
%              If not otherwise possible, it is also allowed to pass trials in any custom format to
%              ml_predict, given that the prediction function in question can handle these data.
%
%   Model    : the model to be used for prediction (output of ml_train);
%              when empty, the actual features are returned (passed through).
%
% Out:
%   Prediction : predictions of the model, one for each trial
%                format depends on the chosen Model:
%                  * [Nx1] : classification or one-dimensional regression outputs (point estimates)
%                  * [NxD] : d-dimensional regression outputs (point estimates)
%                  * {'disc', [NxC], [Cx1]}: discrete probabilities for C classes in probabilistic
%                    classification, the last array determines the assigment from class indices (in
%                    NxC) to the output labels, such that [NxC]*[Cx1] is the expected output
%                  * {distrib, NxP}: posterior probability distributions in probabilistic
%                    regression, with distrib being one of:
%                    'bino','chi2','exp','ev','f','gam','gev','gp','geo','hyge','logn','nbin','ncf',
%                    'nct','ncx2','norm','poiss','rayl','t','unif','unid','wbl' with the
%                    appropriate interpretation under pdf(), and P the number of parameters to pdf()
%                  * {distrib, {N}}: posterior probability distributions, with distrib being either
%                    'mvn', for mvnpdf(), or any function handle that can accept parameter sets of
%                    the form distrib(X,Prediction{2}{i}{:});
%                  * {'struct', {N}}: structured predictions
%
% See also:
%   ml_train
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-04-03

if isempty(model)
    pred = trials;
else
    pred = feval(['ml_predict' model.args.arg_selection],trials,model.model);

    % post-process predictions
    if iscell(pred) && length(pred) == 3 && strcmp(pred{1},'disc')
        % sort discrete distributions
        [classes,inds] = sort(pred{3});
        pred = {pred{1} pred{2}(:,inds) classes};
    end
end

repo: REST


text:
function Flicker_Caclulation_function (endval,endval1,Sn,Sk,n,Un,Fn,i,Kp,Ki,F_Sample,Simulation_dynamic_cut_time,N10,N120,U1N_NS,U2N_NS,U3N_NS,I1_NS,I2_NS,I3_NS,time)
% Initial Input data for calculating a complete flicker valuses of a
% meassured data.
% endval1 is the number of calculation to be done (for different Grid phase
% angle
% Sn is Appparent power in kW
% Sk is Short circuit apparent power in MW
% n is % the rate between Sfic/Sn as defined by IEC norm
% Un is Nominal Voltage where the measurment were done in V.
% Fn is Nominal Frequency of the grid were the measurment were done in Hz.
% i is a selector between i = 1 Continuous operation and i = 2 and switching operation.
% Kp Proportional Gain Factor of the PLL Block.
% Ki Integral Gain Factor of the PLL Block.
% F_Sample is Sampling Frequencz used in recording the measurments in S.
% Simulation_dynamic_cut_time is the estimated time needed by the PI
% controller when calculating the Frequency. (this simulation dynamic time
% need to be removed)
% N10 is Number of switching operation with in 10 min (As given in IEC norm)
% N120 is Number of switching operation with in 2 h (As given in IEC norm)
% dataname is the measured data name that should be analyized and it should
% have the format .mat and need to contain the measured three phase
% voltages and current signals with there time axie.
% this file assume that the measured three pahse voltage and current are identical and have the same:
% 1- Sampling rate (time intervals)
% 2- data length (Which is according to the IEC 10 min of measured data)
% This function will also call the Flickermeter simulater (File ID: #24423
% by Patrik Jourdan 12 Jun 2009 (Updated 11 Jan 2010)) in order to
% calculate the flicker values calculated by the Fictitious grid module (so
% called Flickermeter6140021_new_GL_Final_3ph.mdl).
% Please refer to the PDF documentation file in order to get more
% information on how this function works
Sfic = (n*Sn)/1000;% Fictitious Short cicuit apparent power grid in MW
P_st_fic_complete_ave = 0;
P_st_complete_ave = 0;
P_lt_complete_ave = 0;
if i == 2
    P_st_fic_complete = zeros(1,endval);
    P_st_complete = zeros(1,endval);
    P_lt_complete = zeros(1,endval);
    kf_psyk_complete = zeros(1,endval);
    ku_psyk_complete = zeros(1,endval);
    kf_psyk_complete_ave = 0;
    ku_psyk_complete_ave = 0;
    save ('Initial values','time','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','P_st_fic_complete','P_st_complete','P_lt_complete','kf_psyk_complete','ku_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','kf_psyk_complete_ave','ku_psyk_complete_ave')
elseif i == 1
    P_st_fic_complete = zeros(1,endval);
    P_st_complete = zeros(1,endval);
    P_lt_complete = zeros(1,endval);
    c_psyk_complete = zeros(1,endval);
    c_psyk_complete_ave = 0;
    save ('Initial values','time','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','P_st_fic_complete','P_st_complete','P_lt_complete','c_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','c_psyk_complete_ave')
else
end
clear
load 'Initial values'
%-------------------------------------------------------------------------------------End--------------------------------------------------------------------------------------------
for jj=1:endval1
    prompt4 = {'Please Enter The new phase angle Alpha in degree'};
    name = 'Initial Input data';
    numlines = 1;
    defaultanswer4 = {'30'};
    answer4 = inputdlg(prompt4,name,numlines,defaultanswer4);
    Alpha = str2double(answer4{1});
    if jj>1 && i == 2
        save ('Initial values','time','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','j','jj','Sequence_Path','Searchdir','P_st_fic_complete','P_st_complete','P_lt_complete','kf_psyk_complete','ku_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','kf_psyk_complete_ave','ku_psyk_complete_ave')
        clear
        load 'Initial values'
    elseif jj>1 && i == 1
        save ('Initial values','time','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','j','jj','Alpha','P_st_fic_complete','P_st_complete','P_lt_complete','c_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','c_psyk_complete_ave')
        clear
        load 'Initial values'
    end
    for j=1:endval
        if i == 2
            save ('Initial values','time','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','j','jj','Alpha','P_st_fic_complete','P_st_complete','P_lt_complete','kf_psyk_complete','ku_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','kf_psyk_complete_ave','ku_psyk_complete_ave')
            I1_NS = [time' I1_NS'];
            I2_NS = [time' I2_NS'];
            I3_NS = [time' I3_NS'];
            U1_NS = [time' U1N_NS'];
            U2_NS = [time' U2N_NS'];
            U3_NS = [time' U3N_NS'];
            savenamerowdata = sprintf('Input_Data_Matlab_%d',j);
            save (savenamerowdata,'I1_NS','I2_NS','I3_NS','U1_NS','U2_NS','U3_NS','j','i');
            loadfile = [savenamerowdata];
            load ([loadfile '.mat'])
            % Input info for the Fictitious grid Module & Flickermeter
            % afterword and the name of the saved result file
            Tp = eval(sprintf('Simulation_Time_%d',j));
            Fs = 1/F_Sample; %in Hz & must be greater than 2000 Hz
            File_save_name = sprintf('Final_results_%d_%d',j,Alpha);
            filesavename = File_save_name;
            flicker_Calculation_complete (j,i,n,Sk,Sn,Alpha,Un,Kp,Ki,Fn,F_Sample,Tp,Simulation_dynamic_cut_time,N10,N120,File_save_name);
            loadfile_final = [File_save_name];
            load ([loadfile_final '.mat'])
            P_st_fic_complete(j) = P_st_fic_ave;
            P_st_complete(j) = Pst_ave;
            P_lt_complete(j) = Plt_ave;
            kf_psyk_complete(j) = kf_psyk_ave;
            ku_psyk_complete(j) = ku_psyk_max_ave;
            P_st_fic_complete_ave = mean(P_st_fic_complete);
            P_st_complete_ave = mean(P_st_complete);
            P_lt_complete_ave = mean(P_lt_complete);
            kf_psyk_complete_ave = mean(kf_psyk_complete);
            ku_psyk_complete_ave = mean(ku_psyk_complete);
            complet_results = sprintf('Complete_Results_%d',Alpha);
            save (complet_results,'P_st_fic_complete','P_st_complete','P_lt_complete','kf_psyk_complete','ku_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','kf_psyk_complete_ave','ku_psyk_complete_ave');
            save ('Initial values','time','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','j','jj','Alpha','P_st_fic_complete','P_st_complete','P_lt_complete','kf_psyk_complete','ku_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','kf_psyk_complete_ave','ku_psyk_complete_ave')
            clear
            load 'Initial values'
        elseif i == 1
            save ('Initial values','time','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','j','jj','Alpha','P_st_fic_complete','P_st_complete','P_lt_complete','c_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','c_psyk_complete_ave')
            load('Initial values.mat')
            I1_Ns = [time' I1_NS'];
            I2_Ns = [time' I2_NS'];
            I3_Ns = [time' I3_NS'];
            U1_NS = [time' U1N_NS'];
            U2_NS = [time' U2N_NS'];
            U3_NS = [time' U3N_NS'];
            Tp = time(end);
            %Fs = 1/F_Sample;
            %Simulation_Time = Cut_Time;
            savenamerowdata = sprintf('Input_Data_Matlab_%d',j);
            save (savenamerowdata,'I1_Ns','I2_Ns','I3_Ns','U1_NS','U2_NS','U3_NS','j','i','Tp');
            loadfile = [savenamerowdata];
            load ([loadfile '.mat'])
            % Input info for the Fictitious grid Module & Flickermeter
            % afterword and the name of the saved result file
            File_save_name = sprintf('Final_results_%d_%d',j,Alpha);
            flicker_Calculation_complete (j,i,n,Sk,Sn,Alpha,Un,Kp,Ki,Fn,F_Sample,Tp,Simulation_dynamic_cut_time,N10,N120,File_save_name,I1_Ns,I2_Ns,I3_Ns,U1_NS,U2_NS,U3_NS);
            loadfile_final = [File_save_name];
            load ([loadfile_final '.mat'])
            P_st_fic_complete(j) = P_st_fic_ave;
            P_st_complete(j) = Pst_ave;
            P_lt_complete(j) = Plt_ave;
            c_psyk_complete(j) =  cpsyk_ave;
            P_st_fic_complete_ave = mean(P_st_fic_complete);
            P_st_complete_ave = mean(P_st_complete);
            P_lt_complete_ave = mean(P_lt_complete);
            c_psyk_complete_ave = mean(c_psyk_complete);
            complet_results = sprintf('Complete_Results_%d',Alpha);
            save (complet_results,'P_st_fic_complete','P_st_complete','P_lt_complete','c_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','c_psyk_complete_ave');
            save ('Initial values','time','endval','U1N_NS','U2N_NS','U3N_NS','I1_NS','I2_NS','I3_NS','endval1','Sn','Sk','n','Sfic','Un','Fn','i','Kp','Ki','F_Sample','Simulation_dynamic_cut_time','N10','N120','j','jj','Alpha','P_st_fic_complete','P_st_complete','P_lt_complete','c_psyk_complete','P_st_fic_complete_ave','P_st_complete_ave','P_lt_complete_ave','c_psyk_complete_ave')
            clear
            load 'Initial values'
        else
        end
        button = questdlg('The next Row Data calculation is about to start do you want to finish running this M-file?', ...
            'Exit Dialog','Yes','No','No');
        switch button
            case 'Yes',
                disp('Exiting MATLAB');
                %Save variables to matlab.mat
                save
            case 'No',
                quit cancel;
        end
    end
    button = questdlg('The next calculation for a new phase angle of the fictious grid Alpha is about to start do you want to finish running this M-file?', ...
        'Exit Dialog','Yes','No','No');
    switch button
        case 'Yes',
            disp('Exiting MATLAB');
            %Save variables to matlab.mat
            save
        case 'No',
            quit cancel;
    end
end


text:
function DataSet = prtDataGenFeatureSelection(N, nExtraDims)
%prtDataGenFeatureSelection   Generates some unimodal example data for the prt.
%  DataSet = prtDataGenFeatureSelection
%  The data is distributed:
%       H0: N([0 0 0 0 0 0 0 0 0 0],eye(10))
%       H1: N([0 2 0 1 0 2 0 1 0 2],eye(10))
%
% Syntax: [X, Y] = prtDataGenFeatureSelection(N)
%
% Inputs:
%       N ~ number of samples per class (200)
%
% Outputs:
%   X - 2Nx2 Unimodal data
%   Y - 2Nx1 Class labels
%
% Example:
%   DataSet = prtDataGenFeatureSelection;
%   explore(DataSet)
%
% Other m-files required: none
% Subfunctions: none
% MAT-files required: none
%
% See also: prtDataGenUnimodal

if nargin < 1 || isempty(N);
    nSamples = 200;
else
    nSamples = N;
end

if nargin < 2 || isempty(nExtraDims)
    nExtraDims = 0;
end

mu0 = [0 0 0 0 0 0 0 0 0 0];
mu1 = [0 1 0 .5 0 1 0 .5 0 1]*2;

sigma0 = eye(length(mu0));
sigma1 = eye(length(mu1));
rv(1) = prtRvMvn('mu',mu0,'sigma',sigma0);
rv(2) = prtRvMvn('mu',mu1,'sigma',sigma1);

X = cat(1,draw(rv(1),nSamples),draw(rv(2),nSamples));

if nExtraDims > 0
    rvNoise = prtRvMvn('mu',zeros(1,nExtraDims),'sigma',eye(nExtraDims));

    X = cat(2, X, rvNoise.draw(nSamples*2));
end

Y = prtUtilY(nSamples,nSamples);

DataSet = prtDataSetClass(X,Y,'name',mfilename);

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
function polygons3d(varargin)
%POLYGONS3D Description of functions operating on 3D polygons
%
%   A 3D polygon is simply a set of 3D points (called vertices) which are
%   assumed to be located in the same plane.
%   Several functions are provided for computing basic geometrical
%   parameters (centroid, angles), or intersections with lines or planes.
%
%   See also:
%   polygonArea3d, triangleArea3d, polygonCentroid3d, polygon3dNormalAngle
%   intersectLinePolygon3d, intersectLineTriangle3d, intersectRayPolygon3d
%   clipConvexPolygon3dHP
%   drawPolygon3d, drawPolyline3d, fillPolygon3d
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2008-10-13,    using Matlab 7.4.0.287 (R2007a)
% Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
%kglinexyz 'Create Polylines from ASCII XYZ Data'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros glinexyz.pane file
%
% Parameters:
% InputFile: i 'Input ASCII Data ', required: 'input ASCII data containing polyline points'
% String: name 'Name ', default: 'line': 'object name'
% OutputFile: o 'Output Geometry Object', required: 'output geometry object'
%
% Example: o = kglinexyz(i, {'i','';'name','line';'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% glinexyz - Create Polylines from ASCII XYZ Data
%
%  DESCRIPTION
% .I glinexyz
% will read in an ASCII file of coordinate information and produce a
% series of connected polyline primitives.
%
% The ASCII input should contain blocks of information, where each block
% consists of a number indicating how many vertices will be contained in
% the polyline and then a series of XYZ points, with one for each
% vertex.  The format of the input ASCII file is illustrated below :
%
%
%       number of vertices in first connected polyline
%       X value   Y value   Z value
%       X value   Y value   Z value
%       X value   Y value   Z value
% 	 .         .         .
% 	 .         .         .
% 	 .         .         .
%       X value   Y value   Z value
%       number of vertices in second connected polyline
%       X value   Y value   Z value
% 	 .         .         .
% 	 .         .         .
% 	 .         .         .
%
%
%
% A single connected polyline primitive will be created for each
% successive block of information.  The resulting geometry will not
% contain any color data.  To create colored polyline segments, please
% see "glinecolor."
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% glinecolor
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1996,1997 , The Regents of the University of California.  All rights reserved.
%

function varargout = kglinexyz(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kglinexyz(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'name', 'line';'o', '__output'};
maxval={0,0,0};
minval={0,0,0};
istoggle=[0,1,0];
was_set=istoggle * 0;
paramtype={'InputFile','String','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 'glinexyz"  '],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function out = normest(f)
%NORMEST   Estimate the norm of a SINGFUN.
%   NORMEST(F) returns the NORMEST of the smooth part of a SINGFUN F. Since the
%   function value of a SINGFUN is infinite at -1 and 1 in most of the cases due
%   to the pole(s), NORMEST turn the estimated norm of the smooth part of F.

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

% Call NORMEST() of the smooth part:
out = normest(f.smoothPart);

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function [tim,perm] = visTextons(textons,fb)
% function [tim,perm] = visTextons(textons,fb)

if size(textons,1) ~= numel(fb),
  error('size(textons,1) ~= numel(fb)');
end

[d,k] = size(textons);

% find the max filter size
maxsz = max(size(fb{1}));
for j = 1:d,
  maxsz = max(maxsz,max(size(fb{j})));
end

% compute the linear combinations of filters
tim = cell(k,1);
for i = 1:k,
  tim{i} = zeros(maxsz);
  for j = 1:d,
    f = fb{j} * textons(j,i);
    off = (maxsz-size(f,1))/2;
    tim{i}(1+off:end-off,1+off:end-off) = tim{i}(1+off:end-off,1+off:end-off) + f;
  end
end

% computer permutation order for decreasing L1 norm
norms = zeros(k,1);
for i = 1:k,
  norms(i) = sum(sum(abs(tim{i})));
end
[y,perm] = sort(norms);
perm = flipud(perm);

author: zouchuhang

repo: LayoutNet


text:
function [spec,freqs,A]=parafrep(Rx,N,method,q);
% [spec,freqs]=parafrep(Rx,N,method,q) parametric frequency representation
% of a signal.
%
% Rx     : correlation matrix of size (p+1)x(p+1)
% N      : number of frequency bins between 0 and 0.5
% method : can be either 'ar', 'periodogram', 'capon', 'capnorm', 'lagunas',
%          or 'genlag'.
% q      : parameter for the generalized Lagunas method.
%
% noise=rand(1000,1); signal=filter([1 0 0],[1 1 1],noise);
% figure(1);parafrep(correlmx(signal,2,'hermitian'),128,'AR');title('AR (2)');
% figure(2);parafrep(correlmx(signal,4,'hermitian'),128,'Capon');title('Capon (4)');
% figure(3);parafrep(correlmx(signal,2,'hermitian'),128,'lagunas');title('Lagunas (2)');
% figure(4);parafrep(correlmx(signal,40,'hermitian'),128,'periodogram');title('periodogram (40)');

% F. Auger, july 1998, april 99.

if nargin<1,
 error('At least one parameter required');
elseif nargin==1,
 N=128; method='capon';
elseif nargin==2,
 method='capon';
end;

[Rxrow,Rxcol]=size(Rx);
if (Rxrow ~= Rxcol),
 error('Rx must be a square matrix');
end;

p=Rxrow-1;
freqs=linspace(0,0.5,N);
spec=zeros(N,1);

method=upper(method);
if strcmp(method,'AR'),
 Un=ones(Rxrow,1); Rxm1Un= (Rx\Un);
 P1=real(Un'*Rxm1Un); A=Rxm1Un/P1;
 for ifreq=1:N,
  Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)');
  spec(ifreq)=P1 ./ abs(Z' * A)^2 ;
 end;
elseif strcmp(method,'PERIODOGRAM'),
 for ifreq=1:N,
  Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)');
  spec(ifreq)=real(Z' * Rx *Z)/(p+1)^2;
 end;
elseif strcmp(method,'CAPON'),
 for ifreq=1:N,
  Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)');
  spec(ifreq)=1.0 / real(Z' * (Rx\Z));
 end;
elseif strcmp(method,'CAPNORM'),
 for ifreq=1:N,
  Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)');
  spec(ifreq)=(p+1) / real(Z' * (Rx\Z));
 end;
elseif strcmp(method,'LAGUNAS'),
 for ifreq=1:N,
  Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)');
  Rxm1Z=Rx\Z; spec(ifreq)=real(Z' * Rxm1Z)/real(Z' * (Rx\Rxm1Z));
 end;
elseif strcmp(method,'GENLAG'),
 for ifreq=1:N,
  Z=exp(2j*pi*freqs(ifreq)*(0:Rxrow-1)');
  Rxqm1Z=(Rx)^q \Z; spec(ifreq)=real(Z' * Rx * Rxqm1Z)/real(Z' * (Rx\Rxqm1Z));
 end;
else
 error('unknown frequency representation');
end;

if (nargout==0),
 figure(gcf); plot(freqs,10.0*log10(spec)); grid;
 xlabel('normalized frequency');
 ylabel('DSP  (dB)');
end;

%  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

author: HeLiangHIT


text:
function varargout = gabrielGraph(pts)
%GABRIELGRAPH  Gabriel Graph of a set of points
%
%   EDGES = gabrielGraph(PTS)
%   Computes the Gabriel graph of the input set of points PTS. The Gabriel
%   graph is based on the euclidean Delaunay triangulation, and keeps only
%   edges whose circumcircle does not contain any other input point than
%   the edge extremities.
%
%   [NODES EDGES] = gabrielGraph(PTS)
%   Also returns the initial set of points;
%
%   Example
%     pts = rand(100, 2);
%     edges = gabrielGraph(pts);
%     figure; drawPoint(pts);
%     hold on; axis([0 1 0 1]); axis equal;
%     drawGraph(pts, edges);
%
%   See also
%     drawGraph, delaunayGraph
%

% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2012-01-22,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2012 INRA - Cepia Software Platform.

% compute Delaunay triangulation
if verLessThan('matlab', '8.1')
    % Code for versions before R2013a
    dt = DelaunayTri(pts); %#ok<DDELTRI>
else
    % Code for versions R2013a and later
    dt = delaunayTriangulation(pts);
end

% extract edges (N-by-2 array)
eds = dt.edges();

% radius of the circule circumscribed to each edge
rads = edgeLength([pts(eds(:,1), :) pts(eds(:,2), :)]) / 2;

% extract middle point of each edge
midPts = midPoint(pts(eds(:,1), :), pts(eds(:,2), :));

% distance between midpoints and all points
% closest points should be edge vertices
dists = minDistancePoints(midPts, pts);

% geometric tolerance (adapted to point set extent)
tol = max(max(pts) - min(pts)) * eps;

% keep only edges whose circumcircle does not contain any other point
keep = dists >= rads - tol;
edges = eds(keep, :);

if nargout < 2
    varargout = {edges};
else
    varargout = {pts, edges};
end


text:
function dista=w_distance(p1, p2)
    vec = p1-p2;
    dista=sqrt(sum(vec.^2));
end

author: LazyFalcon


text: tb.RefreshToolbar();

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
classdef MimContextMapping < handle
    % MimContextMapping. A class for specifying the relationship between
    % contexts.
    %
    % This class is used by the Framework to store the relationship between
    % a context (the region in the image over which results are calculated),
    % and its context sets (the set of contexts of which it is a member), and
    % alo the hierarchy of contexts. For example, the LeftLung and RightLung
    % contexts are both in the context set SingleLung, and these are both
    % children of the LungROI context.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        Context % The context
        ContextSet % The context type (of type MimContextSet)
        TemplateGenerationFunctions % The name of a function from which this context can be found
        ContextTriggerPlugin % The name of a plugin which, when called, will trigger saving of a template
        Parent %
        Children
    end

    methods
        function obj = MimContextMapping(context_id, context_set, template_generation_function, context_trigger_plugin, parent_context_mapping)
            obj.Context = context_id;
            obj.ContextSet = context_set;
            obj.TemplateGenerationFunctions = template_generation_function;
            obj.ContextTriggerPlugin = context_trigger_plugin;
            obj.Parent = parent_context_mapping;
            obj.Children = {};

            % Add this context to the list of contexts for this context type
            obj.ContextSet.AddContext(obj);

            if ~isempty(parent_context_mapping)
                obj.Parent.AddChild(obj);
            end
        end

        function AddChild(obj, child)
            obj.Children{end + 1} = child;
        end
    end

end

author: tomdoel

repo: pulmonarytoolkit


text:
function net = vl_simplenn_move(net, destination)
%VL_SIMPLENN_MOVE  Move a SimpleNN network between CPU and GPU.
%   NET = VL_SIMPLENN_MOVE(NET, 'gpu') moves the network to the
%   current GPU device. NET = VL_SIMPLENN_MOVE(NET, 'cpu') moves the
%   network to the CPU.
%
%   See also: VL_SIMPLENN().

% Copyright (C) 2014-15 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

switch destination
  case 'gpu', moveop = @(x) gpuArray(x) ;
  case 'cpu', moveop = @(x) gather(x) ;
  otherwise, error('Unknown destination ''%s''.', destination) ;
end
for l=1:numel(net.layers)
  switch net.layers{l}.type
    case {'conv', 'convt', 'bnorm'}
      for f = {'filters', 'biases', 'filtersMomentum', 'biasesMomentum'}
        f = char(f) ;
        if isfield(net.layers{l}, f)
          net.layers{l}.(f) = moveop(net.layers{l}.(f)) ;
        end
      end
      for f = {'weights', 'momentum'}
        f = char(f) ;
        if isfield(net.layers{l}, f)
          for j=1:numel(net.layers{l}.(f))
            net.layers{l}.(f){j} = moveop(net.layers{l}.(f){j}) ;
          end
        end
      end
    otherwise
      % nothing to do ?
  end
end

author: willard-yuan

repo: cnn-for-image-retrieval


text:
% Chapter 5 - Fractals and Multifractals.
% Program_5c - An Iterated Function System.
% Copyright Birkhauser 2013. Stephen Lynch.

% Barnsley's fern (Figure 5.7).
function Program_5c(~)
% This function plots Barnsley's fern with N points.
% The transformations are in the form
% T(x,y) = (a*x+b*y+c, d*x+e*y+f).
echo on
N=50000;
close all
P=zeros(N,2);
P(1,:)=[0.5,0.5];

% The main loop where the iterations are performed.
for k=1:N-1
	r=rand;
	if r<.05;
		P(k+1,:)=T(P(k,:),0,0,0,0,.2,0);
	elseif r<.86;
		P(k+1,:)=T(P(k,:),.85,.05,0,-.04,.85,1.6);
	elseif r<.93;
		P(k+1,:)=T(P(k,:),.2,-.26,0,.23,.22,1.6);
	else
		P(k+1,:)=T(P(k,:),-.15,.28,0,.26,.24,.44);
	end
end

plot(P(:,1),P(:,2),'.','MarkerSize',1);
axis([-2.5 3.5 0 11]);
set(gca,'Position',[0 0 1 1])

% The transformation T
function F=T(P,a,b,c,d,e,f)
F=zeros(1,2);
F(1)=a*P(1)+b*P(2)+c;
F(2)=d*P(1)+e*P(2)+f;

% End of Program_5c.


text:
function name = p07_name ( )

%*****************************************************************************80
%
%% P07_NAME returns the name of problem 07.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string NAME, the name of the problem.
%
  name = 'DR4062';

  return
end

author: johannesgerer

repo: jburkardt-m


text:
filename='Cantilever_quad_coarse';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance';'perimeter'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
optimizer = 'IPOPT';
incrementFactor = 1;
designVariable = 'Density';
filterType = 'P1';

nsteps = 5;
Vfrac_final = 0.4;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-2;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function patches = construct_grid_even(grid_size,overlap,dim,min_diff)

N = length(dim);
start_point = cell(N,1);
end_point = cell(N,1);

for i = 1:N
    start_point{i} = [1:grid_size(i):dim(i)-grid_size(i)-overlap(i)+1,max(dim(i)-grid_size(i)-overlap(i)+1,1)];
    end_point{i} = [grid_size(i)+overlap(i):grid_size(i):dim(i),dim(i)];
    if length(start_point{i}) > 1
        if start_point{i}(end) - start_point{i}(end-1) < min_diff(i)
            start_point{i}(end-1) = [];
            end_point{i}(end-1) = [];
        end
    end
end

start_grid = cell(1,N);
[start_grid{:}] = ndgrid(start_point{:});

end_grid = cell(1,N);
[end_grid{:}] = ndgrid(end_point{:});
patches = zeros(numel(start_grid{1}),2*N);

for i = 1:N
    patches(:,2*i-1) = start_grid{i}(:);
    patches(:,2*i) = end_grid{i}(:);
end

author: flatironinstitute

repo: NoRMCorre


text:
function [rasterSegments, planC, isError] = getRasterSegments(structureID, planC, varargin)
%"getRasterSegments"
%   Data Access Function -- Returns rasterSegments for specified
%   structure from given planC.  varargin allows for a particular
%   slice to be specified, in which case only rasterSegs from that
%   slice are returned.
%
%   If structureID is a string, segs are returned from the structure
%   whose name (case insensitive) matches structureID. If numeric,
%   a direct index is used.
%
% JRA 10/27/03
%
%Usage:
%   [rasterSegments, planC, isError] = getRasterSegments(structureID, planC, varargin)

if ~exist('planC')
    global planC
end

%Warnings only display if isError is not a argout.
if nargout ~= 3
    showWarnings = 1;
else
    showWarnings = 0;
end
rasterSegments = [];
errorMsg = '';
isError = 0;

try
    indexS = planC{end};
    allStructureNames = {planC{indexS.structures}.structureName};
catch
    isError = errorEncounter(['Invalid planC.'], showWarnings);
    return;
end

%Check for matching structureID strings.
if ischar(structureID)
    requestedName = structureID;
    structureID = find(strcmpi(structureID, allStructureNames));
    if isempty(structureID)
        isError = errorEncounter(['No structure matching name ''' requestedName ''' exists.'], showWarnings);
        return;
    end
%Check that numeric ID is in range, and only one value is asked for.
elseif isnumeric(structureID)
    numStructures = length(planC{indexS.structures});
    if structureID > numStructures | structureID <= 0 | length(structureID) > 1
        isError = errorEncounter(['Numeric structureID is out of range.'], showWarnings);
        return;
    end
%Not a number, not a string.  Invalid ID.
else
    isError = errorEncounter(['Invalid structureID.'], showWarnings);
    return;
end

%Try and access rasterSegments given the current index.
if isfield(planC{indexS.structures}, 'rasterSegments')
    rasterSegments = planC{indexS.structures}(structureID).rasterSegments;

    if isempty(rasterSegments)
        try
            warning(['No rasterSegments exist for structure ' allStructureNames{structureID} ', generating.']); %Do not set iserror.
            if isfield(planC{indexS.structures}(structureID), 'associatedScan') & ~isempty(planC{indexS.structures}(structureID).associatedScan)
                scanSet = planC{indexS.structures}(structureID).associatedScan;
            else
                scanSet = 1;
            end

            planC = getRasterSegs(planC, structureID);
            rasterSegments = planC{indexS.structures}(structureID).rasterSegments;
        catch
            isError = errorEncounter(['No rasterSegments exist for structure ' allStructureNames{structureID} ', could not be generated.'], showWarnings);
        end
    end

    if nargin == 3
        sliceNum = varargin{1};
        rasterSegments = rasterSegments(find(rasterSegments(:,6) == sliceNum),:);
    end
else
    isError = errorEncounter(['rasterSegments field is nonexistant. Archive appears corrupt.'], showWarnings);
end

function isError = errorEncounter(errorString, showWarnings)
    isError = 1;
    if showWarnings
        warning(errorString);
    end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function maskM = getStructureMask(structNum, sliceNum, dim, planC)
%"getStructureMask"
%   Returns structure's mask on a specified slice number via uniformized
%   data.
%
%   structNum is the number of the requested structure
%   sliceNum is the slice NUMBER we want the structure on (not coordinate)
%   dim is the dimension (1,2,3 = x,y,z) that the slice should be taken
%   from.
%   planC is the plan (optional parameter: global is used if not passed)
%
%   WARNING: This function uses only uniformized data even if dim is 3 (for
%            zSlices).  In order to get the structure mask on a CT slice
%            via rasterSegments, use getRasterSegments and rasterToMask.
%
% JRA 11/14/03
%
%Usage:
%   function maskM = getStructureMask(structNum, sliceNum, dim, planC)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

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

[scanNum, relStructNum] = getStructureAssociatedScan(structNum, planC);

[indicesC, structBitsC, planC] = getUniformizedData(planC, scanNum);
[arraySize] = getUniformScanSize(planC{indexS.scan}(scanNum));

switch dim
	case 2
         rowDim = 3;    colDim = 2;     sliceDim = 1;
    case 1
         rowDim = 3;    colDim = 1;     sliceDim = 2;
    case 3
         rowDim = 1;    colDim = 2;     sliceDim = 3;
    otherwise
        warning('Valid Dimensions are 1,2,3 (x,y,z respectively.');
        return;
end

maskM = repmat(logical(0), [arraySize(rowDim) arraySize(colDim)]);
if relStructNum <= 52
    cellNum = 1;
else
    cellNum = ceil((relStructNum-52)/8)+1;
end
indicesM    = indicesC{cellNum};
structBitsM = structBitsC{cellNum};
sliceIndices = (indicesM(:,sliceDim) == sliceNum);
sliceXYZ = indicesM(sliceIndices,:);
if relStructNum <= 52
    sliceBits = logical(bitget(structBitsM(sliceIndices), relStructNum));
else
    sliceBits = logical(bitget(structBitsM(sliceIndices), relStructNum-52-8*(cellNum-2)));
end
structXYZ = sliceXYZ(sliceBits,:);

for i=1:size(structXYZ,1)
    maskM(structXYZ(i,rowDim), structXYZ(i,colDim)) = logical(1);
end


text:
function [y,dy] = div_sigma_gmr(Priors,Mu, Sigma_dx,Sigma, x, in, out)
%DIV_GMR Derivative of Gaussian Mixture Regression
%
% Inputs -----------------------------------------------------------------
%   o Priors:  1 x K array representing the prior probabilities of the K GMM
%              components.
%   o Mu:      D x K array representing the centers of the K GMM components.
%   o Sigma:   D x D x K array representing the covariance matrices of the
%              K GMM components.
%   o x:       P x N array representing N datapoints of P dimensions.
%   o in:      1 x P array representing the dimensions to consider as
%              inputs.
%   o out:     1 x Q array representing the dimensions to consider as
%              outputs (D=P+Q).
% Outputs ----------------------------------------------------------------
%   o y:       Q x N array representing the retrieved N datapoints of
%              Q dimensions, i.e. expected means.

N = size(x,2);
[D,D,K] = size(Sigma);
tmp = zeros(1,1,K);

index = 1;
for i=1:K
    for j=1:D
        for l=j:D
            tmp(j,j,i)  = Sigma_dx(index);%, Sigma_dx(2);Sigma_dx(3) Sigma_dx(4)];
            index = index + 1;
        end
    end
end
Sigma_dx = tmp;

%% Fast matrix computation (see the commented code for a version involving
%% one-by-one computation, which is easier to understand).
%%
%% Compute the influence of each GMM component, given input x
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:K
    Pxi(:,i) = Priors(i).*gaussPDF(x, Mu(in,i), Sigma(in,in,i));
end
beta = Pxi./repmat(sum(Pxi,2)+realmin,1,K);
%% Compute expected means y, given input x
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j=1:K
    y_tmp(:,:,j) = repmat(Mu(out,j),1,N) + Sigma_dx(:,:,j)*inv(Sigma(in,in,j)) * (x-repmat(Mu(in,j),1,N));
end
beta_tmp = reshape(beta,[1 size(beta)]);
y_tmp2 = repmat(beta_tmp,[length(out) 1 1]) .* y_tmp;
y = sum(y_tmp2,3);

if nargout > 1

    dy = zeros(1,K);

    for j=1:K
        v = inv(Sigma(in,in,j)) * (x - Mu(in,j));
        v = v(:);
        dy(j) = v;
    end

    dy = dy .* beta;

end

end

author: epfl-lasa


text:
function  bdiffma(newcat)
    %  This routine etsimates the b-value of a curve automatically
    %  The b-valkue curve is differenciated and the point
    %  of maximum curvature marked. The b-value will be calculated
    %  using this point and the point half way toward the high
    %  magnitude end of the b-value curve.

    %  Stefan Wiemer 1/95
    %
    think
    %zmap_message_center.set_info('  ','Calculating b-value...')
    global cluscat mess bfig backcat xt3 bvalsum3
    global  ttcat teb t0b cua b1 b2 n1 n2
    report_this_filefun(mfilename('fullpath'));

    [existFlag,figNumber]=figure_exists('frequency-magnitude distribution',1);
    if existFlag
        % figure_w_normalized_uicontrolunits(bfig);
        bfig = figNumber;
    else
        bfig=figure_w_normalized_uicontrolunits(...                  %build figure for plot
            'Units','normalized','NumberTitle','off',...
            'Name','frequency-magnitude distribution',...
            'MenuBar','none',...
            'visible','off',...
            'pos',[ 0.300  0.7 0.5 0.5]);

        uicontrol('Units','normal',...
            'Position',[.0 .85 .08 .06],'String','Info ',...
             'Callback','infoz(1)');
        uicontrol('Units','normal',...
            'Position',[.0 .55 .10 .06],'String','Manual ',...
             'Callback','bfitnew(newcat)');
        matdraw

        uicontrol('Units','normal',...
            'Position',[.0 .65 .08 .06],'String','Save ',...
             'Callback',{@calSave9,xt3, bvalsum3})

    end

    maxmag = max(newcat.Magnitude);
    mima = min(newcat.Magnitude);
    if mima > 0 ; mima = 0 ; end

    % number of mag units
    nmagu = (maxmag*10)+1;

    bval = zeros(1,nmagu);
    bvalsum = zeros(1,nmagu);
    bvalsum3 = zeros(1,nmagu);

    [bval,xt2] = hist(newcat.Magnitude,(mima:0.1:maxmag));
    bvalsum = cumsum(bval);                        % N for M <=
    bvalsum3 = cumsum(bval(length(bval):-1:1));    % N for M >= (counted backwards)
    xt3 = (maxmag:-0.1:mima);

    backg_be = log10(bvalsum);
    backg_ab = log10(bvalsum3);
    orient tall

    if hold_state
        axes(cua)
        hold on
    else
        figure_w_normalized_uicontrolunits(bfig);delete(gca);delete(gca);delete(gca);delete(gca)
        rect = [0.2,  0.3, 0.70, 0.6];           % plot Freq-Mag curves
        axes('position',rect);
    end

    pl =semilogy(xt3,bvalsum3,'b');
    set(pl,'LineWidth',2.0)
    hold on
    %semilogy(xt3,bvalsum3,'om')
    difb = [0 diff(bvalsum3) ];
    %pl =semilogy(xt3,difb,'g');
    %set(pl,'LineWidth',2.0)
    %semilogy(xt3,difb,'g')
    grid

    % Marks the point of maximum curvature
    %
    i = find(difb == max(difb));
    i = max(i);
    %te = semilogy(xt3(i),difb(i),'xk');
    %set(te,'LineWidth',2,'MarkerSize',ms10)
    %te = semilogy(xt3(i),bvalsum3(i),'xk');
    %set(te,'LineWidth',2,'MarkerSize',ms10)

    % Estimate the b-value
    %
    i2 = 1 ;
    %te = semilogy(xt3(i2),difb(i2),'xk');
    %set(te,'LineWidth',2,'MarkerSize',ms10)
    %te = semilogy(xt3(i2),bvalsum3(i2),'xk');
    %set(te,'LineWidth',2,'MarkerSize',ms10)

    xlabel('Magnitude','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
    ylabel('Cumulative Number','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
    set(gca,'Color',color_bg)
    set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on')

    cua = gca;

    par2 = 0.1 * max(bvalsum3);
    par3 = 0.12 * max(bvalsum3);
    M1b = [];
    M1b = [xt3(i) bvalsum3(i)];
    tt3=num2str(fix(100*M1b(1))/100);
    text( M1b(1),M1b(2),['|: M1=',tt3],'Fontweight','bold' )

    M2b = [];
    M2b =  [xt3(i2) bvalsum3(i2)];
    tt4=num2str(fix(100*M2b(1))/100);
    %text( M2b(1),M2b(2),['|: M2=',tt4],'Fontweight','bold' )

    ll = xt3 >= M1b(1) & xt3 <= M2b(1);
    x = xt3(ll);

    [ av,bv,si] = bmemag(newcat);

    pause(0.1)

    y = backg_ab(ll);
    %[p,s] = polyfit(x,y,1)                    % fit a line to background
    [aw bw,  ew] = wls(x',y');
    p = [bw aw];
    f = polyval(p,x);
    (teb-t0b)/(10.^ polyval(p,5))
    (teb-t0b)/(10.^ polyval(p,6))
    (teb-t0b)/(10.^ polyval(p,7))
    (teb-t0b)/(10.^ polyval(p,8))
    f = 10.^f;
    hold on
    ttm= semilogy(x,f,'r');                         % plot linear fit to backg
    set(ttm,'LineWidth',1)
    set(gca,'XLim',[min(newcat.Magnitude)-0.5  max(newcat.Magnitude)+1.0])
    r = corrcoef(x,y);
    r = r(1,2);
    std_backg = ew;      % standard deviation of fit

    p=-p(1,1);
    p=fix(100*p)/100;
    std_backg=fix(100*std_backg)/100;
    tt2=num2str(std_backg);
    tt1=num2str(p);
    tt4=num2str(bv,2);
    tt5=num2str(si,2);

    rect=[0 0 1 1];
    h2=axes('position',rect);
    set(h2,'visible','off');

    if ~ho
        txt1=text(.16, .18,['b-value (w LS, M  > ', num2str(M1b(1)) '): ',tt1, ' +/- ', tt2]);
        set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
        txt1=text(.16, .12,['b-value (max lik, M > ', num2str(min(newcat.Magnitude)) '): ',tt4, ' +/- ', tt5]);
        set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)

    else
        txt1=text(.16, .06,['b-value (weighted least square): ',tt1, ' +/- ', tt2]);
        set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','r')
    end
    set(gcf,'visible','on');
    zmap_message_center.set_info('  ','Done')
    done

    if hold_state
        % calculate the probability that the two distributins are differnt
        b2 = str2double(tt1); n2 = newcat.Count;
        n = n1+n2;
        da = -2*n*log(n) + 2*n1*log(n1+n2*b1/b2) + 2*n2*log(n1*b2/b1+n2) -2;
        pr = exp(-da/2-2);
        disp(['Probability: ',  num2str(pr)]);
        txt1=text(.65, .85,['Utsu Test: ', num2str(pr)]);
        set(txt1,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m)
    else
        b1 = str2double(tt1); n1 = newcat.Count;
    end

author: CelsoReyes


text:
% read_erplabheader() - import ERPLAB dataset files
%
% Usage:
%   >> header = read_erplabheader(filename);
%
% Inputs:
%   filename - [string] file name
%
% Outputs:
%   header   - FILEIO toolbox type structure
%
% Modified from read_eeglabheader

%123456789012345678901234567890123456789012345678901234567890123456789012

% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, arno@salk.edu
%
% 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

function header = read_erplabheader(filename)

if nargin < 1
  help read_erplabheader;
  return;
end;

if ~isstruct(filename)
  load('-mat', filename);
else
  ERP = filename;
end;

header.Fs          = ERP.srate;
header.nChans      = ERP.nchan;
header.nSamples    = ERP.pnts;
header.nSamplesPre = -ERP.xmin*ERP.srate;
header.nTrials     = ERP.nbin;
try
  header.label       = { ERP.chanlocs.labels }';
catch
  ft_warning('creating default channel names');
  for i=1:header.nChans
    header.label{i} = sprintf('chan%03d', i);
  end
end
ind = 1;
for i = 1:length( ERP.chanlocs )
    if isfield(ERP.chanlocs(i), 'X') && ~isempty(ERP.chanlocs(i).X)
        header.elec.label{ind, 1} = ERP.chanlocs(i).labels;
        % this channel has a position
        header.elec.pnt(ind,1) = ERP.chanlocs(i).X;
        header.elec.pnt(ind,2) = ERP.chanlocs(i).Y;
        header.elec.pnt(ind,3) = ERP.chanlocs(i).Z;
        ind = ind+1;
    end;
end;

header.orig = ERP;

author: spm


text:
function ival = c8mat_is_column_orthogonal ( m, n, a )

%*****************************************************************************80
%
%% C8MAT_IS_COLUMN_ORTHOGONAL checks if a complex matrix is column orthogonal.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the row and column dimensions
%    of the matrix.  M and N must be positive.
%
%    Input, complex A(M,N), the matrix.
%
%    Output, integer IVAL:
%    -1, the matrix is not column orthogonal.
%    1, the matrix is column orthogonal.
%
  tol = 0.0001;
  ival = 1;

  for j1 = 1 : n

    for j2 = j1+1 : n

      deviation = abs ( a(1:m,j1)' * a(1:m,j2) );
      deviation_max = max ( deviation_max, deviation );

    end

  end

  if ( deviation_max < tol )
    ival = +1;
  else
    ival = -1;
  end

  return
end


text:
%% check S1Grid/find

x = S1Grid([1,2,3,4,9],0,10)
x = S1Grid([1,2,3,4,9,9.8],0,10,'periodic')

find(x,4,5)

x = S1Grid(0:39990,0,40000,'periodic');
y = linspace(0,39000,3000);

tic
for i = 1:100
  ind = find(x,y,50);
end
toc

tic
for i = 1:1
  for j = 1:length(y)
    find(x,y(j),50);
  end
end
toc

%% check S2Grid/find

x = equispacedS2Grid('points',500);
plot(subGrid(x,find(x,xvector,10*degree)));
full(find(x,xvector,10*degree))

x = equispacedS2Grid('points',5000);
y = vector3d(equispacedS2Grid('points',100));

tic
for i = 1:length(y)
  find(x,y(i),0.5);
end
toc

tic
for i = 1:100
  find(x,y,0.5);
end
toc

%% check SO3Grid/find

cs = crystalSymmetry('trigonal');
ss = specimenSymmetry('1');

x = equispacedSO3Grid(cs,ss,'points',100000);
y = equispacedSO3Grid(cs,ss,'points',100000);

tic
angle_outer(x,y,5*degree);
toc

tic
find(x,quaternion(y),5*degree);
toc

find(x,quaternion.id,20*degree)

q = axis2quat(xvector+yvector,45*degree);
q = quaternion.id;

sx = quaternion(subGrid(x,find(x,q,10*degree)));

dist(cs,specimenSymmetry,q,sx) / degree

plot(inv(sx)*xvector)
plot(inv(sx)*yvector)
plot(inv(sx)*zvector)

A = cos(ay)*cos(cy)*cos(ax)*(cos(by)*cos(bx)-1) - ...
  sin(ay)*sin(cy)*cos(ax)*(cos(bx)-cos(by));

B = cos(ay)*cos(cy)*cos(ax)*(cos(by)*cos(bx)-1) - ...
  sin(ay)*sin(cy)*cos(ax)*(cos(bx)-cos(by));

author: mtex-toolbox

repo: mtex

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


text:
function anonScanS = defineAnonScan()
%
% function anonScanS = defineAnonScan()
%
% Defines the anonymous scan data structure. The fields containing PHI have
% been left out by default. In order to leave out additional fields, remove
% them from the list below.
%
% The following three operations are allowed per field of the input data structure:
% 1. Keep the value as is: listed as 'keep' in the list below.
% 2. Allow only the specific values: permitted values listed within a cell array.
%    If no match is found, a default anonymous string will be inserted.
% 3. Insert dummy date: listed as 'date' in the list below. Date will be
%    replaced by a dummy value of 11/11/1111.
%
% APA, 1/11/2018

anonScanInfoS = struct( ...
    'imageNumber', 'keep', ...
    'imageType', {{'CT SCAN'}}, ...
    'scanType', {{'TRANSVERSE'}}, ...
    'CTOffset', 'keep', ...
    'rescaleSlope', 'keep', ...
    'rescaleIntercept', 'keep', ...
    'scaleSlope', 'keep', ...
    'scaleIntercept', 'keep', ...
    'grid1Units', 'keep', ...
    'grid2Units','keep', ...
    'numberRepresentation', {{'TWO''S COMPLEMENT INTEGER'}}, ...
    'bytesPerPixel','keep', ...
    'numberOfDimensions','keep', ...
    'sizeOfDimension1', 'keep', ...
    'sizeOfDimension2', 'keep', ...
    'zValue', 'keep', ...
    'imageOrientationPatient', 'keep', ...
    'patientPosition', 'keep', ...
    'xOffset','keep', ...
    'yOffset','keep', ...
    'CTAir','keep',...
    'CTWater','keep',...
    'sliceThickness', 'keep', ...
    'scannerType', {{'GE MEDICAL SYSTEMS'}}, ...
    'headInOut', {{'In','Out'}}, ...
    'positionInScan', {{'HFS', 'HFP', 'FFS', 'FFP'}}, ...
    'bValue', 'keep', ...
    'scanDate', 'date', ...
	'CTScale', 'keep', ...
    'transferProtocol', {{'DICOM'}}, ...
    'LRflippedToMatchPACS', 'keep', ...
    'APflippedToMatchPACS', 'keep', ...
    'SIflippedToMatchPACS', 'keep', ...
    'voxelThickness', 'keep' ...
        );

anonUniformScanInfoS = struct( ...
    'sliceNumSup', 'keep', ...
    'sliceNumInf', 'keep', ...
    'supInfScansCreated', 'keep', ...
    'minCTValue', 'keep', ...
    'maxCTValue', 'keep', ...
    'sliceThickness', 'keep', ...
    'bytesPerPixel', 'keep', ...
    'grid1Units', 'keep', ...
    'grid2Units', 'keep', ...
    'numberRepresentation', {{'TWO''S COMPLEMENT INTEGER'}}, ...
    'sizeOfDimension1', 'keep', ...
    'sizeOfDimension2', 'keep', ...
    'LRflippedToMatchPACS', 'keep', ...
    'APflippedToMatchPACS', 'keep', ...
    'SIflippedToMatchPACS', 'keep', ...
    'xOffset', 'keep', ...
    'yOffset', 'keep', ...
    'CTAir', 'keep', ...
    'CTWater', 'keep', ...
    'firstZValue', 'keep' ...
        );

anonScanS = struct( ...
    'scanArray', 'keep', ...
    'scanType', {{'CT','MR','PET','US','SPECT'}}, ...
    'scanInfo', anonScanInfoS, ...
    'uniformScanInfo', anonUniformScanInfoS, ...
    'scanArraySuperior', 'keep', ...
    'scanArrayInferior', 'keep', ...
    'transM', 'keep', ...
    'scanUID', 'keep', ...
    'assocDeformUID', 'keep', ...
    'assocTextureUID', 'keep');


text:
function varargout = process_scale( varargin )
% PROCESS_SCALE: Sacle values by a constant factor.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Scale values';
    sProcess.FileTag     = 'scale';
    sProcess.Category    = 'Filter';
    sProcess.SubGroup    = 'Pre-process';
    sProcess.Index       = 75;
    sProcess.Description = '';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data', 'results', 'timefreq', 'raw', 'matrix'};
    sProcess.OutputTypes = {'data', 'results', 'timefreq', 'raw', 'matrix'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;
    sProcess.isSeparator = 1;
    % Default values for some options
    sProcess.processDim  = 2;    % Process time by time
    % === Factor
    sProcess.options.factor.Comment = 'Multiplication factor: ';
    sProcess.options.factor.Type    = 'value';
    sProcess.options.factor.Value   = {1, '', 4};
    % === Sensor types
    sProcess.options.sensortypes.Comment = 'Sensor types or names (empty=all): ';
    sProcess.options.sensortypes.Type    = 'text';
    sProcess.options.sensortypes.Value   = 'MEG, EEG';
    sProcess.options.sensortypes.InputTypes = {'data', 'raw'};
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function sInput = Run(sProcess, sInput) %#ok<DEFNU>
    % Get factor
    factor = sProcess.options.factor.Value{1};
    % Opposite values
    sInput.A = factor * sInput.A;
    % Do not keep the Std field in the output
    if isfield(sInput, 'Std') && ~isempty(sInput.Std)
        sInput.Std = [];
    end
end

author: brainstorm-tools


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
% ##2
%==============================================================================
%
% - initialize
%     data:            Hands,           see setup2DhandData, level = 5;
%     visualization:   viewImage2D,     see viewImage.m
%     interpolation:   splineInter,   see inter.m
%     distance:        SSD,             see distance.m
%     regularizer:     mfElastic,       see regularizer.m
% - initialize FAIR plots
% - run optimization
%     NPIR:            Non-Parametric Image Registration, Trust-Region
% ===============================================================================

clear; close all; help(mfilename)

setup2DhandData
level = 5; omega = ML{level}.omega; m = ML{level}.m;
imgModel('reset','imgModel','splineInter','regularizer','moments','theta',0.01);
distance('reset','distance','SSD');
regularizer('reset','regularizer','mfElastic','alpha',1000,'mu',1,'lambda',0);

[T,R] = imgModel('coefficients',ML{level}.T,ML{level}.R,omega);
xc    = getStaggeredGrid(omega,m); % starting guess and reference for regularization
Rc    = imgModel(R,omega,center(xc,m));

% - initialize FAIR plots
FAIRplots('set','mode','TR-mf','fig',1);
FAIRplots('init',struct('Tc',T,'Rc',R,'omega',omega,'m',m));

% - run Non-Parametric Image Registration (Gauss-Newton)
fctn = @(yc) NPIRobjFctn(T,Rc,omega,m,xc,yc);  fctn([]);
yc = TrustRegion(fctn,xc,'Plots',@FAIRplots);
%==============================================================================


text:
function varargout = grMean(varargin)
%GRMEAN Compute mean value from neighbour nodes.
%
%   LBL2 = grMean(EDGES, LBL1)
%   new label for each node of the graph is computed as the mean of the
%   values of neighbours and of old value.
%
%   Example
%   grMean
%
%   See also
%   grMedian, grDilate, grErode
%

% ------
% Author: David Legland
% E-mail: david.legland@inrae.fr
% Created: 2006-01-20
% Copyright 2006-2022 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas)

if length(varargin) == 2
    edges   = varargin{1};
    values 	= varargin{2};
elseif length(varargin) == 3
    edges   = varargin{2};
    values  = varargin{3};
else
    error('Wrong number of arguments in "grMean"');
end

res = zeros(size(values));

uni = unique(edges(:));
for n = 1:length(uni)
    neigh = grAdjacentNodes(edges, uni(n));
    res(uni(n)) = mean(values([uni(n); neigh]));
end

varargout{1} = res;

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function numUnique=numUniqueElsInArray(vecList,skipEl)
%%NUMUNIQUEELSINARRAY Count the number of unique elements in a vector.
%
%INPUTS: vecList A numElsXnumVecs list of vectors for which the number of
%                unique elements in each vector (not considering across
%                vectors) is desired. NaN values are not counted.
%         skipEl If there is an element that should not count toward being
%                unique (i.e. these are skipped), then it can be given. If
%                no elements should be skipped, then this input can be
%                omitted or an empty matrix can be passed.
%
%OUTPUTS: numUnique A numVecsX1 array, where the number of unique elements
%               of each (column) vector in the matrix vecList is given.
%
%This function sorts the array, which puts makes duplicates consecutive.
%then, it scans through the array, skipping duplicates. The sorting places
%NaN values, if any, at the highest end of the array, past Inf. NaN values
%are just skipped.
%
%EXAMPLE:
% vecList=[17, 24,  1,  8, 15;
%          17,  2,  7, 14, 16;
%           4,  6,  2, 20, 22;
%          10, 12, 19,  2,  3;
%          11, 18, 25,  2,  0];
% numUnique=numUniqueElsInArray(vecList,0)
%One should get
% numUnique=[4;5;5;4;4]
%
%September 2020 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

numEls=size(vecList,1);
numVecs=size(vecList,2);

if(nargin>1&&~isempty(skipEl))
    vecList(vecList==skipEl)=NaN;
end

%Sorting the array makes all duplicates consecutive and places all NaN
%values at the end of the array (even after Inf).
vecList=sort(vecList,1,'ascend');

numUnique=zeros(numVecs,1);
for curVec=1:numVecs
    curEl=1;
    while(curEl<=numEls)
        %Advance the index past duplicates.
        while(curEl<numEls&&vecList(curEl,curVec)==vecList(curEl+1,curVec))
            curEl=curEl+1;
        end

        if(isnan(vecList(curEl,curVec)))
            break;
        end
        numUnique(curVec)=numUnique(curVec)+1;
        curEl=curEl+1;
    end
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function cx = jacobi_poly ( n, alpha, beta, x )

%*****************************************************************************80
%
%% JACOBI_POLY evaluates the Jacobi polynomials at X.
%
%  Differential equation:
%
%    (1-X*X) Y'' + (BETA-ALPHA-(ALPHA+BETA+2) X) Y' + N (N+ALPHA+BETA+1) Y = 0
%
%  Recursion:
%
%    P(0,ALPHA,BETA,X) = 1,
%
%    P(1,ALPHA,BETA,X) = ( (2+ALPHA+BETA)*X + (ALPHA-BETA) ) / 2
%
%    P(N,ALPHA,BETA,X)  =
%      (
%        (2*N+ALPHA+BETA-1)
%        * ((ALPHA**2-BETA**2)+(2*N+ALPHA+BETA)*(2*N+ALPHA+BETA-2)*X)
%        * P(N-1,ALPHA,BETA,X)
%        -2*(N-1+ALPHA)*(N-1+BETA)*(2*N+ALPHA+BETA) * P(N-2,ALPHA,BETA,X)
%      ) / 2*N*(N+ALPHA+BETA)*(2*N-2+ALPHA+BETA)
%
%  Restrictions:
%
%    -1 < ALPHA
%    -1 < BETA
%
%  Norm:
%
%    Integral ( -1 <= X <= 1 ) ( 1 - X )**ALPHA * ( 1 + X )**BETA
%      * P(N,ALPHA,BETA,X)**2 dX
%    = 2**(ALPHA+BETA+1) * Gamma ( N + ALPHA + 1 ) * Gamma ( N + BETA + 1 ) /
%      ( 2 * N + ALPHA + BETA ) * N! * Gamma ( N + ALPHA + BETA + 1 )
%
%  Special values:
%
%    P(N,ALPHA,BETA)(1) = (N+ALPHA)!/(N!*ALPHA!) for integer ALPHA.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 July 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Milton Abramowitz and Irene Stegun,
%    Handbook of Mathematical Functions,
%    US Department of Commerce, 1964.
%
%  Parameters:
%
%    Input, integer N, the highest order polynomial to compute.  Note
%    that polynomials 0 through N will be computed.
%
%    Input, real ALPHA, one of the parameters defining the Jacobi
%    polynomials, ALPHA must be greater than -1.
%
%    Input, real BETA, the second parameter defining the Jacobi
%    polynomials, BETA must be greater than -1.
%
%    Input, real X, the point at which the polynomials are to be evaluated.
%
%    Output, real CX(1:N+1), the values of the first N+1 Jacobi
%    polynomials at the point X.
%
  if ( alpha <= -1.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'JACOBI_POLY - Fatal error!\n' );
    fprintf ( 1, '  Illegal input value of ALPHA = %f\n', alpha );
    fprintf ( 1, '  But ALPHA must be greater than -1.\n' );
    error ( 'JACOBI_POLY - Fatal error!' );
  end

  if ( beta <= -1.0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'JACOBI_POLY - Fatal error!\n' );
    fprintf ( 1, '  Illegal input value of BETA = %f\n', beta );
    fprintf ( 1, '  But BETA must be greater than -1.\n' );
    error ( 'JACOBI_POLY - Fatal error!' );
  end

  if ( n < 0 )
    cx = [];
    return
  end

  cx(1) = 1.0;

  if ( n == 0 )
    return
  end

  cx(2) = ( 1.0 + 0.5 * ( alpha + beta ) ) * x  + 0.5 * ( alpha - beta );

  for i = 2 : n

    c1 = 2 * i * ( i + alpha + beta ) * ( 2 * i - 2 + alpha + beta );

    c2 = ( 2 * i - 1 + alpha + beta ) * ( 2 * i + alpha + beta ) ...
      * ( 2 * i - 2 + alpha + beta );

    c3 = ( 2 * i - 1 + alpha + beta ) * ( alpha + beta ) * ( alpha - beta );

    c4 = - 2 * ( i - 1 + alpha ) * ( i - 1 + beta )  * ( 2 * i + alpha + beta );

    cx(i+1) = ( ( c3 + c2 * x ) * cx(i) + c4 * cx(i-1) ) / c1;

  end

  return
end


text:
% ----------------------------------------------------------------------------
% function hfssInsertDesign(fid, designName, [designType = 'driven modal'])
%
% Description :
% -------------
% Create the necessary VB Script to insert an HFSS Design into the Project
% and set it as the active design.
%
% Parameters :
% ------------
% fid        - file identifier of the HFSS script file.
% designName - name of the new design to be inserted.
% designType - (Optional String) choose from the following:
%              1. 'driven modal' (default)
%			   2. 'driven terminal'
%			   3. 'eigenmode'
%
% Note :
% ------
% This function is usually called after a call to either hfssNewProject()
% or hfssOpenProject(), but this is not necessary.
%
% Example :
% ---------
% fid = fopen('myantenna.vbs', 'wt');
% ...
% hfssInsertDesign(fid, 'Dipole_SingleElement');
% ----------------------------------------------------------------------------

% ----------------------------------------------------------------------------
% This file is part of HFSS-MATLAB-API.
%
% HFSS-MATLAB-API 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.
%
% HFSS-MATLAB-API 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
% Foobar; if not, write to the Free Software Foundation, Inc., 59 Temple
% Place, Suite 330, Boston, MA  02111-1307  USA
%
% Copyright 2004, Vijay Ramasami (rvc@ku.edu)
% ----------------------------------------------------------------------------
function hfssInsertDesign(fid, designName, designType)

% arguments processor.
if (nargin < 2)
	error('Insufficient number of arguments !');
elseif (nargin < 3)
	designType = [];
end

% default arguments.
if isempty(designType)
	designType = 'driven modal';
end

% create the necessary script.
fprintf(fid, '\n');
fprintf(fid, 'oProject.InsertDesign "HFSS", ');
fprintf(fid, '"%s", ', designName);
switch (lower(designType))
	case 'driven terminal'
		fprintf(fid, '"DrivenTerminal", ""\n');
	case 'driven modal'
		fprintf(fid, '"DrivenModal", ""\n');
	case 'eigenmode'
		fprintf(fid, '"Eigenmode", ""\n');
end
fprintf(fid, 'Set oDesign = oProject.SetActiveDesign("%s")\n', designName);
fprintf(fid, 'Set oEditor = oDesign.SetActiveEditor("3D Modeler")\n');

author: yuip

repo: hfss-api

save_path: github-repos/MATLAB/yuip-hfss-api


text:
function [e, edata, eprior] = gperr(net, x, t)
%GPERR	Evaluate error function for Gaussian Process.
%
%	Description
%	E = GPERR(NET, X, T) takes a Gaussian Process data structure NET
%	together  with a matrix X of input vectors and a matrix T of target
%	vectors, and evaluates the error function E. Each row of X
%	corresponds to one input vector and each row of T corresponds to one
%	target vector.
%
%	[E, EDATA, EPRIOR] = GPERR(NET, X, T) additionally returns the data
%	and hyperprior components of the error, assuming a Gaussian prior on
%	the weights with mean and variance parameters PRMEAN and PRVARIANCE
%	taken from the network data structure NET.
%
%	See also
%	GP, GPCOVAR, GPFWD, GPGRAD
%

%	Copyright (c) Ian T Nabney (1996-2001)

errstring = consist(net, 'gp', x, t);
if ~isempty(errstring);
  error(errstring);
end

cn = gpcovar(net, x);

edata = 0.5*(sum(log(eig(cn, 'nobalance'))) + t'*inv(cn)*t);

% Evaluate the hyperprior contribution to the error.
% The hyperprior is Gaussian with mean pr_mean and variance
% pr_variance
if isfield(net, 'pr_mean')
  w = gppak(net);
  m = repmat(net.pr_mean, size(w));
  if size(net.pr_mean) == [1 1]
    eprior = 0.5*((w-m)*(w-m)');
    e2 = eprior/net.pr_var;
  else
    wpr = repmat(w, size(net.pr_mean, 1), 1)';
    eprior = 0.5*(((wpr - m').^2).*net.index);
    e2 = (sum(eprior, 1))*(1./net.pr_var);
  end
else
  e2 = 0;
  eprior = 0;
end

e = edata + e2;

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function [vxx,vy] = powerdiagram(varargin)
% Power diagram
% modified voronoi.m to use power centers instead of circumcenters

[cax,args,nargs] = axescheck(varargin{:});
error(nargchk(1,5,nargs));

x = args{1};
y = args{2};
if ~isequal(size(x),size(y))
        error(message('MATLAB:voronoi:InputSizeMismatch'));
end
if ndims(x) > 2 || ndims(y) > 2
        error(message('MATLAB:voronoi:HigherDimArray'));
end
x = x(:);
y = y(:);
tri = args{3};
ls = args{4};
wts = args{5};

if isempty(tri)
    return;
end

% Compute power centers of triangles
% (this is already done in cells2D)
sE = [x, y];
[c, powers] = powercentersPD(tri, sE, wts);
% tr = triangulation(tri,x,y);
% c = tr.circumcenter();

% Create matrix T where i and j are endpoints of edge of triangle T(i,j)
n = numel(x);
t = repmat((1:size(tri,1))',1,3);
T = sparse(tri,tri(:,[3 1 2]),t,n,n);

% i and j are endpoints of internal edge in triangle E(i,j)
E = (T & T').*T;
% i and j are endpoints of external edge in triangle F(i,j)
F = xor(T, T').*T;

% v and vv are triangles that share an edge
[~,~,v] = find(triu(E));
[~,~,vv] = find(triu(E'));

% Internal edges
vx = [c(v,1) c(vv,1)]';
vy = [c(v,2) c(vv,2)]';

%%% Compute lines-to-infinity
% i and j are endpoints of the edges of triangles in z
[i,j,z] = find(F);
% Counter-clockwise components of lines between endpoints
dx = x(j) - x(i);
dy = y(j) - y(i);

% Calculate scaling factor for length of line-to-infinity
% Distance across range of data
rx = max(x)-min(x);
ry = max(y)-min(y);
% Distance from vertex to center of data
cx = (max(x)+min(x))/2 - c(z,1);
cy = (max(y)+min(y))/2 - c(z,2);
% Sum of these two distances
nm = sqrt(rx.*rx + ry.*ry) + sqrt(cx.*cx + cy.*cy);
% Compute scaling factor
scale = nm./sqrt((dx.*dx+dy.*dy));

% Lines from voronoi vertex to "infinite" endpoint
% We know it's in correct direction because compononents are CCW
ex = [c(z,1) c(z,1)-dy.*scale]';
ey = [c(z,2) c(z,2)+dx.*scale]';
% Combine with internal edges
vx = [vx ex];
vy = [vy ey];

if nargout<2
    % Plot diagram
    if isempty(cax)
        % If no current axes, create one
        cax = gca;
    end
    if isempty(ls)
        % Default linespec
        ls = '-';
    end
    [l,c,mp,msg] = colstyle(ls); error(msg) % Extract from linespec
    if isempty(mp)
        % Default markers at points
        mp = '.';
    end
     if isempty(l)
        % Default linestyle
        l = get(ancestor(cax,'figure'),'DefaultAxesLineStyleOrder');
    end
    if isempty(c),
        % Default color
        co = get(ancestor(cax,'figure'),'DefaultAxesColorOrder');
        c = co(1,:);
    end
    % Plot points
    h1 = plot(x,y,'marker',mp,'color',c,'linestyle','none','parent',cax);
    % Plot voronoi lines
    h2 = line(vx,vy,'color',c,'linestyle',l,'parent',cax,...
        'yliminclude','off','xliminclude','off');
    if nargout==1, vxx = [h1; h2]; end % Return handles
else
    vxx = vx; % Don't plot, just return vertices
end

author: optimaltransport


text:
function g = uniformPriorGradient(prior, x)

% UNIFORMPRIORGRADIENT Gradient wrt x of the uniform prior.

% PRIOR

% Compute gradient of prior
g = 0 * x;

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function snakedisp(x,y,style)
%--------Display the snake model contour-----------

hold on

% convert to column data
x = x(:); y = y(:);

if nargin == 3          %nargin returns the number of input arguments specified for a function
   plot([x;x(1,1)],[y;y(1,1)],style);
   hold off
else
   disp('snakedisp.m: The input parameter is not correct!');
end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function volume = sphere_volume_nd ( dim_num, r )

%*****************************************************************************80
%
%% SPHERE_VOLUME_ND computes the volume of an implicit sphere in ND.
%
%  Discussion:
%
%    An implicit sphere in ND satisfies the equation:
%
%      sum ( ( X(1:N) - CENTER(1:N) )^2 ) = R * R
%
%    where R is the radius and CENTER is the center.
%
%    Results for the first few values of N are:
%
%    DIM_NUM  Volume
%    -     -----------------------
%    2                PI   * R^2
%    3     (4/3)    * PI   * R^3
%    4     (1/2)    * PI^2 * R^4
%    5     (8/15)   * PI^2 * R^5
%    6     (1/6)    * PI^3 * R^6
%    7     (16/105) * PI^3 * R^7
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 April 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the dimension of the space.
%
%    Input, real R, the radius of the sphere.
%
%    Output, real VOLUME, the volume of the sphere.
%
  volume = r^dim_num * sphere_unit_volume_nd ( dim_num );

  return
end


text:
function Q = ForwardStepIC2D(x2d, y2d, time)

% function Q = ForwardStepIC2D(x2d, y2d, time)
% Purpose: compute plane flow configuration

Globals2D;

gamma = 1.4;

rho = gamma*ones(Np,K);  p = ones(Np,K);

% M = |u|/c,  c = sqrt(gamma*p/rho)
rhou = rho.*(3*ones(Np, K)); rhov = zeros(Np, K);
Ener = p/(gamma-1.0) + (rhou.^2+rhov.^2)./(2*rho);

Q(:,:,1) = rho; Q(:,:,2) = rhou; Q(:,:,3) = rhov; Q(:,:,4) = Ener;
return

repo: Aero-matlab


text:
function H_MMSE = MMSE_CE(Y,Xp,pilot_loc,Nfft,Nps,h,SNR)
%function H_MMSE = MMSE_CE(Y,Xp,pilot_loc,Nfft,Nps,h,ts,SNR)
% MMSE channel estimation function
% Inputs:
%       Y         = Frequency-domain received signal
%       Xp        = Pilot signal
%       pilot_loc = Pilot location
%       Nfft      = FFT size
%       Nps       = Pilot spacing
%       h         = Channel impulse response
%       ts        = Sampling time
%       SNR       = Signal-to-Noise Ratio[dB]
% output:
%      H_MMSE     = MMSE channel estimate

%H = fft(h,N);
snr = 10^(SNR*0.1);
Np=Nfft/Nps; k=1:Np;
H_tilde = Y(1,pilot_loc(k))./Xp(k);  % LS estimate
k=0:length(h)-1; %k_ts = k*ts;
hh = h*h';
tmp = h.*conj(h).*k; %tmp = h.*conj(h).*k_ts;
r = sum(tmp)/hh;
r2 = tmp*k.'/hh; %r2 = tmp*k_ts.'/hh;
tau_rms = sqrt(r2-r^2);     % rms delay
df = 1/Nfft;  %1/(ts*Nfft);
j2pi_tau_df = j*2*pi*tau_rms*df;
K1 = repmat([0:Nfft-1].',1,Np);
K2 = repmat([0:Np-1],Nfft,1);
rf = 1./(1+j2pi_tau_df*(K1-K2*Nps));
K3 = repmat([0:Np-1].',1,Np);
K4 = repmat([0:Np-1],Np,1);
rf2 = 1./(1+j2pi_tau_df*Nps*(K3-K4));
Rhp = rf;
Rpp = rf2 + eye(length(H_tilde),length(H_tilde))/snr;
H_MMSE = transpose(Rhp*inv(Rpp)*H_tilde.');  % MMSE channel estimate

author: LyricYang


text:
% interpmethod is either 'linear' or 'spline'
function [z,Hu] = htls(k,y,interpmethod)
% "Algorithm for time-domain NMR data fitting based on total least squares"
% Vanhuffel, S., Chen, H., Decanniere, C. and Vanhecke, P., (1994)
if nargin < 3; interpmethod = 'linear'; end

y = complete_signal(y,interpmethod);
n = length(y);
y = reshape(y,[n,1]);
l = ceil(n/2);
Hy = hankel(y(1:l),y(l:n));
[U,~,~] = svd(Hy,'econ');
Ur = U(:,1:k);
Ur1 = Ur(2:end,:);
Ur2 = Ur(1:end-1,:);
[~,~,V] = svd([Ur2 Ur1]);
I = 1:k;
V12 = V(I,k+I);
V22 = V(k+I,k+I);
Q = -V12/V22;
e = eig(Q);
A = (e.^(0:n-1)).';
c = A \ y;
u = A*c;
Hu = hankel(u(1:k+1),u(k+1:n));
[U,~,~] = svd(Hu,'econ');
z = U(:,end);

function y = complete_signal(y,interpmethod)
I = isnan(y);
if ~any(I); return; end
t = 1:length(y);
y(I) = interp1(t(~I),y(~I),t(I),interpmethod);

author: MIT-SPARK

repo: CertifiablyRobustPerception


text:
function [study,xmesh,ymesh,zmesh,tags]=dicomrt_d2c_coordsystem(study,xmesh,ymesh,zmesh,tags)
% dicomrt_d2c_coordsystem(study,xmesh,ymesh,zmesh,tags)
%
% Convert DICOM data from native coordinate system to RTOG coordinate system
%
% Copyright (C) 2002 Emiliano Spezi (emiliano.spezi@physics.org)
% LM 04/28/2006 DK
%         Fix for dose x-coordinates when patient position is FFS.

% Check input data
% PatientPosition is N/A in VOI hence it must be defined previously
% and stored in tags.dicomPatientPosition if we are dealing with VOI
if ~isfield(tags,'dicomPatientPosition') || isempty(tags(1).dicomPatientPosition)
    [study,type,dummylabel,PatientPosition]=dicomrt_checkinput(study);
    %tags.dicomPatientPosition=PatientPosition;
    for i=1:length(tags)
        tags(i).('dicomPatientPosition') = PatientPosition;
    end
else
    [study,type,dummylabel]=dicomrt_checkinput(study);
    PatientPosition=tags.dicomPatientPosition;
end

% Get DICOM-RT toolbox dataset info
study_pointer=study{1,1};
study_array=study{2,1};

% Accounting for different coordinate system between DICOM and RTOG
%
% NOTE: The origin of the RTOG coordinate system is defined as the coordinates of
% the geometrical center of the image. Offsets along the x- and y-direction
% are calculated from the DICOM original data.
%
if strcmpi('VOI',type)~=1                       % Separate case if study is a VOI
    if PatientPosition==1                       % HFS
        study_array                 = flipdim(study_array,3);
        tags.hio                    = 'IN';
        tags.pos                    = 'NOSE UP';
        if strcmpi('CT',type)~=1
            xmesh                       = xmesh;
            ymesh                       = -ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
            tags.coord1OFFirstPoint     = xmesh(1);
            tags.coord2OFFirstPoint     = ymesh(1);
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.horizontalGridInterval = temp_diff_x(1);
            tags.verticalGridInterval   = temp_diff_y(1);
        else
            tags.originalCTxmesh        = xmesh;
            tags.originalCTymesh        = ymesh;
            tags.originalCTzmesh        = zmesh;
            xmesh                       = xmesh;
            ymesh                       = -ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;
            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.grid1Units             = abs(temp_diff_x(1));
            tags.grid2Units             = abs(temp_diff_y(1));
        end
        tags.xcoordOfNormaliznPoint = '';
        tags.ycoordOfNormaliznPoint = '';
        tags.zcoordOfNormaliznPoint = '';
    elseif PatientPosition==2                   % FFS
        study_array                 = flipdim(study_array,3);
        tags.hio                    = 'OUT';
        tags.pos                    = 'NOSE UP';
        if strcmpi('CT',type)~=1
%             xmesh                       = xmesh;
            xmesh                       = -xmesh;%DK
            ymesh                       = -ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
%             tags.coord1OFFirstPoint     = xmesh(1);
            tags.coord1OFFirstPoint     = -xmesh(1);%DK
            tags.coord2OFFirstPoint     = ymesh(1);
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.horizontalGridInterval = temp_diff_x(1);
            tags.verticalGridInterval   = temp_diff_y(1);
        else
            tags.originalCTxmesh        = xmesh;
            tags.originalCTymesh        = ymesh;
            tags.originalCTzmesh        = zmesh;
            xmesh                       = xmesh;
            ymesh                       = -ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;
            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.grid1Units             = abs(temp_diff_x(1));
            tags.grid2Units             = abs(temp_diff_y(1));
        end
        tags.xcoordOfNormaliznPoint = '';
        tags.ycoordOfNormaliznPoint = '';
        tags.zcoordOfNormaliznPoint = '';
    elseif PatientPosition==3                   % HFP
        study_array                 = flipdim(study_array,3);
        tags.hio                    = 'IN';
        tags.pos                    = 'NOSE DOWN';
        if strcmpi('CT',type)~=1
            xmesh                       = -xmesh;
            ymesh                       = ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
            tags.coord1OFFirstPoint     = xmesh(1);
            tags.coord2OFFirstPoint     = ymesh(1);
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.horizontalGridInterval = temp_diff_x(1);
            tags.verticalGridInterval   = temp_diff_y(1);
        else
            tags.originalCTxmesh        = xmesh;
            tags.originalCTymesh        = ymesh;
            tags.originalCTzmesh        = zmesh;
            xmesh                       = -xmesh;
            ymesh                       = ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;
            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.grid1Units             = abs(temp_diff_x(1));
            tags.grid2Units             = abs(temp_diff_y(1));
        end
        tags.xcoordOfNormaliznPoint = '';
        tags.ycoordOfNormaliznPoint = '';
        tags.zcoordOfNormaliznPoint = '';
    else                                        % FFP
        study_array                 = flipdim(study_array,3);
        tags.hio                    = 'OUT';
        tags.pos                    = 'NOSE DOWN';
        if strcmpi('CT',type)~=1
            xmesh                       = -xmesh;
            ymesh                       = ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
            tags.coord1OFFirstPoint     = xmesh(1);
            tags.coord2OFFirstPoint     = ymesh(1);
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.horizontalGridInterval = temp_diff_x(1);
            tags.verticalGridInterval   = temp_diff_y(1);
        else
            tags.originalCTxmesh        = xmesh;
            tags.originalCTymesh        = ymesh;
            tags.originalCTzmesh        = zmesh;
            xmesh                       = -xmesh;
            ymesh                       = ymesh;
            zmesh                       = -zmesh;
            zmesh                       = flipdim(zmesh,1);
            %zmesh                       = zmesh-zmesh(1); % set origin to the first image transmitted
            tags.xOffset                = xmesh(1) + sqrt(power((xmesh(1)-xmesh(end)),2))./2;
            tags.yOffset                = ymesh(1) - sqrt(power((ymesh(1)-ymesh(end)),2))./2;
            temp_diff_x                 = diff(xmesh);
            temp_diff_y                 = diff(ymesh);
            tags.grid1Units             = abs(temp_diff_x(1));
            tags.grid2Units             = abs(temp_diff_y(1));
        end
        tags.xcoordOfNormaliznPoint = '';
        tags.ycoordOfNormaliznPoint = '';
        tags.zcoordOfNormaliznPoint = '';
    end
else
    if PatientPosition==1                       % HFS flip dimensions
        xmesh                       = xmesh;
        ymesh                       = -ymesh;
        zmesh                       = -zmesh;
        for jj=1:size(study_array,1)            % loop though the number of VOIs
            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections
                % reverse Z
                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);
                % reverse Y
                study_array{jj,2}{kk}(:,2)=-study_array{jj,2}{kk}(:,2);
            end
        end
    elseif PatientPosition==2                   % FFS flip dimensions
        xmesh                       = xmesh;
        ymesh                       = -ymesh;
        zmesh                       = -zmesh;
        for jj=1:size(study_array,1)            % loop though the number of VOIs
            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections
                % reverse Z
                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);
                % reverse Y
                study_array{jj,2}{kk}(:,2)=-study_array{jj,2}{kk}(:,2);
            end
        end
    elseif PatientPosition==3                   % HFP nothing to do
        xmesh                       = -xmesh;
        ymesh                       = ymesh;
        zmesh                       = -zmesh;
        for jj=1:size(study_array,1)            % loop though the number of VOIs
            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections
                % reverse Z
                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);
                % reverse X
                study_array{jj,2}{kk}(:,1)=-study_array{jj,2}{kk}(:,1);
            end
        end
    else
        xmesh                       = -xmesh;
        ymesh                       = ymesh;
        zmesh                       = -zmesh;
        for jj=1:size(study_array,1)            % loop though the number of VOIs
            for kk=1:size(study_array{jj,2},1)  % loop though the number of sections
                % reverse Z
                study_array{jj,2}{kk}(:,3)=-study_array{jj,2}{kk}(:,3);
                % reverse X
                study_array{jj,2}{kk}(:,1)=-study_array{jj,2}{kk}(:,1);
            end
        end
    end
end

% Return data
study{2,1}=study_array;


text:
function Y = dec2(X);
%Y = dec2(X) downsampling of a matrix by 2
%
%    X - input matrix
%
%    Y - output matrix

%    (Oliver Rockinger 16.08.99)

[a b] = size(X);
Y     = X(1:2:a, 1:2:b);

author: xingchenzhang

repo: VIFB

save_path: github-repos/MATLAB/xingchenzhang-VIFB


text:
function initialized = fgrabm_isinit()
%initialized = FGRABM_ISINIT() FrameGrabM Tell if initialized
%   FGRABM_ISINIT will return true if FrameGrabM and the underlying
%   LTI-CIVIL library is already initialized.
%
%   Version 0.8 - 06 March 2012
global FGRABM

% Had we initialized?
if isempty(FGRABM)
    initialized = false;
    return;
end

initialized = FGRABM.class.getState();

author: Sable

repo: mcbench-benchmarks