text:
function a = dbgetarrivals(databasePath, subset_expr)
    %DBGETARRIVALS Load arrivals from an Antelope CSS3.0 database
    %
    % arrivals = DBGETORIGINS(databasePath) opens the arrival table belonging to
    % the database specified by databasePath. The arrival table will be joined to
    % the assoc, origin and event tables too, if these are present. If all
    % of these is present, only arrivals corresponding to preferred origins
    % will be loaded. If assoc is present, but not event or origin, only
    % arrivals referenced in the assoc table are loaded.
    %
    % The output is a structure containing the fields:
    %   * arid
    %   * sta
    %   * chan
    %   * time (arrival date/time converted from epoch to MATLAB datenum)
    %   * iphase
    %   * amp
    %   * snr
    %   * seaz
    %   * deltim
    %   * iphase
    %   * delta
    %   * otime (origin date/time converted from epoch to MATLAB datenum)
    %   * orid
    %   * evid
    %   * timeres
    %   * traveltime (= time - otime)
    %
    % All these fields are vectors of numbers, or cell arrays of strings.
    % If you want more fields adding, please email Glenn
    %
    % arrivals = DBGETARRIVALS(databasePath, subset_expression) evaluates the
    % subset specified before reading the arrivals. subset_expression must
    % be a valid expression accepted by dbe/dbeval.

    % Author: Glenn Thompson
    %
    %% To do:
    %   test

    %% Load the earthquake catalogue

    % Initialize output so we don't crash if return early
    a = struct('sta', [], 'chan',[], 'time', [], 'arid',[], 'amp',[], ...
        'snr',[], 'seaz', [], 'deltim', [], 'iphase', {}, 'delta', [], 'otime', [], ...
        'orid', [], 'evid', [], 'timeres', [], 'traveltime', []);

    % Check the database descriptor exists - if not abort
    if ~exist(databasePath, 'file')
        warning(sprintf('Database %s does not exist, please type in a different one',databasePath));
        return
    end
    debug.print_debug(0, sprintf('Loading data from %s',databasePath));
    ARRIVAL_TABLE_PRESENT = antelope.dbtable_present(databasePath, 'arrival');
    if (ARRIVAL_TABLE_PRESENT) % Open the arrival table, subset if expr exists
        db = dbopen(databasePath, 'r');
        db = dblookup_table(db, 'arrival');
        numarrivals = dbquery(db,'dbRECORD_COUNT');
        debug.print_debug(1,sprintf('Got %d records from %s.arrival',numarrivals,databasePath));
        if numarrivals > 0
            ASSOC_TABLE_PRESENT = antelope.dbtable_present(databasePath, 'assoc');
            ORIGIN_TABLE_PRESENT = antelope.dbtable_present(databasePath, 'origin');
            EVENT_TABLE_PRESENT = antelope.dbtable_present(databasePath, 'event');

            if (ASSOC_TABLE_PRESENT)
                % open and join the assoc table
                db2 = dblookup_table( db , 'assoc');
                db = dbjoin(db, db2);

                if dbnrecs(db) > 0 & (ORIGIN_TABLE_PRESENT)
                    % open and join the origin table
                    db3=dblookup_table( db, 'origin');
                    db= dbjoin(db, db3);

                    if dbnrecs(db) > 0 & (EVENT_TABLE_PRESENT)
                        % open and join the event table and subset for prefor
                        db4=dblookup_table( db, 'event');
                        db= dbjoin(db, db4);
                        %dbunjoin(db, 'dbview2')
                        db = dbsubset( db, 'origin.orid == event.prefor');
                    end
                end
            end
            if exist('subset_expr','var')
                db = dbsubset(db, subset_expr);
            end

            if dbnrecs(db)>0

                % read (some) fields & close db
                dbsave_view(db)
                [a.sta, a.chan, a.time, a.phase, a.arid, a.amp, a.snr, a.deltim] = dbgetv(db, 'sta', 'chan', 'arrival.time', 'iphase', 'arid', 'amp', 'snr', 'deltim');
                if (ASSOC_TABLE_PRESENT)
                    [a.delta, a.seaz, a.esaz, a.timeres] = dbgetv(db, 'assoc.delta', 'assoc.seaz', 'assoc.esaz', 'assoc.timeres');
                end
                if (ORIGIN_TABLE_PRESENT)
                    [a.otime, a.orid, a.evid] = dbgetv(db, 'origin.time', 'origin.orid', 'origin.evid');
                    a.otime
                    a.traveltime = a.time - a.otime;
                end

                dbclose(db);

                % Cell arrays don't get created if only 1 row
                if strcmp(class(a.sta),'char')
                   a.sta = {a.sta};
                   a.chan = {a.chan};
                   a.iphase = {a.iphase};
                end

                % Times are all in epoch
                a.time = epoch2datenum(a.time);
                a.otime = epoch2datenum(a.otime);

                % Display counts
                fprintf('\n%d arrivals\n',numel(a.time));
            end

        end
    end

end


text:
%--- help for mdd/laplace_mcmc ---
%
%mdd/laplace_mcmc is a function.
%    log_mdd = laplace_mcmc(obj, ~, ~)
%

author: jmaih


text:
%randsample(V,n,true,distribution) returns a set of n values sampled
% at random from the integers 1 through V with replacement using distribution
% 'distribution'
%
% replacing true with false causes sampling w/out replacement
% omitting the distribution causes a default to the uniform distribution
%
% Copyright (C) Daphne Koller, Stanford University, 2012

function [v] = randsample(vals,numSamp,replace,weightIncrements)

  vals = vals(:);
  if(length(vals)==1)
    maxval = vals;
    vals = 1:maxval;
  else
    maxval = length(vals);
  end

  if(exist('replace','var')~=1)
    replace = true;
  end
  if(exist('weightIncrements','var')~=1)
    weightIncrements = (1/maxval)*ones(maxval,1);
    weights = (1/maxval):(1/maxval):1;
  else
    weightIncrements = weightIncrements(:)/sum(weightIncrements(:));
    weights = zeros(size(weightIncrements));
    weights(1) = weightIncrements(1);
    for i = 2:length(weightIncrements)
      weights(i) = weightIncrements(i)+weights(i-1);
    end
  end

  weights = [0; weights(:)];

  %now do the sampling
  v = [];
  probs = rand(numSamp,1);
  for i=1:numSamp
    curInd = find((weights(1:end-1)<=probs(i))&(weights(2:end)>=probs(i)));
    v(end+1)=vals(curInd);
    if(replace~=true)
      vals(curInd)=[];
      weightIncrements(curInd)=[];
      weightIncrements = weightIncrements(:)/sum(weightIncrements(:));
      weights = zeros(size(weightIncrements));
      for i = 2:length(weightIncrements)
        weights(i) = weightIncrements(i)+weights(i-1);
      end
    end
  end

end

author: anhncs

repo: Probabilistic-Graphical-Models


text:
function value = normal_01_moment ( order )

%*****************************************************************************80
%
%% NORMAL_01_MOMENT evaluates moments of the Normal 01 PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 August 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer ORDER, the order of the moment.
%    0 <= ORDER.
%
%    Output, real VALUE, the value of the moment.
%
  if ( mod ( order, 2 ) == 0 )
    value = r8_factorial2 ( order - 1 );
  else
    value = 0.0;
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [TrainData, TestData, TrainLabel, TestLabel] = createData_CDPLSA()

    % load source domain 1
    A = csvread('CD_PLSA/data/Train1.data');
    TrainX1 = spconvert(A);
    C = textread('CD_PLSA/data/Train1.label');
    TrainY1 = C';
    % load source domain 2
    A = csvread('CD_PLSA/data/Train2.data');
    TrainX2 = spconvert(A);
    C = textread('CD_PLSA/data/Train2.label');
    TrainY2 = C';
    % load source domain 3
    A = csvread('CD_PLSA/data/Train3.data');
    TrainX3 = spconvert(A);
    C = textread('CD_PLSA/data/Train3.label');
    TrainY3 = C';

    % load target domain
    A = csvread('CD_PLSA/data/Test.data');
    TestX = spconvert(A);
    C = textread('CD_PLSA/data/Test.label');
    TestY = C';

    TrainData{1,1} = TrainX1;
    TrainLabel{1,1} = TrainY1;
    TrainData{1,2} = TrainX2;
    TrainLabel{1,2} = TrainY2;
    TrainData{1,3} = TrainX3;
    TrainLabel{1,3} = TrainY3;
    TestData{1,1} = TestX;
    TestLabel{1,1} = TestY;
    save inputData.mat TrainData TrainLabel TestData TestLabel
    clear TrainX1 TrainX2 TrainX3 TrainY1 TrainY2 TrainY3 TestX TestY
end

author: FuzhenZhuang

repo: Transfer-Learning-Toolkit


text:
classdef Tx < adi.AD9361.Tx

    methods
        %% Constructor
        function obj = Tx(varargin)
            % Returns the matlabshared.libiio.base object
            coder.allowpcode('plain');
            obj = obj@adi.AD9361.Tx(varargin{:});
        end
    end

end

author: analogdevicesinc


text:
function varargout = dsxy2figxy2(varargin)
% dsxy2figxy -- Transform point or position from axis to figure coords
% Transforms [axx axy] or [xypos] from axes hAx (data) coords into coords
% wrt GCF for placing annotation objects that use figure coords into data
% space. The annotation objects this can be used for are
%    arrow, doublearrow, textarrow
%    ellipses (coordinates must be transformed to [x, y, width, height])
% Note that line, text, and rectangle anno objects already are placed
% on a plot using axes coordinates and must be located within an axes.
% Usage: Compute a position and apply to an annotation, e.g.,
%   [axx axy] = ginput(2);
%   [figx figy] = getaxannopos(gca, axx, axy);
%   har = annotation('textarrow',figx,figy);
%   set(har,'String',['(' num2str(axx(2)) ',' num2str(axy(2)) ')'])
%% Obtain arguments (only limited argument checking is performed).
% Determine if axes handle is specified
if length(varargin{1})== 1 && ishandle(varargin{1}) && ...
  strcmp(get(varargin{1},'type'),'axes')
 hAx = varargin{1};
 varargin = varargin(2:end);
else
 hAx = gca;
end;
% Parse either a position vector or two 2-D point tuples
if length(varargin)==1 % Must be a 4-element POS vector
 pos = varargin{1};
else
 [x,y] = deal(varargin{:});  % Two tuples (start & end points)
end
%% Get limits
axun = get(hAx,'Units');
set(hAx,'Units','normalized');  % Need normaized units to do the xform
axpos = get(hAx,'Position');
axlim = axis(hAx);              % Get the axis limits [xlim ylim (zlim)]
axwidth = diff(axlim(1:2));
axheight = diff(axlim(3:4));
yisreversed = strcmpi(get(hAx,'ydir'),'reverse');
xisreversed = strcmpi(get(hAx,'xdir'),'reverse');
%% Transform data from figure space to data space
if exist('x','var')     % Transform a and return pair of points
  xout = (x-axlim(1))/axwidth;
  yout = (y-axlim(3))/axheight;
  if xisreversed,
    xout = 1 - xout;
  end
  if yisreversed
    yout = 1 - yout;
  end

  varargout{1} = xout*axpos(3) + axpos(1);
  varargout{2} = yout*axpos(4) + axpos(2);
else                    % Transform and return a position rectangle
  xout = (pos(1)-axlim(1))/axwidth;
  yout = (pos(2)-axlim(3))/axheight;
  if xisreversed,
    xout = 1 - xout;
  end
  if yisreversed,
    yout = 1 - yout;
  end
  pos(1) = xout*axpos(3) + axpos(1);
  pos(2) = yout*axpos(4) + axpos(2);
  pos(3) = pos(3)*axpos(3)/axwidth;
  pos(4) = pos(4)*axpos(4)/axheight;
  varargout{1} = pos;
end
%% Restore axes units
set(hAx,'Units',axun)

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


function mdnet_prepare_model()
% MDNET_PREPARE_MODEL
% Prepare a initial CNN model for learning MDNet.
%
% conv1-3 are adopted from VGG-M network.
% fc4-fc6 are randomly initialized.
% fc6 will be replaced by multiple domain-specific layers when training MDNet.
%
% Hyeonseob Nam, 2015
%

% conv1-3 layers from VGG-M network pretrained on ImageNet
src_model = './models/imagenet-vgg-m-conv1-3.mat';
% output network
dst_model = './models/mdnet_init.mat';

if exist(dst_model,'file')
    return;
end

%% load conv layers
load(src_model);

new_layers = {};
for i=1:numel(layers)
    if strcmp(layers{i}.name,'conv4'), break; end
    switch (layers{i}.type)
        case 'conv'
            layers{i}.filters = layers{i}.weights{1};
            layers{i}.biases = layers{i}.weights{2};
            layers{i} = rmfield(layers{i},'weights');
            layers{i}.pad = 0;
            last_dim = size(layers{i}.biases,2);
        case 'pool'
            layers{i}.pad = 0;
    end
    new_layers{end+1} = layers{i};
end

%% init fc layers
scal = 1 ;
init_bias = 0.1;

% Block 4
new_layers{end+1} = struct('type', 'conv', ...
                           'name', 'fc4', ...
                           'filters', 0.01/scal * randn(3,3,last_dim,512,'single'),...
                           'biases', init_bias*ones(1,512,'single'), ...
                           'stride', 1, ...
                           'pad', 0, ...
                           'filtersLearningRate', 10, ...
                           'biasesLearningRate', 20, ...
                           'filtersWeightDecay', 1, ...
                           'biasesWeightDecay', 0) ;
new_layers{end+1} = struct('type', 'relu', 'name', 'relu4') ;
new_layers{end+1} = struct('type', 'dropout', 'name', 'drop4', 'rate', 0.5) ;

% Block 5
new_layers{end+1} = struct('type', 'conv', ...
                           'name', 'fc5', ...
                           'filters', 0.01/scal * randn(1,1,512,512,'single'),...
                           'biases', init_bias*ones(1,512,'single'), ...
                           'stride', 1, ...
                           'pad', 0, ...
                           'filtersLearningRate', 10, ...
                           'biasesLearningRate', 20, ...
                           'filtersWeightDecay', 1, ...
                           'biasesWeightDecay', 0) ;
new_layers{end+1} = struct('type', 'relu', 'name', 'relu5') ;
new_layers{end+1} = struct('type', 'dropout', 'name', 'drop5', 'rate', 0.5) ;

% Block 6
new_layers{end+1} = struct('type', 'conv', ...
                           'name', 'fc6', ...
                           'filters', 0.01/scal * randn(1,1,512,2,'single'), ...
                           'biases', zeros(1, 2, 'single'), ...
                           'stride', 1, ...
                           'pad', 0, ...
                           'filtersLearningRate', 10, ...
                           'biasesLearningRate', 20, ...
                           'filtersWeightDecay', 1, ...
                           'biasesWeightDecay', 0) ;
new_layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;

clear layers; layers = new_layers;
save(dst_model,'layers');


text:
function y = GUSFT_Toeplitz(x,lambda);
% GUSFT_Toeplitz: Gram matrix associated with the nonuniform FT
%  Usage:
%     y = GUSFT_Toeplitz(x,lambda);
%  Inputs:
%    x       vector of length n
%    lambda  Fourier multiplier of length 2n -1
%  Outputs:
%    y       vector of length n
%  Description:
%    Performs A'A where A is the nonuniform FT in the
%    Fourier domain. A'A has a Toeplitz structure which can be
%    embedded in a larger circulant matrix.  Applying A'A is a
%    multiplication in Fourier space with weights lambda. Note that
%    lambda specifies the unequispaced grid).
%  See Also
%    USFT_simple, USFFT, MakeFourierDiagonal
%
% By Emmanuel candes, 2003-2004

  n = length(x);
  extended.x = [x;zeros(n-1,1)];
  y = fft(ifft(extended.x) .* lambda);
  y = y(1:n);

author: thomaskuestner


text:
function [ avw, machine ] = avw_img_read(fileprefix,IMGorient,machine,verbose)

% avw_img_read - read Analyze format data image (*.img)
%
% [ avw, machine ] = avw_img_read(fileprefix,[orient],[machine],[verbose])
%
% fileprefix - a string, the filename without the .img extension
%
% orient - read a specified orientation, integer values:
%
%          '', use header history orient field
%          0,  transverse unflipped (LAS*)
%          1,  coronal unflipped (LA*S)
%          2,  sagittal unflipped (L*AS)
%          3,  transverse flipped (LPS*)
%          4,  coronal flipped (LA*I)
%          5,  sagittal flipped (L*AI)
%
% where * follows the slice dimension and letters indicate +XYZ
% orientations (L left, R right, A anterior, P posterior,
% I inferior, & S superior).
%
% Some files may contain data in the 3-5 orientations, but this
% is unlikely. For more information about orientation, see the
% documentation at the end of this .m file.  See also the
% AVW_FLIP function for orthogonal reorientation.
%
% machine - a string, see machineformat in fread for details.
%           The default here is 'ieee-le' but the routine
%           will automatically switch between little and big
%           endian to read any such Analyze header.  It
%           reports the appropriate machine format and can
%           return the machine value.
%
% verbose - the default is to output processing information to the command
%           window.  If verbose = 0, this will not happen.
%
% Returned values:
%
% avw.hdr - a struct with image data parameters.
% avw.img - a 3D matrix of image data (double precision).
%
% A returned 3D matrix will correspond with the
% default ANALYZE coordinate system, which
% is Left-handed:
%
% X-Y plane is Transverse
% X-Z plane is Coronal
% Y-Z plane is Sagittal
%
% X axis runs from patient right (low X) to patient Left (high X)
% Y axis runs from posterior (low Y) to Anterior (high Y)
% Z axis runs from inferior (low Z) to Superior (high Z)
%
% The function can read a 4D Analyze volume, but only if it is in the
% axial unflipped orientation.
%
% See also: avw_hdr_read (called by this function),
%           avw_view, avw_write, avw_img_write, avw_flip
%

% $Revision$ $Date: 2009/01/14 09:24:45 $

% Licence:  GNU GPL, no express or implied warranties
% History:  05/2002, Darren.Weber@flinders.edu.au
%                    The Analyze format is copyright
%                    (c) Copyright, 1986-1995
%                    Biomedical Imaging Resource, Mayo Foundation
%           01/2003, Darren.Weber@flinders.edu.au
%                    - adapted for matlab v5
%                    - revised all orientation information and handling
%                      after seeking further advice from AnalyzeDirect.com
%           03/2003, Darren.Weber@flinders.edu.au
%                    - adapted for -ve pixdim values (non standard Analyze)
%           07/2004, chodkowski@kennedykrieger.org, added ability to
%                    read volumes with dimensionality greather than 3.
%  a >3D volume cannot be flipped.  and error is thrown if a volume of
%  greater than 3D (ie, avw.hdr.dime.dim(1) > 3) requests a data flip
%  (ie, avw.hdr.hist.orient ~= 0 ).  i pulled the transfer of read-in
%  data (tmp) to avw.img out of any looping mechanism.  looping is not
%  necessary as the data is already in its correct orientation.  using
%  'reshape' rather than looping should be faster but, more importantly,
%  it allows the reading in of N-D volumes. See lines 270-280.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if ~exist('IMGorient','var'), IMGorient = ''; end
if ~exist('machine','var'), machine = 'ieee-le'; end
if ~exist('verbose','var'), verbose = 1; end

if isempty(IMGorient), IMGorient = ''; end
if isempty(machine), machine = 'ieee-le'; end
if isempty(verbose), verbose = 1; end

if ~exist('fileprefix','var'),
  msg = sprintf('...no input fileprefix - see help avw_img_read\n\n');
  ft_error(msg);
end
if contains(fileprefix, '.hdr')
  fileprefix = strrep(fileprefix,'.hdr','');
end
if contains(fileprefix, '.img')
  fileprefix = strrep(fileprefix,'.img','');
end

% MAIN

% Read the file header
[ avw, machine ] = avw_hdr_read(fileprefix,machine,verbose);

avw = read_image(avw,IMGorient,machine,verbose);

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ avw ] = read_image(avw,IMGorient,machine,verbose)

fid = fopen_or_error(sprintf('%s.img',avw.fileprefix),'r',machine);

if verbose,
    ver = '[$Revision$]';
    fprintf('\nAVW_IMG_READ [v%s]\n',ver(12:16));  tic;
end

% short int bitpix;    /* Number of bits per pixel; 1, 8, 16, 32, or 64. */
% short int datatype      /* Datatype for this image set */
% /*Acceptable values for datatype are*/
% #define DT_NONE             0
% #define DT_UNKNOWN          0    /*Unknown data type*/
% #define DT_BINARY           1    /*Binary             ( 1 bit per voxel)*/
% #define DT_UNSIGNED_CHAR    2    /*Unsigned character ( 8 bits per voxel)*/
% #define DT_SIGNED_SHORT     4    /*Signed short       (16 bits per voxel)*/
% #define DT_SIGNED_INT       8    /*Signed integer     (32 bits per voxel)*/
% #define DT_FLOAT           16    /*Floating point     (32 bits per voxel)*/
% #define DT_COMPLEX         32    /*Complex (64 bits per voxel; 2 floating point numbers)/*
% #define DT_DOUBLE          64    /*Double precision   (64 bits per voxel)*/
% #define DT_RGB            128    /*A Red-Green-Blue datatype*/
% #define DT_ALL            255    /*Undocumented*/

switch double(avw.hdr.dime.bitpix),
  case  1,   precision = 'bit1';
  case  8,   precision = 'uchar';
  case 16,   precision = 'int16';
  case 32,
    if     isequal(avw.hdr.dime.datatype, 8), precision = 'int32';
    else                                      precision = 'single';
    end
  case 64,   precision = 'double';
  otherwise,
    precision = 'uchar';
    if verbose, fprintf('...precision undefined in header, using ''uchar''\n'); end
end

% read the whole .img file into matlab (faster)
if verbose,
    fprintf('...reading %s Analyze %s image format.\n',machine,precision);
end
fseek(fid,0,'bof');
% adjust for matlab version
ver = version;
ver = str2num(ver(1));
if ver < 6,
  tmp = fread(fid,inf,sprintf('%s',precision));
else
  tmp = fread(fid,inf,sprintf('%s=>double',precision));
end
fclose(fid);

% Update the global min and max values
avw.hdr.dime.glmax = max(double(tmp));
avw.hdr.dime.glmin = min(double(tmp));

%---------------------------------------------------------------
% Now partition the img data into xyz

% --- first figure out the size of the image

% short int dim[ ];      /* Array of the image dimensions */
%
% dim[0]      Number of dimensions in database; usually 4.
% dim[1]      Image X dimension;  number of pixels in an image row.
% dim[2]      Image Y dimension;  number of pixel rows in slice.
% dim[3]      Volume Z dimension; number of slices in a volume.
% dim[4]      Time points; number of volumes in database.

PixelDim = double(avw.hdr.dime.dim(2));
RowDim   = double(avw.hdr.dime.dim(3));
SliceDim = double(avw.hdr.dime.dim(4));
TimeDim  = double(avw.hdr.dime.dim(5));

PixelSz  = double(avw.hdr.dime.pixdim(2));
RowSz    = double(avw.hdr.dime.pixdim(3));
SliceSz  = double(avw.hdr.dime.pixdim(4));
TimeSz   = double(avw.hdr.dime.pixdim(5));

% ---- NON STANDARD ANALYZE...

% Some Analyze files have been found to set -ve pixdim values, eg
% the MNI template avg152T1_brain in the FSL etc/standard folder,
% perhaps to indicate flipped orientation?  If so, this code below
% will NOT handle the flip correctly!
if PixelSz < 0,
  ft_warning('X pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(2))');
  PixelSz = abs(PixelSz);
  avw.hdr.dime.pixdim(2) = single(PixelSz);
end
if RowSz < 0,
  ft_warning('Y pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(3))');
  RowSz = abs(RowSz);
  avw.hdr.dime.pixdim(3) = single(RowSz);
end
if SliceSz < 0,
  ft_warning('Z pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(4))');
  SliceSz = abs(SliceSz);
  avw.hdr.dime.pixdim(4) = single(SliceSz);
end

% ---- END OF NON STANDARD ANALYZE

% --- check the orientation specification and arrange img accordingly
if ~isempty(IMGorient),
  if ischar(IMGorient),
    avw.hdr.hist.orient = uint8(str2num(IMGorient));
  else
    avw.hdr.hist.orient = uint8(IMGorient);
  end
end

if isempty(avw.hdr.hist.orient),
  msg = [ '...unspecified avw.hdr.hist.orient, using default 0\n',...
      '   (check image and try explicit IMGorient option).\n'];
  fprintf(msg);
  avw.hdr.hist.orient = uint8(0);
end

% --- check if the orientation is to be flipped for a volume with more
% --- than 3 dimensions.  this logic is currently unsupported so throw
% --- an error.  volumes of any dimensionality may be read in *only* as
% --- unflipped, ie, avw.hdr.hist.orient == 0
if ( TimeDim > 1 ) && (avw.hdr.hist.orient ~= 0 ),
   msg = [ 'ERROR: This volume has more than 3 dimensions *and* ', ...
           'requires flipping the data.  Flipping is not supported ', ...
           'for volumes with dimensionality greater than 3.  Set ', ...
           'avw.hdr.hist.orient = 0 and flip your volume after ', ...
           'calling this function' ];
   msg = ft_error( '%s (%s).', msg, mfilename );
   ft_error( msg );
end

switch double(avw.hdr.hist.orient),

  case 0, % transverse unflipped

    % orient = 0:  The primary orientation of the data on disk is in the
    % transverse plane relative to the object scanned.  Most commonly, the fastest
    % moving index through the voxels that are part of this transverse image would
    % span the right-left extent of the structure imaged, with the next fastest
    % moving index spanning the posterior-anterior extent of the structure.  This
    % 'orient' flag would indicate to Analyze that this data should be placed in
    % the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension
    % being the slice direction.

    % For the 'transverse unflipped' type, the voxels are stored with
    % Pixels in 'x' axis (varies fastest) - from patient right to left
    % Rows in   'y' axis                  - from patient posterior to anterior
    % Slices in 'z' axis                  - from patient inferior to superior

    if verbose, fprintf('...reading axial unflipped orientation\n'); end

    % -- This code will handle nD files
    dims = double( avw.hdr.dime.dim(2:end) );
    % replace dimensions of 0 with 1 to be used in reshape
    idx = find( dims == 0 );
    dims( idx ) = 1;
    avw.img = reshape( tmp, dims );

    % -- The code above replaces this
    %         avw.img = zeros(PixelDim,RowDim,SliceDim);
    %
    %         n = 1;
    %         x = 1:PixelDim;
    %         for z = 1:SliceDim,
    %             for y = 1:RowDim,
    %                 % load Y row of X values into Z slice avw.img
    %                 avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
    %                 n = n + PixelDim;
    %             end
    %         end

    % no need to rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim

case 1, % coronal unflipped

    % orient = 1:  The primary orientation of the data on disk is in the coronal
    % plane relative to the object scanned.  Most commonly, the fastest moving
    % index through the voxels that are part of this coronal image would span the
    % right-left extent of the structure imaged, with the next fastest moving
    % index spanning the inferior-superior extent of the structure.  This 'orient'
    % flag would indicate to Analyze that this data should be placed in the X-Z
    % plane of the 3D Analyze Coordinate System, with the Y dimension being the
    % slice direction.

    % For the 'coronal unflipped' type, the voxels are stored with
    % Pixels in 'x' axis (varies fastest) - from patient right to left
    % Rows in   'z' axis                  - from patient inferior to superior
    % Slices in 'y' axis                  - from patient posterior to anterior

    if verbose, fprintf('...reading coronal unflipped orientation\n'); end

    avw.img = zeros(PixelDim,SliceDim,RowDim);

    n = 1;
    x = 1:PixelDim;
    for y = 1:SliceDim,
      for z = 1:RowDim,
        % load Z row of X values into Y slice avw.img
        avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
        n = n + PixelDim;
      end
    end

    % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
    avw.hdr.dime.dim(2:4) = int16([PixelDim,SliceDim,RowDim]);
    avw.hdr.dime.pixdim(2:4) = single([PixelSz,SliceSz,RowSz]);

  case 2, % sagittal unflipped

    % orient = 2:  The primary orientation of the data on disk is in the sagittal
    % plane relative to the object scanned.  Most commonly, the fastest moving
    % index through the voxels that are part of this sagittal image would span the
    % posterior-anterior extent of the structure imaged, with the next fastest
    % moving index spanning the inferior-superior extent of the structure.  This
    % 'orient' flag would indicate to Analyze that this data should be placed in
    % the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension
    % being the slice direction.

    % For the 'sagittal unflipped' type, the voxels are stored with
    % Pixels in 'y' axis (varies fastest) - from patient posterior to anterior
    % Rows in   'z' axis                  - from patient inferior to superior
    % Slices in 'x' axis                  - from patient right to left

    if verbose, fprintf('...reading sagittal unflipped orientation\n'); end

    avw.img = zeros(SliceDim,PixelDim,RowDim);

    n = 1;
    y = 1:PixelDim;         % posterior to anterior (fastest)

    for x = 1:SliceDim,     % right to left (slowest)
      for z = 1:RowDim,   % inferior to superior

        % load Z row of Y values into X slice avw.img
        avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
        n = n + PixelDim;
      end
    end

    % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
    avw.hdr.dime.dim(2:4) = int16([SliceDim,PixelDim,RowDim]);
    avw.hdr.dime.pixdim(2:4) = single([SliceSz,PixelSz,RowSz]);

    %--------------------------------------------------------------------------------
    % Orient values 3-5 have the second index reversed in order, essentially
    % 'flipping' the images relative to what would most likely become the vertical
    % axis of the displayed image.
    %--------------------------------------------------------------------------------

  case 3, % transverse/axial flipped

    % orient = 3:  The primary orientation of the data on disk is in the
    % transverse plane relative to the object scanned.  Most commonly, the fastest
    % moving index through the voxels that are part of this transverse image would
    % span the right-left extent of the structure imaged, with the next fastest
    % moving index spanning the *anterior-posterior* extent of the structure.  This
    % 'orient' flag would indicate to Analyze that this data should be placed in
    % the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension
    % being the slice direction.

    % For the 'transverse flipped' type, the voxels are stored with
    % Pixels in 'x' axis (varies fastest) - from patient right to Left
    % Rows in   'y' axis                  - from patient anterior to Posterior *
    % Slices in 'z' axis                  - from patient inferior to Superior

    if verbose, fprintf('...reading axial flipped (+Y from Anterior to Posterior)\n'); end

    avw.img = zeros(PixelDim,RowDim,SliceDim);

    n = 1;
    x = 1:PixelDim;
    for z = 1:SliceDim,
      for y = RowDim:-1:1, % flip in Y, read A2P file into P2A 3D matrix

        % load a flipped Y row of X values into Z slice avw.img
        avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
        n = n + PixelDim;
      end
    end

    % no need to rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim

  case 4, % coronal flipped

    % orient = 4:  The primary orientation of the data on disk is in the coronal
    % plane relative to the object scanned.  Most commonly, the fastest moving
    % index through the voxels that are part of this coronal image would span the
    % right-left extent of the structure imaged, with the next fastest moving
    % index spanning the *superior-inferior* extent of the structure.  This 'orient'
    % flag would indicate to Analyze that this data should be placed in the X-Z
    % plane of the 3D Analyze Coordinate System, with the Y dimension being the
    % slice direction.

    % For the 'coronal flipped' type, the voxels are stored with
    % Pixels in 'x' axis (varies fastest) - from patient right to Left
    % Rows in   'z' axis                  - from patient superior to Inferior*
    % Slices in 'y' axis                  - from patient posterior to Anterior

    if verbose, fprintf('...reading coronal flipped (+Z from Superior to Inferior)\n'); end

    avw.img = zeros(PixelDim,SliceDim,RowDim);

    n = 1;
    x = 1:PixelDim;
    for y = 1:SliceDim,
      for z = RowDim:-1:1, % flip in Z, read S2I file into I2S 3D matrix

        % load a flipped Z row of X values into Y slice avw.img
        avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
        n = n + PixelDim;
      end
    end

    % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
    avw.hdr.dime.dim(2:4) = int16([PixelDim,SliceDim,RowDim]);
    avw.hdr.dime.pixdim(2:4) = single([PixelSz,SliceSz,RowSz]);

  case 5, % sagittal flipped

    % orient = 5:  The primary orientation of the data on disk is in the sagittal
    % plane relative to the object scanned.  Most commonly, the fastest moving
    % index through the voxels that are part of this sagittal image would span the
    % posterior-anterior extent of the structure imaged, with the next fastest
    % moving index spanning the *superior-inferior* extent of the structure.  This
    % 'orient' flag would indicate to Analyze that this data should be placed in
    % the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension
    % being the slice direction.

    % For the 'sagittal flipped' type, the voxels are stored with
    % Pixels in 'y' axis (varies fastest) - from patient posterior to Anterior
    % Rows in   'z' axis                  - from patient superior to Inferior*
    % Slices in 'x' axis                  - from patient right to Left

    if verbose, fprintf('...reading sagittal flipped (+Z from Superior to Inferior)\n'); end

    avw.img = zeros(SliceDim,PixelDim,RowDim);

    n = 1;
    y = 1:PixelDim;

    for x = 1:SliceDim,
      for z = RowDim:-1:1, % flip in Z, read S2I file into I2S 3D matrix

        % load a flipped Z row of Y values into X slice avw.img
        avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
        n = n + PixelDim;
      end
    end

    % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
    avw.hdr.dime.dim(2:4) = int16([SliceDim,PixelDim,RowDim]);
    avw.hdr.dime.pixdim(2:4) = single([SliceSz,PixelSz,RowSz]);

  otherwise

    ft_error('unknown value in avw.hdr.hist.orient, try explicit IMGorient option.');

end

if verbose, t=toc; fprintf('...done (%5.2f sec).\n\n',t); end

return

% This function attempts to read the orientation of the
% Analyze file according to the hdr.hist.orient field of the
% header.  Unfortunately, this field is optional and not
% all programs will set it correctly, so there is no guarantee,
% that the data loaded will be correctly oriented.  If necessary,
% experiment with the 'orient' option to read the .img
% data into the 3D matrix of avw.img as preferred.
%

% (Conventions gathered from e-mail with support@AnalyzeDirect.com)
%
% 0  transverse unflipped
%       X direction first,  progressing from patient right to left,
%       Y direction second, progressing from patient posterior to anterior,
%       Z direction third,  progressing from patient inferior to superior.
% 1  coronal unflipped
%       X direction first,  progressing from patient right to left,
%       Z direction second, progressing from patient inferior to superior,
%       Y direction third,  progressing from patient posterior to anterior.
% 2  sagittal unflipped
%       Y direction first,  progressing from patient posterior to anterior,
%       Z direction second, progressing from patient inferior to superior,
%       X direction third,  progressing from patient right to left.
% 3  transverse flipped
%       X direction first,  progressing from patient right to left,
%       Y direction second, progressing from patient anterior to posterior,
%       Z direction third,  progressing from patient inferior to superior.
% 4  coronal flipped
%       X direction first,  progressing from patient right to left,
%       Z direction second, progressing from patient superior to inferior,
%       Y direction third,  progressing from patient posterior to anterior.
% 5  sagittal flipped
%       Y direction first,  progressing from patient posterior to anterior,
%       Z direction second, progressing from patient superior to inferior,
%       X direction third,  progressing from patient right to left.

%----------------------------------------------------------------------------
% From ANALYZE documentation...
%
% The ANALYZE coordinate system has an origin in the lower left
% corner. That is, with the subject lying supine, the coordinate
% origin is on the right side of the body (x), at the back (y),
% and at the feet (z). This means that:
%
% +X increases from right (R) to left (L)
% +Y increases from the back (posterior,P) to the front (anterior, A)
% +Z increases from the feet (inferior,I) to the head (superior, S)
%
% The LAS orientation is the radiological convention, where patient
% left is on the image right.  The alternative neurological
% convention is RAS (also Talairach convention).
%
% A major advantage of the Analzye origin convention is that the
% coordinate origin of each orthogonal orientation (transverse,
% coronal, and sagittal) lies in the lower left corner of the
% slice as it is displayed.
%
% Orthogonal slices are numbered from one to the number of slices
% in that orientation. For example, a volume (x, y, z) dimensioned
% 128, 256, 48 has:
%
%   128 sagittal   slices numbered 1 through 128 (X)
%   256 coronal    slices numbered 1 through 256 (Y)
%    48 transverse slices numbered 1 through  48 (Z)
%
% Pixel coordinates are made with reference to the slice numbers from
% which the pixels come. Thus, the first pixel in the volume is
% referenced p(1,1,1) and not at p(0,0,0).
%
% Transverse slices are in the XY plane (also known as axial slices).
% Sagittal slices are in the ZY plane.
% Coronal slices are in the ZX plane.
%
%----------------------------------------------------------------------------

%----------------------------------------------------------------------------
% E-mail from support@AnalyzeDirect.com
%
% The 'orient' field in the data_history structure specifies the primary
% orientation of the data as it is stored in the file on disk.  This usually
% corresponds to the orientation in the plane of acquisition, given that this
% would correspond to the order in which the data is written to disk by the
% scanner or other software application.  As you know, this field will contain
% the values:
%
% orient = 0 transverse unflipped
% 1 coronal unflipped
% 2 sagittal unflipped
% 3 transverse flipped
% 4 coronal flipped
% 5 sagittal flipped
%
% It would be vary rare that you would ever encounter any old Analyze 7.5
% files that contain values of 'orient' which indicate that the data has been
% 'flipped'.  The 'flipped flag' values were really only used internal to
% Analyze to precondition data for fast display in the Movie module, where the
% images were actually flipped vertically in order to accommodate the raster
% paint order on older graphics devices.  The only cases you will encounter
% will have values of 0, 1, or 2.
%
% As mentioned, the 'orient' flag only specifies the primary orientation of
% data as stored in the disk file itself.  It has nothing to do with the
% representation of the data in the 3D Analyze coordinate system, which always
% has a fixed representation to the data.  The meaning of the 'orient' values
% should be interpreted as follows:
%
% orient = 0:  The primary orientation of the data on disk is in the
% transverse plane relative to the object scanned.  Most commonly, the fastest
% moving index through the voxels that are part of this transverse image would
% span the right-left extent of the structure imaged, with the next fastest
% moving index spanning the posterior-anterior extent of the structure.  This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension
% being the slice direction.
%
% orient = 1:  The primary orientation of the data on disk is in the coronal
% plane relative to the object scanned.  Most commonly, the fastest moving
% index through the voxels that are part of this coronal image would span the
% right-left extent of the structure imaged, with the next fastest moving
% index spanning the inferior-superior extent of the structure.  This 'orient'
% flag would indicate to Analyze that this data should be placed in the X-Z
% plane of the 3D Analyze Coordinate System, with the Y dimension being the
% slice direction.
%
% orient = 2:  The primary orientation of the data on disk is in the sagittal
% plane relative to the object scanned.  Most commonly, the fastest moving
% index through the voxels that are part of this sagittal image would span the
% posterior-anterior extent of the structure imaged, with the next fastest
% moving index spanning the inferior-superior extent of the structure.  This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension
% being the slice direction.
%
% Orient values 3-5 have the second index reversed in order, essentially
% 'flipping' the images relative to what would most likely become the vertical
% axis of the displayed image.
%
% Hopefully you understand the difference between the indication this 'orient'
% flag has relative to data stored on disk and the full 3D Analyze Coordinate
% System for data that is managed as a volume image.  As mentioned previously,
% the orientation of patient anatomy in the 3D Analyze Coordinate System has a
% fixed orientation relative to each of the orthogonal axes.  This orientation
% is completely described in the information that is attached, but the basics
% are:
%
% Left-handed coordinate system
%
% X-Y plane is Transverse
% X-Z plane is Coronal
% Y-Z plane is Sagittal
%
% X axis runs from patient right (low X) to patient left (high X)
% Y axis runs from posterior (low Y) to anterior (high Y)
% Z axis runs from inferior (low Z) to superior (high Z)
%
%----------------------------------------------------------------------------

%----------------------------------------------------------------------------
% SPM2 NOTES from spm2 webpage: One thing to watch out for is the image
% orientation. The proper Analyze format uses a left-handed co-ordinate
% system, whereas Talairach uses a right-handed one. In SPM99, images were
% flipped at the spatial normalisation stage (from one co-ordinate system
% to the other). In SPM2b, a different approach is used, so that either a
% left- or right-handed co-ordinate system is used throughout. The SPM2b
% program is told about the handedness that the images are stored with by
% the spm_flip_analyze_images.m function and the defaults.analyze.flip
% parameter that is specified in the spm_defaults.m file. These files are
% intended to be customised for each site. If you previously used SPM99
% and your images were flipped during spatial normalisation, then set
% defaults.analyze.flip=1. If no flipping took place, then set
% defaults.analyze.flip=0. Check that when using the Display facility
% (possibly after specifying some rigid-body rotations) that:
%
% The top-left image is coronal with the top (superior) of the head displayed
% at the top and the left shown on the left. This is as if the subject is viewed
% from behind.
%
% The bottom-left image is axial with the front (anterior) of the head at the
% top and the left shown on the left. This is as if the subject is viewed from above.
%
% The top-right image is sagittal with the front (anterior) of the head at the
% left and the top of the head shown at the top. This is as if the subject is
% viewed from the left.
%----------------------------------------------------------------------------

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function cellInfo = Extended_States_Bus(varargin)
% EXTENDED_STATES_BUS returns a cell array containing bus object information
%
% Optional Input: 'false' will suppress a call to Simulink.Bus.cellToObject
%                 when the MATLAB file is executed.
% The order of bus element attributes is as follows:
%   ElementName, Dimensions, DataType, SampleTime, Complexity, SamplingMode, DimensionsMode, Min, Max, DocUnits, Description

suppressObject = false;
if nargin == 1 && islogical(varargin{1}) && varargin{1} == false
    suppressObject = true;
elseif nargin > 1
    error('Invalid input argument(s) encountered');
end

cellInfo = { ...
  { ...
    'AirSpeed_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'diff_pressure', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('Pa'), ''}; ...
{'temperature', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degC'), ''}; ...
    } ...
  } ...
  { ...
    'Auto_Cmd_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'p_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('rate x command in body frame')}; ...
{'q_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('rate y command in body frame')}; ...
{'r_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('rate z command in body frame')}; ...
{'phi_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('roll command')}; ...
{'theta_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('pitch command')}; ...
{'psi_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'psi_rate_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('yaw rate command')}; ...
{'x_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'y_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'z_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'lat_cmd', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'lon_cmd', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'alt_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'u_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity x command in control frame')}; ...
{'v_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity y command in control frame')}; ...
{'w_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity z command in control frame')}; ...
{'ax_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'ay_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'az_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'throttle_cmd', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('throttle command')}; ...
{'frame', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Coordinate Frame:\n0:FRAME_GLOBAL_NED\n1:FRAME_LOCAL_FRD\n2:FRAME_BODY_FRD')}; ...
{'reserved', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'cmd_mask', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Type mask for auto command:\n  1: p_cmd valid\n  2: q_cmd valid\n  3: r_cmd valid\n  4: phi_cmd valid\n  5: theta_cmd valid\n  6: psi__cmd_valid\n  7: psi_rate_cmd_valid\n  8: x_cmd valid\n  9: y_cmd valid\n10: z_cmd valid\n11: lat_cmd valid\n12: lon_cmd valid\n13: alt_cmd valid\n14: u_cmd valid\n15: v_cmd valid\n16: w_cmd valid\n17: ax_cmd valid\n18: ay_cmd valid\n19: ax_cmd valid\n20: throttle_cmd valid')}; ...
    } ...
  } ...
  { ...
    'Barometer_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'pressure', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('Pa'), ''}; ...
{'temperature', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('deg'), ''}; ...
    } ...
  } ...
  { ...
    'Commander_In_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'sp_waypoint', 3, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'cur_waypoint', 3, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'offboard_psi_0', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('The psi value when offboard mode entered, \nwhich is used for FRAME_LOCAL_FRD')}; ...
    } ...
  } ...
  { ...
    'Control_Out_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'actuator_cmd', 16, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
    } ...
  } ...
  { ...
    'Extended_States_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'temprature', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('deg'), ''}; ...
{'prop_vel', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'quat', 4, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'M_BO', [3 3], 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'M_OB', [3 3], 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'Va', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('Airspeed in body frame')}; ...
    } ...
  } ...
  { ...
    'FMS_Out_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), sprintf('fms output timestamp')}; ...
{'p_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('roll rate command in body frame')}; ...
{'q_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('pitch rate command in body frame')}; ...
{'r_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('yaw rate command in body frame')}; ...
{'phi_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('roll command in body frame')}; ...
{'theta_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), sprintf('pitch command in body frame')}; ...
{'psi_rate_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), sprintf('yaw rate command in body frame')}; ...
{'u_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity x command in control frame')}; ...
{'v_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity y command in control frame')}; ...
{'w_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), sprintf('velocity z command in control frame')}; ...
{'ax_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s^2'), sprintf('acceleration x command in control frame')}; ...
{'ay_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s^2'), sprintf('acceleration y command in control frame')}; ...
{'az_cmd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s^2'), sprintf('acceleration z command in control frame')}; ...
{'actuator_cmd', 16, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('actuator command')}; ...
{'throttle_cmd', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('throttle command')}; ...
{'cmd_mask', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Type mask for offboard mode:\n  1: p_cmd valid\n  2: q_cmd valid\n  3: r_cmd valid\n  4: phi_cmd valid\n  5: theta_cmd valid\n  6: psi_rate_cmd_valid\n  7: u_cmd valid\n  8: v_cmd valid\n  9: w_cmd valid\n10: ax_cmd valid\n11: ay_cmd valid\n12: ax_cmd valid\n13: throttle_cmd valid')}; ...
{'status', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum VehicleStatus\n\nvehicle status:\n0: None\n1: Disarm\n2: Standby\n3: Arm')}; ...
{'state', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum VehicleState\n\nvehicle state:\n0: None\n1: Disarm\n2: Standby\n3: Offboard\n4: Mission\n5: InvalidAutoMode\n6: Hold\n7: Acro\n8: Stabilize\n9: Altitude\n10: Position\n11: InvalidAssistMode\n12: Manual\n13: InvalidManualMode\n14: InvalidArmMode\n15: Land\n16: Return\n17: Takeoff')}; ...
{'ctrl_mode', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum ControlMode\n\ncontrol mode:\n0: None\n1: Manual\n2: Acro\n3: Stabilize\n4: ALTCTL\n5: POSCTL')}; ...
{'mode', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum PilotMode\n\npilot mode:\n0: None\n1: Manual\n2: Acro\n3: Stabilize\n4: Altitude\n5: Position\n6: Mission\n7: Offboard')}; ...
{'reset', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('reset the controller')}; ...
{'wp_consume', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('consumed waypoints')}; ...
{'wp_current', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('current waypoint')}; ...
{'reserved', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('enum of PilotMode')}; ...
    } ...
  } ...
  { ...
    'GCS_Cmd_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'mode', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'cmd_1', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 1')}; ...
{'cmd_2', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 2')}; ...
    } ...
  } ...
  { ...
    'GPS_uBlox_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'iTOW', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'year', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'month', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'day', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'hour', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'min', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'sec', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'valid', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'tAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'nano', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'fixType', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'flags', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'reserved1', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'numSV', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'lon', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'lat', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'height', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'hMSL', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'hAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'vAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'velN', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'velE', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'velD', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'gSpeed', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'heading', 1, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'sAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'headingAcc', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'pDOP', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'reserved2', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
    } ...
  } ...
  { ...
    'IMU_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'gyr_x', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'gyr_y', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'gyr_z', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'acc_x', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'acc_y', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'acc_z', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
    } ...
  } ...
  { ...
    'INS_Out_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'phi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'theta', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'psi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'quat', 4, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('unified'), ''}; ...
{'p', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'q', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'r', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'ax', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'ay', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'az', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'vn', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'ve', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'vd', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'airspeed', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'lat', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...
{'lon', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...
{'alt', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'lat_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...
{'lon_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('degree'), ''}; ...
{'alt_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'x_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'y_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'h_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'h_AGL', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'flag', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'status', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
    } ...
  } ...
  { ...
    'MAG_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'mag_x', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('gauss'), ''}; ...
{'mag_y', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('gauss'), ''}; ...
{'mag_z', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('gauss'), ''}; ...
    } ...
  } ...
  { ...
    'Mission_Data_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'valid_items', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'reserved', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'seq', 8, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Start from 0')}; ...
{'command', 8, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'frame', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'current', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'autocontinue', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'mission_type', 8, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'param1', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'param2', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'param3', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'param4', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'x', 8, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'y', 8, 'int32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'z', 8, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
    } ...
  } ...
  { ...
    'Optical_Flow_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'vx', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'vy', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'quality', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'reserved1', 1, 'uint8', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'reserved2', 1, 'uint16', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
    } ...
  } ...
  { ...
    'Pilot_Cmd_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'stick_yaw', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of yaw channel')}; ...
{'stick_throttle', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of throttle channel')}; ...
{'stick_roll', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of roll chanel')}; ...
{'stick_pitch', 1, 'single', -1, 'real', 'Sample', 'Fixed', -1, 1, '', sprintf('Stick value of pitch channel')}; ...
{'mode', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'cmd_1', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 1')}; ...
{'cmd_2', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Operation channel 2')}; ...
    } ...
  } ...
  { ...
    'Plant_States_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'phi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'theta', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'psi', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'rot_x_B', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'rot_y_B', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'rot_z_B', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad/s'), ''}; ...
{'acc_x_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'acc_y_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'acc_z_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s2'), ''}; ...
{'vel_x_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'vel_y_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'vel_z_O', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m/s'), ''}; ...
{'x_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'y_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'h_R', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'lat', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'lon', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'alt', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
{'lat_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'lon_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('rad'), ''}; ...
{'alt_0', 1, 'double', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
    } ...
  } ...
  { ...
    'Rangefinder_Bus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('ms'), ''}; ...
{'distance', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], sprintf('m'), ''}; ...
    } ...
  } ...
  { ...
    'StatesBus', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'V_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'Omega_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'Euler', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'Accel_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'dOmega_body', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'V_ned', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'X_ned', [3 1], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
{'LLA', [1 3], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Latitude, Longitude, Altitude')}; ...
{'DCM_be', [3 3], 'double', -1, 'real', 'Sample', 'Fixed', [], [], '', ''}; ...
    } ...
  } ...
  { ...
    'mavlink_fmt_pilot_cmd_t', ...
    '', ...
    '', ...
    'Auto', ...
    '-1', {...
{'timestamp', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('timestamp in milliseconds')}; ...
{'ls_lr', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Left stick left/right')}; ...
{'ls_ud', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Left stick up/down')}; ...
{'rs_lr', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Right stick left/right')}; ...
{'rs_ud', 1, 'single', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Right stick up/down')}; ...
{'mode', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Control Mode')}; ...
{'command_1', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Pilot command 1')}; ...
{'command_2', 1, 'uint32', -1, 'real', 'Sample', 'Fixed', [], [], '', sprintf('Pilot command 2')}; ...
    } ...
  } ...
}';

if ~suppressObject
    % Create bus objects in the MATLAB base workspace
    Simulink.Bus.cellToObject(cellInfo)
end

author: Firmament-Autopilot

repo: FMT-Model


text:
function [ir,x0] = ir_localwfs(X,head_orientation,xs,src,sofa,conf)
%IR_LOCALWFS binaural simulation of local WFS
%
%   Usage: [ir,x0] = ir_localwfs(X,head_orientation,xs,src,sofa,conf)
%
%   Input parameters:
%       X                - listener position / m
%       head_orientation - orientation of the listener with [phi theta] /
%                          (rad, rad)
%       xs               - virtual source position / m
%       src              - source type: 'pw' -plane wave
%                                       'ps' - point source
%       sofa             - impulse response data set for the secondary sources
%       conf             - configuration struct (see SFS_config)
%
%   Output parameters:
%       ir               - impulse responses for the desired WFS array
%                          (nx2 matrix)
%       x0               - secondary sources / m
%
%   IR_LOCALWFS(X,head_orientation,xs,src,sofa,conf) calculates a binaural room
%   impulse response for a virtual source at xs for a virtual local WFS array
%   and a listener located at X.
%
%   See also: ssr_brs_wfs, ir_point_source, auralize_ir

%*****************************************************************************
% The MIT License (MIT)                                                      *
%                                                                            *
% Copyright (c) 2010-2019 SFS Toolbox Developers                             *
%                                                                            *
% Permission is hereby granted,  free of charge,  to any person  obtaining a *
% copy of this software and associated documentation files (the "Software"), *
% to deal in the Software without  restriction, including without limitation *
% the rights  to use, copy, modify, merge,  publish, distribute, sublicense, *
% and/or  sell copies of  the Software,  and to permit  persons to whom  the *
% Software is furnished to do so, subject to the following conditions:       *
%                                                                            *
% The above copyright notice and this permission notice shall be included in *
% all copies or substantial portions of the Software.                        *
%                                                                            *
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
% IMPLIED, INCLUDING BUT  NOT LIMITED TO THE  WARRANTIES OF MERCHANTABILITY, *
% FITNESS  FOR A PARTICULAR  PURPOSE AND  NONINFRINGEMENT. IN NO EVENT SHALL *
% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
% LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT, TORT  OR OTHERWISE, ARISING *
% FROM,  OUT OF  OR IN  CONNECTION  WITH THE  SOFTWARE OR  THE USE  OR OTHER *
% DEALINGS IN THE SOFTWARE.                                                  *
%                                                                            *
% The SFS Toolbox  allows to simulate and  investigate sound field synthesis *
% methods like wave field synthesis or higher order ambisonics.              *
%                                                                            *
% https://sfs.readthedocs.io                            sfstoolbox@gmail.com *
%*****************************************************************************

%% ===== Checking of input  parameters ==================================
nargmin = 6;
nargmax = 6;
narginchk(nargmin,nargmax);
if conf.debug
    isargposition(X);
    isargxs(xs);
    isargvector(head_orientation);
    isargchar(src);
    isargstruct(conf);
end

%% ===== Computation =====================================================
% Get secondary sources
x0 = secondary_source_positions(conf);
% Get driving signals
[d, x0] = driving_function_imp_localwfs(x0,xs,src,conf);
% Generate the impulse response for WFS
ir = ir_generic(X,head_orientation,x0,d,sofa,conf);

author: sfstoolbox

repo: sfs-matlab


text:
function [ responses ] = PatchResponseCEN_mirror(patches, patch_experts_class, visibilities, patchExperts, window_size)
% As frontal faces are roughly symmetrical can compute the responses for
% two patches at the same time using only one of the landmark patch experts

    normalisationOptions = patchExperts.normalisationOptionsCol;
    patchSize = normalisationOptions.patchSize;

    responses = cell(size(patches, 1), 1);
    empty = zeros(window_size(1)-patchSize(1)+1, window_size(2)-patchSize(2)+1);

    % These landmark responses can be computed together
    mirror_inds = [1,17;2,16;3,15;4,14;5,13;6,12;7,11;8,10;18,27;19,26;20,25;21,24;22,23;...
                  32,36;33,35;37,46;38,45;39,44;40,43;41,48;42,47;49,55;50,54;51,53;60,56;59,57;...
                  61,65;62,64;68,66];

    for i = 1:numel(patches(:,1))
        if visibilities(i)
            % Do it only if not mirrored
            if(isempty(find(mirror_inds(:,2)==i, 1)))
                responses{i} = empty;

                col_norm = normalisationOptions.useNormalisedCrossCorr == 1;

                smallRegionVec = patches(i,:);
                smallRegion = reshape(smallRegionVec, window_size(1), window_size(2));

                patch = im2col_mine(smallRegion, patchSize)';

                % Add the mirrored version as well (it will be applied the
                % same way)
                mirr_id = mirror_inds(find(mirror_inds(:,1)==i,1),2);
                if(~isempty(mirr_id))
                    responses{mirr_id} = empty;
                    smallRegionVec_mirr = patches(mirr_id,:);
                    smallRegion_mirr = reshape(smallRegionVec_mirr, window_size(1), window_size(2));
                    patch_mirr = im2col_mine(fliplr(smallRegion_mirr), patchSize)';
                    patch = cat(1, patch, patch_mirr);
                end

                % Normalize
                if(col_norm)
                    mean_curr = mean(patch, 2);
                    patch_normed = patch - repmat(mean_curr, 1, patchSize(1)* patchSize(2));

                    % Normalising the patches using the L2 norm
                    scaling = sqrt(sum(patch_normed.^2,2));
                    scaling(scaling == 0) = 1;

                    patch_normed = patch_normed ./ repmat(scaling, 1, 11 * 11);

                    patch = patch_normed;
                end
                patch = patch';
                % Add bias
                patch_normed = cat(1, ones(1, size(patch,2)), patch);
                weights = patch_experts_class{i};
                % Where DNN will happen
                for w =1:numel(weights)/2

                    % mult and bias
                    patch_normed = weights{(w-1)*2+1}' * patch_normed + repmat(weights{(w-1)*2+2}', 1, size(patch_normed,2));

                    if w < 3
    %                    patch_normed(patch_normed < 0) = 0;
                       patch_normed = max(0, patch_normed);
                    else
                       patch_normed = 1./(1+exp(-patch_normed));
                    end

                end
                % If no mirroring took place
                if(isempty(mirr_id))
                    responses{i}(:) = reshape(patch_normed', window_size(1)-patchSize(1)+1, window_size(2)-patchSize(2)+1);
                else
                    patch_normed_1 = patch_normed(1:end/2);
                    patch_normed_2 = patch_normed(end/2+1:end);
                    responses{i}(:) = reshape(patch_normed_1', window_size(1)-patchSize(1)+1, window_size(2)-patchSize(2)+1);
                    responses{mirr_id}(:) = fliplr(reshape(patch_normed_2', window_size(1)-patchSize(1)+1, window_size(2)-patchSize(2)+1));
                end
            end
        end
    end

end

author: TadasBaltrusaitis

repo: OpenFace


text:
function y = upfilt(x, f, dim, extmod, shift)
% UPFILT   Upsample (by 2) and filter along a dimension
%
%       y = upfilt(x, f, dim, extmod, shift)
%
% Input:
%   x:      input signal
%   f:      1-D filter
%   dim:    the processing dimension
%   extmod: extension mode (e.g. 'per' or 'sym')
%   shift:  specifies the window over which filtering occurs
%
% Output:
%   y:      upsampled and filtered signal
%
% Note:
%   The origin of the filter f is assumed to be floor(size(f)/2) + 1.
%   Amount of shift should be no more than floor((size(f)-1)/2).

% Skip singleton dimension
if size(x, dim) == 1
    y = x;
    return
end

nd = ndims(x);
% Consider column vectors as 1-D signals
if nd == 2 & size(x, 2) == 1
    nd = 1;
end

% Cell array of indexes for each dimension
I = cell(1, ndims(x));
for d = 1:ndims(x)
    I{d} = 1:size(x,d);
end

% Upsample (by 2)
sx = size(x);
sx(dim) = 2*sx(dim);
y = zeros(sx);
I{dim} = 1:2:sx(dim);
y(I{:}) = x;

% Border extend
n = size(y, dim);
hlf = (length(f) - 1) / 2;
% Amount of extension at two ends
e1 = floor(hlf) + shift;
e2 = ceil(hlf) - shift;

switch extmod
    case 'per'
        I{dim} = [ly-e1+1:n , 1:n , 1:e2];

    case 'sym'
        I{dim} = [e1+1:-1:2 , 1:n , n-1:-1:e2];

    otherwise
        error('Invalid input for EXTMOD')

end
y = y(I{:});

% Filter and return only the 'valid' part
y = filter(f, 1, y, [], dim);

I{dim} = (1:n) + length(f) - 1;
y = y(I{:});

author: Sable

repo: mcbench-benchmarks


text:
function varargout = test(varargin)
% VL_TEST  Run test suite
%  RESULTS = VL_TEST() runs all VLFeat test suites. The tests
%  verify that VLFeat is working correctly.
%
%  RESULTS is a structure listing the result of each test.
%  It has fileds:
%
%  TESTNAME:   name of the test
%  SUCCEDED:   a boolean flag indicating whether the test succeded
%  EXCEPTION:  the exception generated if the test failed
%
%  VL_TEST(SUITE) runs only the specified SUITE.
%
%  VL_TEST(SUITE, TEST) runs the specified SUITE/TEST without catching
%  the potential exception. Useful to DBSTOP to debug.
[varargout{1:nargout}] = vl_test(varargin{:});

author: yihui-he

repo: panorama

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


text:
function option_num = p11_option_num ( )

%*****************************************************************************80
%
%% P11_OPTION_NUM returns the number of options for problem 11.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 September 2008
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer OPTION_NUM, the number of options.
%
  option_num = 2;

  return
end


text:
classdef DEAGNG < ALGORITHM
% <multi/many> <real/integer/label/binary/permutation>
% Decomposition based evolutionary algorithm guided by growing neural gas
% aph ---   0.1 --- Parameter alpha
% eps --- 0.314 --- Parameter epsilon

%------------------------------- Reference --------------------------------
% Y. Liu, H. Ishibuchi, N. Masuyama, and Y. Nojima, Adapting reference
% vectors and scalarizing functions by growing neural gas to handle
% irregular Pareto fronts. IEEE Transactions on Evolutionary Computation,
% 2020, 24(3): 439-453.
%--------------------------------------------------------------------------
% Copyright Yiping Liu
% Please contact {yiping0liu@gmail.com} if you have any problem.
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            [aph,eps] = Algorithm.ParameterSet(0.1,0.314);

            %% DEA Initialization
            [Ru,Problem.N] = UniformPoint(Problem.N,Problem.M);	% Uniform reference vectors
            Population     = Problem.Initialization();          % Random population
            Zmin           = min(Population.objs,[],1);         % Ideal Point
            AS             = [];                                % Input Signal Archive
            Ruq            = Ru;                                % Refernce vectors in Ru for selection
            [FrontNo,~]    = NDSort(Population.objs,Problem.N); % Fitness for the first mating selection
            crd            = zeros(1,Problem.N);                % Fitness for the first mating selection
            MaxGen         = ceil(Problem.maxFE/Problem.N);    	% Maximum Generation

            %% GNG Initialization
            ArchiveSize = Problem.M*Problem.N;	% Size of Input Signal Archive
            NoG = aph*MaxGen;                   % Number of generations of Not Training GNG
            GNGnet.maxIter = 1;                 % Number of iterations to train GNG per Generation
            GNGnet.maxAge = Problem.N;          % Maximum cluster age
            GNGnet.maxNode = Problem.N;         % Max number of nodes
            GNGnet.lambda = 0.2*Problem.N;      % Cycle for topology reconstruction
            GNGnet.hp = [];                     % Hit point of node
            GNGnet.maxHP = 2*ArchiveSize;       % Max HP of node
            GNGnet.Node = [];                   % Node
            GNGnet.NodeS = [];                  % Expanded node
            GNGnet.NodeP = [];                  % Node mapped to hyperplane
            GNGnet.Err = [];                    % Error
            GNGnet.edge = zeros(2,2);           % Edge between nodes
            GNGnet.age = zeros(2,2);            % Age of edge
            GNGnet.epsilon_a = 0.2;             % Learning coefficient
            GNGnet.epsilon_nb = 0.01;           % Learning coefficient of neighbor
            GNGnet.alpha = 0.5;                 % Nodes r1max and r2max error reduction constant
            GNGnet.delta = 0.9;                 % Error reduction coefficient

            %% Optimization
            while Algorithm.NotTerminated(Population)
                MatingPool = TournamentSelection(2,Problem.N,FrontNo,crd);
                Offspring  = OperatorGA(Problem,Population(MatingPool));
                Zmin       = min([Zmin;Offspring.objs],[],1);

                %% GNG-based adaptation
                if ceil(Problem.FE/Problem.N) <= MaxGen - NoG
                    % Input Signal Archive Update
                    AS = ArchiveUpdate([AS;Offspring.objs],ArchiveSize,Ruq,GNGnet.NodeS,Zmin);
                    nAS = length(AS);
                    % GNG Update (and Algorithm 3)
                    GNGnet.maxNode = min(Problem.N,floor(nAS/2)); % paramter reset
                    GNGnet.maxHP = 2*nAS; % paramter reset
                    GNGnet = GNGUpdate(AS,GNGnet);
                    % Reference Vector Adaptation (Algorithm 4)
                    if size(GNGnet.NodeS,1)>2
                        [Ruq,GNGnet] = ReferenceCombination(Ru,GNGnet);
                    end
                    % Scalarizing Function Adaptation
                    theta = TunePBI(GNGnet,eps); % Tune theta in PBI function
                end

               %% Environmental Selection
               [Population,FrontNo,crd] = ESelection([Population,Offspring],Problem.N,Ruq,GNGnet.NodeS,theta,Zmin);
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function tests = test_imDistanceMap(varargin)
% Test suite for function imDistanceMap.
%
%   output = test_imDistanceMap(input)
%
%   Example
%   test_imDistanceMap
%
%   See also
%

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2018-02-22,    using Matlab 2017b
% Copyright 2010 INRA - Cepia Software Platform.

tests = functiontests(localfunctions);

function test_TouchingParticles(testCase)
% Aim is to compute distance map within each label, even if some of them
% touch each other.
% Uses an image with a completely landlocked label region.

img = [...
    0 0 0 0 0 0 0 0 0 0 0; ...
    0 1 1 1 2 2 2 3 3 3 0; ...
    0 1 1 1 2 2 2 3 3 3 0; ...
    0 1 1 1 2 2 2 3 3 3 0; ...
    0 1 1 1 4 4 4 3 3 3 0; ...
    0 1 1 1 4 4 4 3 3 3 0; ...
    0 1 1 1 4 4 4 3 3 3 0; ...
    0 1 1 1 5 5 5 3 3 3 0; ...
    0 1 1 1 5 5 5 3 3 3 0; ...
    0 1 1 1 5 5 5 3 3 3 0; ...
    0 0 0 0 0 0 0 0 0 0 0; ...
];

exp = [...
    0 0 0 0 0 0 0 0 0 0 0; ...
    0 1 1 1 1 1 1 1 1 1 0; ...
    0 1 2 1 1 2 1 1 2 1 0; ...
    0 1 2 1 1 1 1 1 2 1 0; ...
    0 1 2 1 1 1 1 1 2 1 0; ...
    0 1 2 1 1 2 1 1 2 1 0; ...
    0 1 2 1 1 1 1 1 2 1 0; ...
    0 1 2 1 1 1 1 1 2 1 0; ...
    0 1 2 1 1 2 1 1 2 1 0; ...
    0 1 1 1 1 1 1 1 1 1 0; ...
    0 0 0 0 0 0 0 0 0 0 0; ...
];

dist = imDistanceMap(img, [3 4]);

assertEqual(testCase, dist, exp);

author: mattools

repo: matImage

save_path: github-repos/MATLAB/mattools-matImage


text:
function export_generic(SO3F,filename,varargin)
% export an SO3F to an ASCII file
%
% Syntax
%   export(SO3F,'file.txt',S3G)
%   export(SO3F,'file.txt',regular,'resolution',2.5*degree)
%   export(SO3F,'file.txt',regular,'resolution',2.5*degree)
%
% Input
%  SO3F     - @SO3Fun to be exported
%  filename - name of the ascii file
%
% Options
%  weights   - export weights of the ODF components
%  ZYZ, ABG  - Matthies (alpha, beta, gamma) convention (default)
%  ZXZ,BUNGE - Bunge (phi1,Phi,phi2) convention
%
% See also
% ODFImport ODFExport

% open the file
if nargin == 1, filename = uigetfile;end
fid = fopen(filename,'w');

% write intro
fprintf(fid,'%% MTEX ODF\n');

% symmetries
CS = SO3F.CS; SS = SO3F.SS;
fprintf(fid,'%% crystal symmetry: %s\n',char(CS));
fprintf(fid,'%% specimen symmetry: %s\n',char(SS));

% get SO3Grid
if any(cellfun(@(x) isa(x,'SO3Grid'),varargin))
  S3G = getClass(varargin,'SO3Grid');
  S3G = orientation(S3G);
  d = Euler(S3G,varargin{:});
else
  [S3G,~,~,d] = regularSO3Grid(CS,SS,varargin{:});
end

% evaluate ODF
v = eval(SO3F,S3G,varargin{:});

% build up matrix to be exported
d = mod(d,2*pi);
if ~check_option(varargin,'radians'), d = d./degree;end

% convention
if check_option(varargin,{'Bunge','ZXZ'})
  convention = 'ZXZ';
elseif check_option(varargin,{'ABG','ZYZ'})
  convention = 'ZYZ';
else
  convention = 'ZXZ';
end

% save matrix
if strcmp(convention,'ZXZ')
  fprintf(fid,'%% phi1    Phi     phi2    value\n');
else
  fprintf(fid,'%% alpha   beta    gamma   value\n');
end

fprintf(fid,'%3.5f %3.5f %3.5f %3.5f\n',[d,v(:)].');

fclose(fid);

author: mtex-toolbox

repo: mtex

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


text:
% SP_L2_ERROR: Evaluate the error in L^2 norm.
%
%   errl2 = sp_l2_error (space, msh, u, uex)
%
% INPUT:
%
%   space: object defining the space of discrete functions (see sp_vector)
%   msh:   object defining the domain partition and the quadrature rule (see msh_cartesian)
%   u:     vector of dof weights
%   uex:   function handle to evaluate the exact solution
%
% OUTPUT:
%
%     errl2:  error in L^2 norm
%
% Copyright (C) 2010 Carlo de Falco
% Copyright (C) 2011, 2015 Rafael Vazquez
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Octave; see the file COPYING.  If not, see
% <http://www.gnu.org/licenses/>.

function errl2 = sp_l2_error (space, msh, u, uex)

  if (numel(u) ~= space.ndof)
    error ('Wrong size of the vector of degrees of freedom')
  end

  errl2 = 0;

  for iel = 1:msh.nel_dir(1)
    msh_col = msh_evaluate_col (msh, iel);
    sp_col  = sp_evaluate_col (space, msh_col, 'value', true, 'gradient', false);

    errl2 = errl2 + (sp_l2_error (sp_col, msh_col, u, uex)).^2;
  end

  errl2 = sqrt (errl2);

end

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes


text:
function display(pot)

disp('conditional Gaussian potential object');
disp(struct(pot));

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function value = p12_autonomous ( )

%*****************************************************************************80
%
%% P12_AUTONOMOUS reports whether problem P12 is autonomous.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 February 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer VALUE, is 1 if the equation is autonomous.
%
  value = 1;

  return
end


text:
function maskM = fastPolyFill(pointsM,optS)
%function maskM = fastPolyFill(pointsM,optS)
%fastPolyFill:  fills in images given polygons defining edges.
%Intention is to only fill a voxel if it's center is in the polygon.
%Faster than previous version by a significant factor (about x10).
%JOD; 17 June 05.
%Fixed bug, 5 July 05.
%
% 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/>.

imageSizeV = optS.ROIImageSize;

xOffset = optS.xCTOffset;
yOffset = optS.yCTOffset;

numRows = imageSizeV(1);
numCols = imageSizeV(2);

xInV = pointsM(:,1);
yInV = pointsM(:,2);

maskM = zeros(numRows,numCols);
%could also be a double.

%preallocate a table of voxel indices
%'next to' refers to voxel centers just to the right of where polygon
%edges cross a line connecting voxel centers.
nextToPtsM = sparse(numRows * 4, numCols * 4); %hard to imagine bigger (sparse is faster than full)
numNextToPtsV = zeros(numRows,1);

%convert to "row and col space", that is, a continuous space where
%s is a coord that runs from 1 to numCols (along x axis)
%t is a coord that runs from 1 to numRows (along -y axis)
sInV = (xInV - xOffset)/optS.ROIxVoxelWidth + (numCols + 1)/2;
tInV = (yInV - yOffset)/optS.ROIyVoxelWidth + (numRows + 1)/2;

%For each polygonal element, compute and add one to 'row starters,' centers of
%voxels (assumed at image coords) whose rows cross the polygonal elements
%and are the first element to the right of that polygonal element's row crossing.
%
%Use the parameterization col = n * deltaRow + c + rowURPt    (URPt = upper
%right point).
%
%Algorithm:
%1.  Determine n
%2.  Determine c
%3.  Determine vector of row crossings
%4.  Determine vector of column crossings
%5.  Add one to row starters.

%Loop over polygonal elements
%For polygonal elements:

shift_sV = [sInV(end); sInV(1:end-1)];
shift_tV = [tInV(end); tInV(1:end-1)];

sM = [sInV(:), shift_sV];
tM = [tInV(:), shift_tV];

%Loop over polygonal edges, put ones where voxel centers are inside
%polygon.
for i = 1 : length(sInV)

    if tM(i,1) ~= tM(i,2)   %skip horizontal lines

        tMax = max([tM(i,1),tM(i,2)]);
        tMin = min([tM(i,1),tM(i,2)]);

        %determine n (line parameterization: s = n * t + c )
        n = (sM(i,1) - sM(i,2))/(tM(i,1) - tM(i,2));
        %determine c, could vectorize these two
        c = sM(i,1) - n * tM(i,1);

        %get delta_tV
        tPtsV = ceil(tMin) : floor(tMax);
        delta_tV = tPtsV - tMax;
        sPtsV = n * delta_tV + c + n * tMax; %these are s values at edge 'crossings'

        %derive s values 'next to the right' of the crossings
        sVoxelsV = ceil(sPtsV);

        %catalogue
        for j = 1: length(sVoxelsV)

         num = numNextToPtsV(tPtsV(j));
         numNextToPtsV(tPtsV(j)) = num + 1;
         nextToPtsM(tPtsV(j),num+1) = sVoxelsV(j);

        end

    end

end

%This should be faster than the oft-used cumsum trick:
for i = 1 : numRows
   num = numNextToPtsV(i);
   if num ~=0
       %get 'em
       nextToPtsV = nextToPtsM(i,1:num);
       %sort 'em
       sortPtsV = sort(full(nextToPtsV));
       %fill image
       for j = 1 : length(sortPtsV)/2
         indV = sortPtsV(2*j-1) : sortPtsV(2*j) - 1;
         maskM(i * ones(1,length(indV)),indV) = 1;
       end
   end
end

%lastly, correct an oversight in writing the code: rows need to be flipped:
maskM = flipud(maskM);  %fast operation.

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function h = plotElipse(center,axesLength,hParent)

% This function plots 2D-ellipses in given axes

try
    haf = hParent;
    isax = isequal(get(haf,'type'),'axes');
    if ~isax
        hf = figure('color',ones(1,3));
        haf = axes('parent',hf,'nextplot','add');
        box(haf,'on')
    end
catch
    hf = figure('color',ones(1,3));
    haf = axes('parent',hf,'nextplot','add');
    box(haf,'on')
end

h = rectangle(...
    'Position',[center(:)'-0.5*axesLength(:)',axesLength(:)'],...
    'Curvature',[1,1],...
    'facecolor',0.8*ones(1,3));

author: MBB-team

repo: VBA-toolbox


text:
function [strings, perm] = vl_alphanum(strings)
% VL_ALPHANUM  Sort strings using the Alphanum algorithm
%   STRINGS = VL_ALPHANUM(STRINGS) sorts the cell array of strings
%   STRINGS by using the Alphanum algorithm [1]. [STRINGS,PERM] =
%   VL_ALPHANUM(...) returns the corresponding permutation PERM as
%   well.
%
%   Example::
%     Alphanum sorts strings in a way that 'makes sense'. For instance
%
%      strings = {'B1', 'B2', 'B12', 'A12', 'A1', 'A2'} ;
%      sorted = vl_alphanum(strings) ;
%
%     produces the sorted array {'A1', 'A2', 'A12', 'B1', B2',
%     'B12'}. By contrast, SORT() produces the array {'A1', 'A12',
%     'A2', 'B1', B12', 'B2'} (note the position of the elements
%     'A12', 'B12').
%
%   References:
%   [1] Dave Koelle, 'The Alphanum Algorithm',
%   http://www.davekoelle.com/alphanum.html

chunks = regexp(strings, '(\d+|\D+)', 'tokens') ;
for i = 1:length(strings)
  chunks{i} = [chunks{i}{:}] ;
  for j = 1:length(chunks{i})
    if isstrprop(chunks{i}{j},'digit')
      chunks{i}{j} = sprintf('%020.0f',sscanf(chunks{i}{j},'%d')) ;
    end
  end
  chunks{i} = [chunks{i}{:}] ;
end

[dorp,perm] = sort(chunks) ;
strings = strings(perm) ;


text:
function [Jul1,Jul2]=TCB2TDB(Jul1,Jul2)
%%TCB2TDB Convert from  barycentric coordinate time (TCB) to barycentric
%         dynamical time (TDB), both represented as two-part Julian dates.
%
%INPUTS: Jul1, Jul2 Two parts of a Julian date given in TCB. The units of
%                   the date are days. The full date is the sum of both
%                   terms. The date is broken into two parts to provide
%                   more bits of precision. It does not matter how the
%                   date is split.
%
%OUTPUTS: Jul1, Jul2 The time as a Julian date in TDB.
%
%This is a mex wrapper for the function iauTcbtdb in the International
%Astronomical Union's (IAU) Standard's of Fundamental Astronomy library.
%
%The algorithm can be compiled for use in Matlab  using the
%CompileCLibraries function.
%
%The algorithm is run in Matlab using the command format
%[Jul1,Jul2]=TCB2TDB(Jul1,Jul2);
%
%Many temporal coordinate systems standards are compared in [1].
%
%REFERENCES:
%[1] D. F. Crouse, "An Overview of Major Terrestrial, Celestial, and
%    Temporal Coordinate Systems for Target Tracking," Formal Report,
%    Naval Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016,
%    173 pages.
%
%March 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

error('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')

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 p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters.
%               You should set p to a vector of 0's and 1's
%

result = sigmoid(X * theta);
p = round(result);

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

end

repo: MachineLearning


text:
clear all
close all

bnet = mk_asia_bnet();

N = length(bnet.dag);

base_proba = 0.3;
bnet_miss = gener_MCAR_net(bnet, base_proba);

m=500;
[data, comp_data, bnet_miss, taux, bnet_orig, notok] = gener_data_from_bnet_miss(bnet_miss, m, base_proba);

dag0 = zeros(N);
bnet0 = mk_bnet(dag0, bnet.node_sizes);
for node = 1:N
  bnet0.CPD{node} = tabular_CPD(bnet0, node, 'prior_type', 'dirichlet', 'dirichlet_weight', 0);
end

max_loop = 6;
[bnet0, cpdag, BIC_score, nloop] = learn_struct_ges_EM(bnet0, data, max_loop);

[XX, YY] = draw_graph(bnet.dag);
figure;
draw_graph(bnet0.dag, {'1','2','3','4','5','6','7','8'}, zeros(1,N), XX, YY);


text:
function out = check_option(option_list,option,varargin)
% check for option in option list
%
% Syntax
%   out = check_option(option_list,option_name,type)
%   out = check_option(option_list,option_name,[],option)
%
% Input
%  option_list - Cell Array
%  option_name - String
%  option      - String
%  type        - class
%
% Output
%  out         - true / false
%
% See also
% get_option set_option find_option

if isempty(option_list)
  out = false;
elseif nargin == 2
  if ischar(option)
    out = any(strcmpi(option_list,option));
  else
    out = false;
    for k = 1:length(option)
      out = out || any(strcmpi(option_list,option{k}));
    end
  end
elseif nargin == 3
  out = find_option(option_list,option,varargin{:}) > 0;
else
  pos = find_option(option_list,option);
  out = pos > 0 && numel(option_list)>pos && ischar(option_list{pos+1}) && ...
    strcmpi(option_list{pos+1},varargin{2});
end