text:
function val=greatestCommonDivisor(m,n)
%%GREATESTCOMMONDIVISOR Given two integers m and n, determine the integer
%           that is the greatest common divisor. This is like the gcd
%           function that is built into Matlab, but it can be useful to
%           have an explcit function if one wishes to use a different data
%           type with appropriately overloaded operators, such as for
%           extended precision arithmetic.
%
%INPUTS: m, n Two positive real integers.
%
%OUTPUTS: val The greatest common divisor of the integers.
%
%This function implements Algorithm F in Problem 3 of Section 1.1 of [1].
%
%EXAMPLE:
% val=greatestCommonDivisor(24,32)
%One will get val=8.
%
%REFERENCES:
%[1] D. E. Knuth, The Art of Computer Programming. Vol. 1: Fundamental
%    Algorithms, 3rd Edition, Boston: Addison-Wesley, 2011.
%
%October 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

while(1)
    %Step F1
    m=rem(m,n);

    %Step F2
    if(m==0)
        val=n;
        return
    end

    %Step F3
    n=rem(n,m);

    %Step F4
    if(n==0)
        val=m;
        return
    end
end
end

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

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function [u, dataError, nSpikes, energy] = iSparsByPottsADMM(f, gamma, A, p, opts)
%iSparsPottsADMM Minimizes the sparsity problem using an Potts ADMM method
%
%Description:
% Minimizes the sparsity functional
%
%  \gamma \| u \|_0 + \| A u - f \|_p^p
%
% using the inverse Potts functional (see iPottsADMM)

% written by M. Storath
% $Date: 2013-04-05 12:22:32 +0200 (Fr, 05. Apr 2013) $	$Revision: 73 $

% create differentiation matrix
if isa(A, 'linop')
    D = linop( @(x) diff(x), @(x) conv(x, [-1 1], 'full') );
elseif isa(A, 'convop')
    d(numel(f),1) = -1; d(1) = 1;
    D = convop(fft(d));
else
    D = spdiffmatrix(size(A, 2)+1);
end

% create substitution matrix
B = A * D;

% parse parameters
if ~exist('opts', 'var')
    % standard parameters
    opts.muInit = gamma * 1e-6;
    %opts.muInit = 2 * gamma / norm(B' * f, 2)^2 ;
    opts.muStep = 1.05;
    opts.dispStatus = 1;
    opts.tol = 1e-6;
    opts.iMax = 1;
end

% call Potts problem with matrix A * D
v = iPottsADMM(f, gamma, B, p, opts);

% resubstitution
u = real(D * v);

% compute error
res = A * u - f;
dataError = sum(res(:).^p);

% count number of spikes
nSpikes = sum(u(:) ~= 0);

% total energy
energy = gamma * nSpikes + dataError;

end

author: mstorath

repo: Pottslab

save_path: github-repos/MATLAB/mstorath-Pottslab


text:
function rx = vecrotx(angle)
%
% Function Name:
%
%   vecrotx - Transformation matrix for a rotation around the x axis.
%
% Calling Sequence:
%
%   rx = vecrotx(angle);
%
% Parameters:
%
%   angle		: rotation angle defined in radians
%
%   rx		: (4x4) Transformation matrix.
%
%
% Description:
%
%   Return the (4x4) Transformation matrix for a rotation about the x axis
%   by the defined angle.
%
%   The matrix is:
%
%         [ 1         0            0          0]
%         [ 0     cos(angle)  -sin(angle)     0]
%         [ 0     sin(angle)   cos(angle)     0]
%         [ 0         0            0          1]
%
% Examples:
%
%    Rotate the NURBS line (0.0 0.0 0.0) - (3.0 3.0 3.0) by 45 degrees
%    around the x-axis
%
%    line = nrbline([0.0 0.0 0.0],[3.0 3.0 3.0]);
%    trans = vecrotx(%pi/4);
%    rline = nrbtform(line, trans);
%
% See:
%
%    nrbtform

%  Dr D.M. Spink
%  Copyright (c) 2000.

sn = sin(angle);
cn = cos(angle);
rx = [1 0 0 0; 0 cn -sn 0; 0 sn cn 0; 0 0 0 1];

author: Sable

repo: mcbench-benchmarks


text:
% nanmean() - Average, not considering NaN values
%
% Usage: same as mean()

% Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002

%123456789012345678901234567890123456789012345678901234567890123456789012

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

% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: nanmean.m 2885 2011-02-16 09:41:58Z roboos $

function out = nanmean(in, dim)

if nargin < 1
    help nanmean;
    return;
end;
if nargin < 2
    if size(in,1) ~= 1
        dim = 1;
    elseif size(in,2) ~= 1
        dim = 2;
    else
        dim = 3;
    end;
end;
tmpin = in;
tmpin(find(isnan(in(:)))) = 0;
out = sum(tmpin, dim) ./ sum(~isnan(in),dim);

author: PatternRecognition

repo: OpenBMI


text:
function [Mreordered,Mindices,cost] = reorder_matrix(M1,cost,flag)
%REORDER_MATRIX         matrix reordering for visualization
%
%   [Mreordered,Mindices,cost] = reorder_matrix(M1,cost,flag)
%
%   This function rearranges the nodes in matrix M1 such that the matrix
%   elements are squeezed along the main diagonal.  The function uses a
%   version of simulated annealing.
%
%   Inputs:     M1             = connection matrix (weighted or binary,
%                                directed or undirected)
%               cost           = 'line' or 'circ', for shape of lattice
%                                cost (linear or ring lattice)
%
%               Mreordered     = reordered connection matrix
%               Mindices       = reordered indices
%               cost           = distance between M1 and Mreordered
%
%   Note that in general, the outcome will depend on the initial condition
%   (the setting of the random number seed).  Also, there is no good way to
%   determine optimal annealing parameters in advance - these paramters
%   will need to be adjusted "by hand" (particularly H, Texp, and T0).
%   For large and/or dense matrices, it is highly recommended to perform
%   exploratory runs varying the settings of 'H' and 'Texp' and then select
%   the best values.
%
%   Based on extensive testing, it appears that T0 and Hbrk can remain
%   unchanged in most cases.  Texp may be varied from 1-1/H to 1-10/H, for
%   example.  H is the most important parameter - set to larger values as
%   the problem size increases.  It is advisable to run this function
%   multiple times and select the solution(s) with the lowest 'cost'.
%
%   Setting 'Texp' to zero cancels annealing and uses a greedy algorithm
%   instead.
%
%   Yusuke Adachi, University of Tokyo 2010
%   Olaf Sporns, Indiana University 2010

N = size(M1,1);

% generate cost function
if (strcmp(cost,'line'))
    profil = fliplr(normpdf(1:N,0,N/2));
end;
if (strcmp(cost,'circ'))
    profil = fliplr(normpdf(1:N,N/2,N/4));
end;
COST = (toeplitz(profil,profil).*~eye(N));
COST = COST./sum(sum(COST));

% establish maxcost, lowcost, mincost
maxcost = sum(sort(COST(:)).*(sort(M1(:))));
lowcost = sum(sum(M1.*COST))/maxcost;
mincost = lowcost;

% initialize
anew = 1:N;
amin = 1:N;
h = 0; hcnt = 0;

% set annealing parameters
% H determines the maximal number of steps
% Texp determines the steepness of the temperature gradient
% T0 sets the initial temperature (and scales the energy term)
% Hbrk sets a break point for the simulation (if no further improvement)
H = 1e04; Texp = 1-10/H; T0 = 1e-03; Hbrk = H/10;
%Texp = 0;

while h<H
    h = h+1; hcnt = hcnt+1;
    % terminate if no new mincost has been found for some time
    if (hcnt>Hbrk)
        break;
    end;
    % current temperature
    T = T0*Texp^h;
    % choose two positions at random and flip them
    atmp = anew;
    %r = randperm(N);  % slower
    r = ceil(rand(1,2).*N);
    atmp(r(1)) = anew(r(2));
    atmp(r(2)) = anew(r(1));
    costnew = sum(sum(M1(atmp,atmp).*COST))/maxcost;
    % annealing
    if (costnew < lowcost) || (rand < exp(-(costnew-lowcost)/T))
        anew = atmp;
        lowcost = costnew;
        % is this a new absolute best?
        if (lowcost<mincost)
            amin = anew;
            mincost = lowcost;
            if (flag==1)
                disp(['step ',num2str(h),' ... current lowest cost = ',num2str(mincost)]);
            end;
            hcnt = 0;
        end;
    end;
end;
disp(['step ',num2str(h),' ... final lowest cost = ',num2str(mincost)]);

% prepare output
Mreordered = M1(amin,amin);
Mindices = amin;
cost = mincost;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [varargout] = likGaussWarpExact(warp, hyp, y, mu, varargin)

% likGaussWarp - Warped Gaussian likelihood for regression.
% The expression for the likelihood is
%   likGaussWarp( y | t ) = likGauss( g(y) | t ) * g'(y),
% where likGauss is the Gaussian likelihood and g is the warping function.
%
% The hyperparameters are:
%
% hyp = [ theta_1
%         theta_2
%           ..
%         theta_ng
%         log(sn) ]
%
% Here, sn is the standard deviation of the underlying Gaussian and theta_i for
% i=1..ng are the ng hyperparameters of the warping function g.
%
% At the moment, likGaussWarp offers 3 different warping functions:
% id                   yields g(y) = y  =>  likGaussWarp = likGauss
% poly<m> e.g. 'poly1' yields g(y) = y  =>  likGaussWarp = likGauss
%              'poly3' yields g(y) = y + c1*sy*ay^2 + c2*sy*ay^3
%                             where sy = sign(y), ay = abs(y), cj = exp(theta_j)
% tanh<m> e.g. 'tanh0' yields g(y) = y  =>  likGaussWarp = likGauss
%              'tanh2' yields g(y) = y + a1*tanh(b1*(y+c1)) + a2*tanh(b2*(y+c2))
%                 where aj = exp(theta_j), bj = exp(theta_j+m), bj = theta_j+2*m
%
% The code is based on the exposition in the paper Warped Gaussian Processes,
% NIPS, 2003 by Edward Snelson, Carl Rasmussen and Zoubin Ghahramani.
%
% Several modes are provided, for computing likelihoods, derivatives and moments
% respectively, see likFunctions.m for the details. In general, care is taken
% to avoid numerical issues when the arguments are extreme.
%
% Copyright (c) by Hannes Nickisch, 2013-10-24.
%
% See also LIKFUNCTIONS.M.

lik = {@likGauss}; % in principle any likelihood function can be warped but only
% for homoscedastic likelihoods, in particular Gaussian has feasible integrals
if numel(warp)==0, warp = 'id'; end               % set default warping function
if ischar(warp) || isa(warp,'function_handle'); warp = {warp}; end

ng = feval(warp{:});        % number of hyperparameters for the warping function
nhyp = ['(',num2str(ng),'+',feval(lik{:}),')'];      % number of hyperparameters
if nargin<4, varargout = {nhyp}; return, end       % report number of parameters
nhyp = eval(nhyp);
if nhyp>length(hyp), error('not enough hyperparameters'), end

[gy,lgpy] = feval(warp{:},y,hyp(1:ng));                     % evaluate warping function

% [gy,ig(warp,gy,hyp(1:ng))]'
i = 0; if nargin>6, i = varargin{3}; varargin{3} = varargin{3}-ng; end
varargout = cell(nargout,1);              % allocate memory for output arguments
if i==0 || ng<i                               % only evaluate the required parts
  [varargout{:}] = feval(lik{:},hyp(ng+1:end),gy,mu,varargin{:});     % eval lik
end
if nargin<6                              % prediction mode if inf is not present
  if numel(y)==0,  y = zeros(size(mu)); end
  s2zero = 1; if nargin>4, s2 = varargin{1}; end                       % s2==0 ?
  if nargin>4&&numel(s2)>0&&norm(s2)>eps>0, s2zero = 0; end
  if s2zero                                                    % log probability
    lp = likGaussWarpExact(warp, hyp, y, mu, [], 'infLaplace'); s2 = 0*mu;
  else
    lp = likGaussWarpExact(warp, hyp, y, mu, s2, 'infEP');               % prediction
  end
  if nargout>0, varargout{1} = lp; end                       % works for any lik
  % the predictive moments are very hard to compute for lik not being likGauss
  if nargout>1
    ymu = mu;                                                % first g(y) moment
    sn2 = exp(2*hyp(ng+1));                            % Gaussian noise variance
    ys2 = s2 + sn2;                                         % second g(y) moment
%     ymuM = ig(warp,ymu,hyp(1:ng));                                    % median
%     yupp = ig(warp,ymu+2*sqrt(ys2),hyp(1:ng));       % 95% confidence interval
%     ylow = ig(warp,ymu-2*sqrt(ys2),hyp(1:ng));
%     ys2C = (yupp-ylow).^2/16;

%    N = 20; [t,w] = gauher(N); oN = ones(1,N);     % Gaussian-Hermite quadrature
%    Z = sqrt(ys2(:))*t'+ymu(:)*oN;
%    Y = ig(warp,Z,hyp(1:ng));
%    ymu = Y*w; ys2 = (Y-ymu*oN).^2*w;                % first and second y moment

    ymu = feval(warp{:},mu,hyp(1:ng),'inv');
    % muin = feval(warp{:},mu,hyp(1:ng));
    %ylow = feval(warp{:},muin-10*sqrt(ys2),hyp(1:ng),'inv');
    ylow = feval(warp{:},mu-sqrt(ys2),hyp(1:ng),'inv');
    ys2 = (ymu-ylow).^2;

    varargout{2} = reshape(ymu,size(mu));
    if nargout>2
      varargout{3} = ys2;
    end
  end

else
  inf = varargin{2};                                    % obtain input variables
  switch inf
  case {'infLaplace','infEP'}                     % they have the same structure
    if nargin<7                                             % no derivative mode
      if nargout>0, varargout{1} = varargout{1} + lgpy; end
    else                                                       % derivative mode
      if i<=ng                  % derivatives w.r.t. warping function parameters
        n = max([numel(y),numel(mu)]);
        for j=2:nargout, varargout{j} = zeros(n,1); end
        [dgy,dlgpy] = feval(warp{:},y,hyp(1:ng),i);    % warping function derivative
        out = cell(nargout+1,1);                               % allocate memory
        [out{:}] = likGaussWarpExact(warp, hyp, y, mu, varargin{1:2});    % query lik
        % works only for homoscedastic likelihoods where y and mu can be swapped
        if nargout>0, varargout{1} = dlgpy - out{2}.*dgy; end % apply chain rule
        if nargout>1, varargout{2} =       - out{3}.*dgy; end
        if nargout>2, varargout{3} =       - out{4}.*dgy; end
      end
    end

  case 'infVB'           % output does not depend on mu and following parameters
  end
end

author: acerbilab

repo: bads

save_path: github-repos/MATLAB/acerbilab-bads


text:
close all;
clear all;
clc;

% Create the directory for storing results
spx.fs.ensure_dir('bin');

% set number
r = 1;
h = spx.data.motion.Hopkins155;
% pre-load all examples
h.load_all_examples();
examples = h.get_2_3_motions();
example = examples{r};
solver = @ssc_mc_omp;

Y = example.X;
% homogenize
Y = spx.la.affine.homogenize(Y);
Y = spx.norm.normalize_l2(Y);
Y = Y;

if true
    fprintf('\n\n\n Statistics for the pair of motions:\n\n');
    [M, S]  = size(Y);
    sizes = example.counts;
    angle_result = spx.cluster.subspace.nearest_same_subspace_neighbors_by_inner_product(Y, sizes);
    spx.cluster.subspace.print_nearest_neighbor_result(angle_result);

end

mf = spx.graphics.Figures;
if true
    % Ambient space dimension and number of data points
    [trial.M, trial.S] = size(Y);
    % Number of subspaces
    trial.K = example.num_motions;
    % maximum dimension for each subspace
    trial.D = 3;
    trial.cluster_sizes = example.counts;
    % Solve the sparse subspace clustering problem
    tstart = tic;
    try
        clustering_result = solver(Y, trial.D, trial.K);
    catch ME
        % we will move on to next one
        fprintf('Problem in processing this example. %s: %s\n', ME.identifier, ME.message);
        % move on to next example
        error('cannot continue.');
    end
    trial.elapsed_time = toc (tstart);
    trial.singular_values = clustering_result.singular_values;
    % graph connectivity
    trial.connectivity = clustering_result.connectivity;
    % estimated number of clusters
    trial.estimated_num_subspaces = clustering_result.num_clusters;
    % Time to compare the clustering
    cluster_labels = clustering_result.labels;
    true_labels = example.labels;
    comparsion_result = spx.cluster.clustering_error(cluster_labels, true_labels, trial.K);
    trial.clustering_error_perc = comparsion_result.error_perc;
    trial.clustering_acc_perc = 100 - comparsion_result.error_perc;
    % Compute the statistics related to subspace preservation
    spr_stats = spx.cluster.subspace.subspace_preservation_stats(clustering_result.Z, trial.cluster_sizes);
    trial.spr_error = spr_stats.spr_error;
    trial.spr_flag = spr_stats.spr_flag;
    trial.spr_perc = spr_stats.spr_perc;
    fprintf('\nclustering error: %0.2f %% , clustering accuracy: %0.2f %%,\n mean spr error: %0.2f preserving : %0.2f %%,\n connectivity: %0.2f, elapsed time: %0.2f sec', trial.clustering_error_perc, trial.clustering_acc_perc, spr_stats.spr_error, spr_stats.spr_perc, trial.connectivity, trial.elapsed_time);
    fprintf('\n\n');
    Z = abs(clustering_result.Z);
    s = spx.stats.format_descriptive_statistics(Z(:));
    fprintf(s);
    fprintf('\n');
    mf.new_figure('Representations');
    imshow(Z);
end

author: indigits

repo: sparse-plex


text:
function image = APPgetLabeledImage2(image, imsegs, pv, ph)
% image = APPgetLabeledImage2(image, imsegs, pv, ph)
%
% Copyright(C) Derek Hoiem, Carnegie Mellon University, 2006
% Current Version: 2.0  04/22/2006
%image = image / double(max(image(:)));

%grayim = rgb2gray(image);
image = rgb2hsv(image);
image(:, :, 2) = 0.0*image(:, :, 2);
image = hsv2rgb(image);

rad = round(max(size(image))/20);
markW = ceil(rad/10);
right_arrow = struct('x', 0, 'y', 0, 'angle', 0, 'radius', rad, 'head_length', rad/2, 'head_base_angle', 30);
up_arrow = struct('x', 0, 'y', 0, 'angle', 90, 'radius', rad, 'head_length', rad/2, 'head_base_angle', 30);
up_left_arrow = struct('x', 0, 'y', 0, 'angle', 135, 'radius', rad, 'head_length', rad/2, 'head_base_angle', 30);
up_right_arrow = struct('x', 0, 'y', 0, 'angle', 45, 'radius', rad, 'head_length', rad/2, 'head_base_angle', 30);
left_arrow = struct('x', 0, 'y', 0, 'angle', 180, 'radius', rad, 'head_length', rad/2, 'head_base_angle', 30);
down_arrow = struct('x', 0, 'y', 0, 'angle', 270, 'radius', rad, 'head_length', rad/2, 'head_base_angle', 30);
toward_arrow = struct('x', 0, 'y', 0, 'angle', 250, 'radius', rad*2/3, 'head_length', rad/3, 'head_base_angle', 60);

vhue = [112 0 177]/255;

if ndims(pv)==2
    [vconf, vlab] = max(pv, [], 2);
    [hconf, hlab] = max(ph, [], 2);

    vlabim = vlab(imsegs.segimage);
    hlabim = hlab(imsegs.segimage);
    hconfim = hconf(imsegs.segimage);
    %vconf = max((vconf - 0.5)*2, 0);
    %vconf = max(vconf, 1);

    hueim = vhue(vlabim);
    satim = vconf(imsegs.segimage);
    valim = ones(size(hueim));
else
    [satim, vlabim] = max(pv, [], 3);
    [hconfim, hlabim] = max(ph, [], 3);
    hueim = vhue(vlabim);
    valim = ones(size(hueim));
end

% set color
image = image*0.5 + 0.5*hsv2rgb(hueim, satim, valim);

% draw boundaries of main classes
% [gx, gy] = gradient(vlabim);
% g = gx.^2 + gy.^2;
% g = conv2(g, ones(2), 'same');
% edgepix = find(g>0);
% npix = numel(hueim);
% for b = 1:3
%     image((b-1)*npix+edgepix) = 0;
% end

if 1 % set do draw subclass marks

%hconfim = max((hconf(imsegs.segimage)-0.5)*2, 0);

height = size(image, 1);  width = size(image, 2);

for x = rad:round(rad*1.51):(width-rad)
    for y = rad:round(rad*1.51):(height-rad)

        %val = 1-hconfim(y, x);
        val = [0 0 0];

        arrows = [];
        if vlabim(y, x)==2 % vertical
            if hlabim(y, x)==1 % left
                arrows = left_arrow;
            elseif hlabim(y, x)==2 % center
                arrows = up_arrow;
            elseif hlabim(y, x)==3 % right
                arrows = right_arrow;
            elseif hlabim(y, x)==4 % porous
                image = draw_circle_image(image, x, y, rad/2, val, markW);
            elseif hlabim(y, x)==5 % solid
                image = draw_x_image(image, x, y, rad, val, markW);
            end

        end

        % draw arrows
        for a = 1:length(arrows)
            arrows(a).x = x;
            arrows(a).y = y;
        end

        image = draw_arrow_image(image, arrows, val, markW);

    end

end
end

author: Cloud-CV

repo: object-proposals


text:
function ss=lpczz2ss(zz)
%LPCZZ2SS Convert z-place poles to s-plane poles SS=(ZZ)
%the s-plane is in units of Normalized Hz and so the imaginary part
% of each ss() value is in the range +-0.5
%
% If you multiply ss by the sample frequency, a formant with
% frequency f and bandwidth b will give an s-plane pole-pair
% of approximately -b/2 +- j f

%      Copyright (C) Mike Brookes 1997
%      Version: $Id: lpczz2ss.m,v 1.4 2007/05/04 07:01:39 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ss=log(max(zz,1e-8))*0.5/pi;

author: decouples


text:
function value = p32_r8vec ( action, name, dim_num, value )

%*****************************************************************************80
%
%% P32_R8VEC sets or gets R8VEC parameters for problem 32.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 June 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string ACTION, the action.
%    'D' sets the internal value of the object to a default value.
%    If NAME = '*', then all variables are defaulted.
%    'G' means the current value of the object should be returned.
%    'R' means randomize the object and return it.
%    'S' means the input values of the object and its dimension should
%    be stored.
%
%    Input, string NAME, the name of the parameter.
%    'C' is the first vector.
%    'Z' is the base vector.
%
%    Input, integer DIM_NUM, the dimension of the object.
%
%    Input/output, real VALUE(DIM_NUM), the value of the object.
%
  persistent c
  persistent dim_num_save;
  persistent z

  if ( size ( dim_num_save ) == 0 )
    dim_num_save = 0;
  end

  if ( dim_num_save ~= dim_num )
    dim_num_save = 0;
    c = [];
    z = [];
  end

  if ( dim_num_save == 0 )
    dim_num_save = dim_num;
  end

  if ( action == 'D' | action == 'd' )

    if ( name == 'C' | name == 'c' | name == '*' )
      c(1:dim_num) = 0.5^( 1.0 / dim_num );
    end

    if ( name == 'Z' | name == 'z' | name == '*' )
      z(1:dim_num) = 0.5^( 1.0 / dim_num );
    end

  elseif ( action == 'G' | action == 'g' )

    if ( name == 'C' | name == 'c' )
      value(1:dim_num) = c(1:dim_num);
    elseif ( name == 'Z' | name == 'z' )
      value(1:dim_num) = z(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P32_R8VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P32_R8VEC - Fatal error!' );
    end

  elseif ( action == 'R' | action == 'r' )

    if ( name == 'C' | name == 'c' )
      c = rand ( 1, dim_num );
      value(1:dim_num) = c(1:dim_num);
    elseif ( name == 'Z' | name == 'z' )
      z = rand ( 1, dim_num );
      value(1:dim_num) = z(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P32_R8VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P32_R8VEC - Fatal error!' );
    end

  elseif ( action == 'S' | action == 's' )

    if ( name == 'C' | name == 'c' )
      c(1:dim_num) = value(1:dim_num);
    elseif ( name == 'Z' | name == 'z' )
      z(1:dim_num) = value(1:dim_num);
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'P32_R8VEC - Fatal error!\n' );
      fprintf ( 1, '  Unrecognized name = "%s".\n', name );
      error ( 'P32_R8VEC - Fatal error!' );
    end

  else

    fprintf ( 1, '\n' );
    fprintf ( 1, 'P32_R8VEC - Fatal error!\n' );
    fprintf ( 1, '  Unrecognized action = "%s".\n', action );
    error ( 'P32_R8VEC - Fatal error!' );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [ux,uy,uz]=LK3D( image1, image2, r )
%This function estimates deformations between two subsequent 3-D images
%using Lucas-Kanade optical flow equation.
%
%   Description :
%
%   -image1, image2 :   two subsequent images or frames
%   -r : radius of the neighbourhood, default value is 2.
%
%   Reference :
%   Lucas, B. D., Kanade, T., 1981. An iterative image registration
%   technique with an application to stereo vision. In: Proceedings of the
%   7th international joint conference on Artificial intelligence - Volume 2.
%   Morgan Kaufmann Publishers Inc., San Francisco, CA, USA, pp. 674-679.
%
%   Author : Mohammad Mustafa
%   By courtesy of The University of Nottingham and Mirada Medical Limited,
%   Oxford, UK
%
%   Published under a Creative Commons Attribution-Non-Commercial-Share Alike
%   3.0 Unported Licence http://creativecommons.org/licenses/by-nc-sa/3.0/
%
%   June 2012

%  Default parameter
if nargin==2
    r=2;
end

[height,width,depth]=size(image1);
image1=im2double(image1);
image2=im2double(image2);

% Initializing flow vectors
ux=zeros(size(image1)); uy=ux; uz=ux;

% Computing image derivatives
[Ix,Iy,Iz,It]=imageDerivatives3D(image1,image2);

for i=(r+1):(height-r)
    for j=(r+1):(width-r)
        for k=(r+1):(depth-r)

        blockofIx=Ix(i-r:i+r,j-r:j+r,k-r:k+r);
        blockofIy=Iy(i-r:i+r,j-r:j+r,k-r:k+r);
        blockofIz=Iz(i-r:i+r,j-r:j+r,k-r:k+r);
        blockofIt=It(i-r:i+r,j-r:j+r,k-r:k+r);

        A=zeros(3,3);
        B=zeros(3,1);

        A(1,1)=sum(sum(sum(blockofIx.^2)));
        A(1,2)=sum(sum(sum(blockofIx.*blockofIy)));
        A(1,3)=sum(sum(sum(blockofIx.*blockofIz)));

        A(2,1)=sum(sum(sum(blockofIy.*blockofIx)));
        A(2,2)=sum(sum(sum(blockofIy.^2)));
        A(2,3)=sum(sum(sum(blockofIy.*blockofIz)));

        A(3,1)=sum(sum(sum(blockofIz.*blockofIx)));
        A(3,2)=sum(sum(sum(blockofIz.*blockofIy)));
        A(3,3)=sum(sum(sum(blockofIz.^2)));

        B(1,1)=sum(sum(sum(blockofIx.*blockofIt)));
        B(2,1)=sum(sum(sum(blockofIy.*blockofIt)));
        B(3,1)=sum(sum(sum(blockofIz.*blockofIt)));

        invofA=pinv(A);

        V=invofA*(-B);
        ux(i,j,k)=V(1,1);
        uy(i,j,k)=V(2,1);
        uz(i,j,k)=V(3,1);
        end
    end
end

end


text:
function full = fullpath(pth)
%
% full = fullpath(pth);
%
% Given a string specifying a path which may be an absolute path,
% or a path relative to the current directory, always return
% an absolute, full path string. Platform-independent.
%
% Ex: if the current directory is '/usr/me' and the pth string is
% 'Inplane/Original', will return '/usr/me/Inplane/Original'. But if the
% pth string is '/usr/someone_else', will return '/usr/someone_else'.
%
% ras, 11/2005.
% ras, 10/30/2006: deals w/ empty paths now.
if isempty(pth), full = pwd; return; end

if isunix
    % Check for the root file separator '/' for absolute paths
    if isequal(pth(1), filesep)
        full = pth;
    else
        full = fullfile(pwd, pth);
    end
elseif ispc
    % check if the drive colon is specified as 2nd char: e.g., 'C:\'
    if isequal(pth(2), ':')
        full = pth;
    else
        full = fullfile(pwd, pth);
    end
else
    % not unix-y (incl. mac) or pc -- ?
    msg = 'This computer not identified as PC, Mac OS X or Unix. ';
    msg = [msg 'Sorry, fullpath can''t work for this platform. '];
    msg = [msg 'Returning un-modified input path.'];
    warning(msg);
    full = pth;
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [fAlpha, fDmax] = calc_KStestGR(mCatalog, fBinning, fBValue, fMc)
% [mAlphaVal] = calc_KStestGR(mCatalog, fBinning, fBValue)
% ------------------------------------------------------------------------
% Calculate Koglomorov-Smirnov-test with constant b-value
% Reference for equations to calculate the statistics nD:
% Y.Y. Kagan, Accuracy of modern global earthquake catalogs, Physics of the Earth and Planetary Interiors
% 4179, 1-37, 2002
%
% Incoming variables:
% mCatalog : Earthquake catalog
% fBinning : Binning interval
% fBValue  : Fix b-value
%
% Outgoing variables:
% mAlphaVal(:,1) : Significance level Alpha according to ascending magnitudes
% mAlphaVal(:,2) : Ascending magnitudes
%
% Author: J. Woessner
% last update: 25.03.03

% Initialize
mAlphaVal = [];
vD = [];

% Select data above Mc
vSel = (mCatalog(:,6) >= fMc);
mCatalog = mCatalog(vSel,:);

% Set fix values
fMaxMag = ceil(10 * max(mCatalog(:,6))) / 10;
fMinMag = (round(min(mCatalog(:,6)*10)))/10;
vMag = fMinMag:0.1:fMaxMag;

% Using Bath's law : see Reference Console
% Beta-value
fBeta = log(10)*fBValue;

% Probability density function
% vPdf = fBeta*exp(-fBeta*(vMag-fMc))
%
% % Cumulative density function
% vCdf = cumsum(vPdf);
% %vCdf = vCdf/max(vCdf);
% vCdf = [vCdf; vMag];
% vCdf = vCdf';

% CDF theoretically
vCdf = (1-exp(-fBeta*(vMag-fMc)))./(1-exp(-fBeta*(fMaxMag-2-fMc)));
vCdf = [vCdf; vMag];
vCdf = vCdf';

% Use Kagan 2002 approach
% Sort catalog with ascending magnitude
[mCatSorted,vIndex] = sort(mCatalog(:,6));
mCat = mCatalog(vIndex(:,1),:);

% Calulate statistic fD = max_(1=<k=<N)((k/N-F(M_k)
nEvents = length(mCat(:,1));
vkEvent = 1:length(mCat(:,1));
vkEvent = vkEvent/nEvents;
vkEvent = vkEvent';
for nE = 1:nEvents
    % Find probability of theoretical distribution for event k with magnitude Mk
    try
        vSel = (vCdf(:,2) == (round(mCat(nE,6)*10))/10);
        fD = max(nE/nEvents-vCdf(vSel,1));
        vD = [vD; fD];
    catch
        fD = nan;
        vD = [vD; fD];
    end
end
fDmax = max(vD);
fAlpha = exp(-2*nEvents*(fDmax+1/(6*nEvents))^2);
% vAlpha = exp(-2*nEvents.*(vD+1/(6*nEvents)).^2)
% disp('v')

author: CelsoReyes


text:
%PSNR  Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric
%
%     psnr = cv.PSNR(src1, src2)
%
% ## Input
% * __src1__ first input array (gray or color image), 8-bit integer type.
% * __src2__ second input array of the same size and type as `src1`.
%
% ## Output
% * __psnr__ Computed signal-to-noise ratio
%
% This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality
% metric in decibels (dB), between two input arrays `src1` and `src2`. Arrays
% must have `uint8` depth.
%
% The PSNR is calculated as follows:
%
%     PSNR = 10 * log10(R^2 / MSE)
%
% where `R` is the maximum integer value of `uint8` depth (255) and `MSE` is
% the mean squared error between the two arrays.
%
% See [PSNR](https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio) for
% more details.
%
% See also: psnr, immse, ssim
%

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
% Like lvmVisualiseGeneral but for audio
function lvmRealtimeAudio(model, YLbls, ...
			visualiseFunction, visualiseModify, showVariance, varargin)

% LVMVISUALISEGENERAL Visualise the manifold.
% This is a copy of lvmVisualise where the classVisualise function depends on the
% model type. Additionally, there is a flag showVariance which, when set to
% false, does not plot the variance of the inputs in the scatter plot,
% something which saves a lot of computational time for high-dimensional
% data.
%
% SEEALSO : lvmVisualise, lvmClassVisualise, lvmScatterPlot,
% lvmScatterPlotNoVar
%

% MLTOOLS

global visualiseInfo

visualiseInfo.showVariance = showVariance;

lvmClassVisualiseFunc = [model.type 'ClassVisualise'];
if ~exist(lvmClassVisualiseFunc)
    lvmClassVisualiseFunc = 'lvmClassVisualise';
end

if isfield(model, 'vis') && isfield(model.vis, 'figHandle')
    figure(model.vis.figHandle{1});
else
    figure(1)
end

clf
if isfield(model, 'vis') && isfield(model.vis, 'startDim')
    visualiseInfo.dim1 = model.vis.startDim{1};
    visualiseInfo.dim2 = model.vis.startDim{2};
else
    visualiseInfo.dim1 = 1;
    visualiseInfo.dim2 = 2;
end
if isfield(model, 'vis') && isfield(model.vis, 'startPos')
    visualiseInfo.latentPos = model.vis.startPos;
else
    visualiseInfo.latentPos = zeros(1, model.q);
end
visualiseInfo.model = model;
visualiseInfo.lbls = YLbls;
if showVariance
    visualiseInfo.plotAxes = lvmScatterPlot(model, YLbls);
else
    visualiseInfo.plotAxes = lvmScatterPlotNoVar(model, YLbls, [], [visualiseInfo.dim1 visualiseInfo.dim2]);
end

if showVariance
    lvmSetPlot;
else
    lvmSetPlotNoVar(lvmClassVisualiseFunc);
end
visualiseInfo.latentHandle = line(visualiseInfo.latentPos(visualiseInfo.dim1), visualiseInfo.latentPos(visualiseInfo.dim2), 'markersize', 20, 'color', ...
                                  [0 0 0], 'marker', '.', 'visible', ...
                                  'on', 'erasemode', 'xor');

visualiseInfo.clicked = 0;
visualiseInfo.digitAxes = [];
visualiseInfo.digitIndex = [];

    visualiseInfo.dynamicsRadio = ...
        uicontrol('Style', 'radiobutton', ...
        'String', 'Run Dynamics', ...
        'units', 'normalized', ...
        'position', [0 0 0.2 0.05], ...
        'Callback', [lvmClassVisualiseFunc '(''toggleDynamics'')'], ...
        'value', 0);

    visualiseInfo.dynamicsSlider = ...
        uicontrol('Style', 'slider', ...
        'String', 'Time', ...
        'sliderStep', [0.01, 0.1], ...
        'units', 'normalized', ...
        'position', [0 0.95 1 0.05], ...
        'callback', [lvmClassVisualiseFunc '(''dynamicsSliderChange'')']);

    if ~isfield(model, 'dynamics') | isempty(model.dynamics)
        set(visualiseInfo.dynamicsRadio, 'visible', 'off');
        set(visualiseInfo.dynamicsSlider, 'visible', 'off');
    else
        if ~isfield(model.dynamics, 'dynamicsType')
            set(visualiseInfo.dynamicsRadio, 'visible', 'on');
            set(visualiseInfo.dynamicsSlider, 'visible', 'off');
        else
            switch model.dynamics.dynamicsType
                case 'regressive'
                    set(visualiseInfo.dynamicsRadio, 'visible', 'off');
                    set(visualiseInfo.dynamicsSlider, 'visible', 'on');
                    set(visualiseInfo.dynamicsSlider, 'min', min(model.dynamics.X), ...
                        'max', max(model.dynamics.X), ...
                        'value', model.dynamics.X(1))
                case 'auto-regressive'
                    set(visualiseInfo.dynamicsRadio, 'visible', 'on');
                    set(visualiseInfo.dynamicsSlider, 'visible', 'off');
            end
        end
    end

visualiseInfo.runDynamics = false;

% Set the callback function
set(gcf, 'WindowButtonMotionFcn', [lvmClassVisualiseFunc '(''move'')'])
set(gcf, 'WindowButtonDownFcn', [lvmClassVisualiseFunc '(''click'')'])

if isfield(model, 'vis') && isfield(model.vis, 'figHandle')
    figure(model.vis.figHandle{2});
else
    figure(2)
end
clf

%
% if length(visualiseFunction)>4 & strcmp(visualiseFunction(1:5), 'image') & length(varargin)>0
%   set(gcf, 'menubar', 'none')
%   xPixels = 115;
%   yPixels = 115;
%   set(gcf, 'position', [232 572 xPixels yPixels/varargin{1}(1)*varargin{1}(2)])
%   visualiseInfo.visualiseAxes = subplot(1, 1, 1);
%   xWidth = varargin{1}(1)/xPixels;
%   yHeight = varargin{1}(2)/yPixels;
%   set(visualiseInfo.visualiseAxes, 'position', [0.5-xWidth/2 0.5-yHeight/2 xWidth yHeight])
% else
  visualiseInfo.visualiseAxes =subplot(1, 1, 1);
% end

visData = zeros(1,model.d);
if(length(visualiseFunction)>4 & strcmp(visualiseFunction(1:5), 'image'))
  visData(1) = min(min(model.y));
  visData(end) = max(max(model.y));
else
  [void, indMax]= max(sum((model.y.*model.y), 2));
  visData = model.y(indMax, :);
end

set(get(visualiseInfo.visualiseAxes, 'title'), 'string', 'Y', 'fontsize',30);
set(visualiseInfo.visualiseAxes, 'position', [0.05 0.05 0.9 0.8]);

visualiseInfo.visualiseFunction = str2func(visualiseFunction);
visHandle = visualiseInfo.visualiseFunction(visData, varargin{:});
handleType = get(visHandle, 'type');
if ~strcmp(handleType, 'figure')
    set(visHandle, 'erasemode', 'xor');
end
% Pass the data to visualiseInfo
visualiseInfo.model = model;
visualiseInfo.varargin = varargin;
visualiseInfo.visualiseModify = str2func(visualiseModify);
visualiseInfo.visHandle = visHandle;

hold off

%hsvargplvmClassVisualise('updateLatentRepresentation')
%visualiseInfo.clicked = 1; %%%%
%hsvargplvmClassVisualise('move')
%hsvargplvmClassVisualise('click')

author: SheffieldML

repo: deepGP

save_path: github-repos/MATLAB/SheffieldML-deepGP


text:
function DeriveDynamicsDP(P)

%FUNCTION:
%   This function is used to derive the analytic equations of motion for a
%   forced double pendulum. This also does the kimenatics and energy
%   calculations.

%State Naming Conventions:
% th = absolute angle of the first link measured wrt the positive horizontal axis (i)
% phi = absolute angle of the second link measured wrt the positive horizontal axis (i)
% Dth = first time derivative of th
% Dphi = first time derivative of phi

%NOTE: It might be faster to use the jacobian command to find the symbolic
%coeffieints of the mass matrix and then invert the system, rather than
%symbolically inverting the matrix.
%

% Define the angles and derivatives
    th = sym('th');
    Dth = sym('Dth');
    DDth = sym('DDth');

    phi = sym('phi');
    Dphi = sym('Dphi');
    DDphi = sym('DDphi');

% Define the scalar parameters
    g = sym('g');   %gravity
    L = sym('L');    %Lenght of each link
    m1 = sym('m1');    %mass of the link
    m2 = sym('m2');    %mass of the link

% Known Vectors
    F1_x = sym('F1_x');
    F1_y = sym('F1_y');
    F1 = [F1_x;F1_y];   %External force at CoM of first link

    F2_x = sym('F2_x');
    F2_y = sym('F2_y');
    F2 = [F2_x;F2_y];   %External force at CoM of 2nd link

    M1 = sym('M1');   %Input torque on link on
    M2 = sym('M2');   %Input torque between links 1 and 2

% UNIT VECTORS:
    i = [1;0];
    j = [0;1];

    a1 = cos(th)*i + sin(th)*j;   %The direction along the first link
    b1 = -sin(th)*i + cos(th)*j;
    Da1 = Dth*b1;
    Db1 = -Dth*a1;
    DDa1 = DDth*b1 + Dth*Db1;
    DDb1 = -DDth*a1 -Dth*Da1;

    a2 = cos(phi)*i + sin(phi)*j;   %The direction along the second link
    b2 = -sin(phi)*i + cos(phi)*j;
    Da2 = Dphi*b2;
    Db2 = -Dphi*a2;
    DDa2 = DDphi*b2 + Dphi*Db2;
    DDb2 = -DDphi*a2 -Dphi*Da2;

%Weights
    W1 = -m1*g*j;   %weight of the first link
    W2 = -m2*g*j;   %weight of the second link

%Kinematic vectors
    r_P1_O = L*a1;    %Position of the point mass 1
    v_P1_O = L*Da1;
    a_P1_O = L*DDa1;

    r_P2_O = L*a1 + L*a2;    %Position of point mass 2
    v_P2_O = L*Da1 + L*Da2;
    a_P2_O = L*DDa1 + L*DDa2;

    r_P2_P1 = L*a2;   %Relative position of the tip with respect to the mid joint

%Momentum balance for both links about the origin
    %       = Moment from weight 1 +  moment from weight 2 + Control torque 1
    Sum_M_O = Cross(r_P1_O,F1+W1) + Cross(r_P2_O,F2+W2) + M1;
    %        = translation mass 1  + translation mass 2
    Sum_DH_O = Cross(r_P1_O,m1*a_P1_O) + Cross(r_P2_O,m2*a_P2_O);

%Momentum balance for second link about central pivot
    %         moment from weight 2  +  control moment
    Sum_M_P1 = Cross(r_P2_P1,F2+W2) + M2;
    %         translation mass 2 +
    Sum_DH_P1 = Cross(r_P2_P1,m2*a_P2_O);

%Simplify
    AMB_1 = simplify(Sum_M_O - Sum_DH_O);
    AMB_2 = simplify(Sum_M_P1 - Sum_DH_P1);

% Solve the system of equations:
    Soln = solve( AMB_1, ...    %AMB for system
           AMB_2, ...    %AMB for second link
            DDth,...                      %acceleration of first joint
            DDphi  );                    %acceleration of second joint

    Soln.DDth = simplify(Soln.DDth);   %Simplify the result
    Soln.DDphi = simplify(Soln.DDphi);   %Simplify the result

%Write the results to a file  --  these are scripts!
if P.misc.CppFlag
    WriteDynamicsFile_Cpp    %Call a script that write the dynamics to a file
else
    WriteDynamicsFile_Matlab;   %Call a script that write the dynamics to a file
end
WriteKinematicsFile_Matlab;   %Call a script that writes the equations for kinetics

end

author: MatthewPeterKelly

repo: dscTutorials


text:
function [ node_xy, element_node, element_neighbor ] = example2_q4_mesh ( ...
  node_num, element_num )

%*****************************************************************************80
%
%% EXAMPLE2_Q4_MESH sets up example #2 Q4 mesh.
%
%  Discussion:
%
%    The region is a semicircle.  This example includes degenerate elements
%    (the first layer of elements is touching the origin, and so has a side
%    of length zero).  The elements are not parallelograms.  And the elements
%    vary in size.
%
%    Because of the treatment of node 1, algorithms for counting boundary
%    edges may become "confused".
%
%    The appropriate values of NODE_NUM and ELEMENT_NUM can be found by
%    calling EXAMPLE1_Q4_MESH_SIZE first.
%
%   29---30---31---32---33---34---35---36---37
%    | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 |
%   20---21---22---23---24---25---26---27---28
%    | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
%   11---12---13---14---15---16---17---18---19
%    |  9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
%    2----3----4----5----6----7----8----9---10
%    |  1 |  2 |  3 |  4 |  5 |  6 |  7 |  8 |
%    1----1----1----1----1----1----1----1----1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 February 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, integer ELEMENT_NUM, the number of elements.
%
%    Output, real NODE_XY(2,NODE_NUM), the coordinates of the
%    nodes.
%
%    Output, integer ELEMENT_NODE(4,ELEMENT_NUM), the nodes
%    that make up the elements.
%
%    Output, integer ELEMENT_NEIGHBOR(4,ELEMENT_NUM), the
%    element neighbors on each side.  Negative values indicate edges that
%    lie on the exterior.
%
  k = 1;
  node_xy(1,k) = 0.0;
  node_xy(2,k) = 0.0;

  for row = 1 : 4
    r = row;
    for col = 0 : 8
      a = ( 8 - col ) * pi / 8.0;
      k = k + 1;
      node_xy(1,k) = r * cos ( a );
      node_xy(2,k) = r * sin ( a );
    end
  end

  element = 0;
  for row = 0 : 3
    for col = 0 : 7
      element = element + 1;
      if ( row == 0 )
        element_node(1,element) = 1;
        element_node(2,element) = 1;
        element_node(3,element) = col + 3;
        element_node(4,element) = col + 2;
      else
        element_node(1,element) = element_node(4,element-8);
        element_node(2,element) = element_node(3,element-8);
        element_node(3,element) = element_node(2,element) + 9;
        element_node(4,element) = element_node(1,element) + 9;
      end
    end
  end

  element = 0;
  for row = 0 : 3
    for col = 0 : 7
      element = element + 1;
      if ( row == 0 )
        element_neighbor(1,element) = -1;
      else
        element_neighbor(1,element) = element - 8;
      end
      if ( col == 7 )
        element_neighbor(2,element) = -1;
      else
        element_neighbor(2,element) = element + 1;
      end
      if ( row == 3 )
        element_neighbor(3,element) = - 1;
      else
        element_neighbor(3,element) = element + 8;
      end
      if ( col == 0 )
        element_neighbor(4,element) = - 1;
      else
        element_neighbor(4,element) = element - 1;
      end
    end
  end

  return
end


text:
function set_legend_fontsize(h_leg, fontsize);
set(h_leg, 'FontSize', fontsize);

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


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

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

% Last Modified by GUIDE v2.5 09-Aug-2020 18:29:26

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_GraphicalAnalysisGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_GraphicalAnalysisGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before lvd_GraphicalAnalysisGUI is made visible.
function lvd_GraphicalAnalysisGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to lvd_GraphicalAnalysisGUI (see VARARGIN)

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

    % Set up GUI
    lvdData = varargin{1};
    setappdata(hObject,'lvdData',lvdData);

    handles.ma_LvdMainGUI = varargin{2};

    exclude = getLvdGAExcludeList();

    taskList = lvd_getGraphAnalysisTaskList(lvdData, exclude);
    set(handles.depVarListbox,'String',taskList);

    maStateLog = lvdData.stateLog.getMAFormattedStateLogMatrix(true);

%     propNames = {'Liquid Fuel/Ox','Monopropellant','Xenon'};
    propNames = lvdData.launchVehicle.tankTypes.getFirstThreeTypesCellArr();
    substituteDefaultPropNamesWithCustomNamesInDepVarListbox(handles.depVarListbox, propNames);
    useSubplotCheckbox_Callback(handles.useSubplotCheckbox, [], handles);
    set(handles.startTimeText,'String',fullAccNum2Str(min(maStateLog(:,1))));
    set(handles.endTimeText,'String',fullAccNum2Str(max(maStateLog(:,1))));
    populateBodiesCombo(lvdData.celBodyData, handles.refBodyCombo);
    % populateOtherSCCombo(handles, handles.refSpacecraftCombo);
    % populateStationsCombo(handles, handles.refStationCombo);
    indepVarCombo_Callback(handles.indepVarCombo, [], handles);

    setappdata(hObject,'xLineValue',[]);
    setappdata(hObject,'yLineValue',[]);

    % Update handles structure
    guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = lvd_GraphicalAnalysisGUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
    varargout{1} = handles.output;

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

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

    if(strcmpi(selected,'Time') || strcmpi(selected,'Mission Elapsed Time'))
        set(handles.showEventTerminationCheckbox,'Enable','on');
%         set(handles.showSoITransCheckbox,'Enable','on');
        set(handles.showPeriCheckbox,'Enable','on');
        set(handles.showApoCheckbox,'Enable','on');
    else
        set(handles.showEventTerminationCheckbox,'Enable','off');
%         set(handles.showSoITransCheckbox,'Enable','off');
        set(handles.showPeriCheckbox,'Enable','off');
        set(handles.showApoCheckbox,'Enable','off');
    end

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

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

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

% Hint: get(hObject,'Value') returns toggle state of useSubplotCheckbox
    if(get(hObject,'Value'))
        set(handles.subPlotSizeXText,'Enable','on');
        set(handles.subPlotSizeYText,'Enable','on');
    else
        set(handles.subPlotSizeXText,'Enable','off');
        set(handles.subPlotSizeYText,'Enable','off');
    end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if(~isempty(errMsg))
        msgbox(errMsg,'Errors were found while validating your split value.  Please sure value is between the given bounds.','error');
        return;
    end

    lvdData = getappdata(handles.lvd_GraphicalAnalysisGUI,'lvdData');
    celBodyData = lvdData.celBodyData;
    maStateLog = lvdData.stateLog.getMAFormattedStateLogMatrix(true);

    taskInds = get(handles.depVarListbox,'Value');
    if(isempty(taskInds))
        errordlg('Error: No valid dependent variables selected.');
        return;
    end

    startTimeUT = str2double(get(handles.startTimeText,'String'));
    endTimeUT = str2double(get(handles.endTimeText,'String'));

    lineWidth = str2double(get(handles.lineWidthText,'String'));

    contents = cellstr(get(handles.lineColorCombo,'String'));
    lineColorStr = contents{get(handles.lineColorCombo,'Value')};
    lineColor = getLineSpecColorFromString(lineColorStr);

    contents = cellstr(get(handles.backgndColorCombo,'String'));
    bgColorStr = contents{get(handles.backgndColorCombo,'Value')};
    bgColor = getLineSpecColorFromString(bgColorStr);

    contents = cellstr(get(handles.lineSpecCombo,'String'));
    lineTypeStr = contents{get(handles.lineSpecCombo,'Value')};
    switch lineTypeStr
        case 'Solid Line'
            lineType = '-';
        case 'Dashed Line'
            lineType = '--';
        case 'Dotted Line'
            lineType = ':';
        case 'Dash-dot Line'
            lineType = '-.';
        otherwise
            lineType = '-';
    end

    propNames = lvdData.launchVehicle.tankTypes.getFirstThreeTypesCellArr();

    lvdSubLog = lvdData.stateLog.getStateLogEntriesBetweenTimes(startTimeUT, endTimeUT);
    maSubLog = maStateLog(maStateLog(:,1) >= startTimeUT & maStateLog(:,1) <= endTimeUT,:);

    contentsIndep = cellstr(get(handles.indepVarCombo,'String'));
    indepVarValues = zeros(size(maSubLog,1), 2);
    indepVarStr = deblank(contentsIndep{get(handles.indepVarCombo,'Value')});

    contentsIndepUnit = cellstr(get(handles.indepVarTimeUnit,'String'));
    indepVarUnitStr = deblank(contentsIndepUnit{get(handles.indepVarTimeUnit,'Value')});

    [secInMin, secInHr, secInDay, secInYear] = getSecondsInVariousTimeUnits();
    switch indepVarUnitStr
        case 'Seconds'
            indepTimeUnit = 'sec';
            indepTimeUnitMult = 1;
        case 'Minutes'
            indepTimeUnit = 'min';
            indepTimeUnitMult = 1/secInMin;
        case 'Hours'
            indepTimeUnit = 'hr';
            indepTimeUnitMult = 1/secInHr;
        case 'Days'
            indepTimeUnit = 'day';
            indepTimeUnitMult = 1/secInDay;
        case 'Years'
            indepTimeUnit = 'year';
            indepTimeUnitMult = 1/secInYear;
    end

    switch indepVarStr
        case 'Time'
            indepVarValues = indepTimeUnitMult*[maSubLog(:,1), maSubLog(:,1)];
            indepVarUnits = indepTimeUnit;

        case 'Mission Elapsed Time'
            indepVarValues = indepTimeUnitMult*[maSubLog(:,1) - maStateLog(1,1), maSubLog(:,1)];
            indepVarUnits = indepTimeUnit;

        case 'True Anomaly'
            for(i=1:size(maSubLog,1))
                indepVarValues(i,:) = [ma_GAKeplerElementsTask(maSubLog(i,:), 'tru', celBodyData), maSubLog(i,1)];
            end
            indepVarUnits = 'deg';

        case 'Longitude'
            for(i=1:size(maSubLog,1))
                indepVarValues(i,:) = [ma_GALongLatAltTasks(maSubLog(i,:), 'long', celBodyData), maSubLog(i,1)];
            end
            indepVarUnits = 'degE';

        case 'Altitude'
            for(i=1:size(maSubLog,1))
                indepVarValues(i,:) = [ma_GALongLatAltTasks(maSubLog(i,:), 'alt', celBodyData), maSubLog(i,1)];
            end
            indepVarUnits = 'km';
    end

    hWaitBar = waitbar(0,'Computing Dependent Variables...','WindowStyle','modal');
    depVarValues = zeros(size(maSubLog,1), length(taskInds));
    depVarUnits = cell(1,length(taskInds));
    contentsDep = strtrim(cellstr(get(handles.depVarListbox,'String')));
    prevDistTraveled = 0;

    hRefBodyCombo = handles.refBodyCombo;
    contents = cellstr(get(hRefBodyCombo,'String'));
    refBodyStr = contents{get(hRefBodyCombo,'Value')};
    refBodyInfo = celBodyData.(strtrim(lower(refBodyStr)));
    refBodyId = refBodyInfo.id;

    hRefSCCombo = handles.refSpacecraftCombo;
    if(strcmpi(get(hRefSCCombo,'Enable'),'off'))
        otherSCId = [];
    else
        try
            refSCInd = get(hRefSCCombo,'Value');
            otherSCs = maData.spacecraft.otherSC;
            otherSCId = otherSCs{refSCInd}.id;
        catch
            otherSCId = [];
        end
    end

%     hRefStnCombo = handles.refStationCombo;
%     if(strcmpi(get(hRefStnCombo,'Enable'),'off'))
%         stationID = [];
%     else
%         try
%             refSCInd = get(hRefStnCombo,'Value');
%             stations = maData.spacecraft.stations;
%             stationID = stations{refSCInd}.id;
%         catch
%
%         end
%     end

    stationID = [];

    dataEvtNums = [];
    maTaskList = ma_getGraphAnalysisTaskList({});
    for(i=1:size(maSubLog,1))
        for(j=1:length(taskInds))
            taskInd = taskInds(j);
            taskStr = contentsDep{taskInd};

            if(isvalid(hWaitBar))
                waitbar(i/size(maSubLog,1), hWaitBar, sprintf('Computing Dependent Variables...\n[%u of %u]', i, size(maSubLog,1)));
            end

            if(ismember(taskStr,maTaskList))
                [depVarValues(i,j), depVarUnits{j}, prevDistTraveled] = ma_getDepVarValueUnit(i, maSubLog, taskStr, prevDistTraveled, refBodyId, otherSCId, stationID, propNames, [], celBodyData, false);
            else
                [depVarValues(i,j), depVarUnits{j}] = lvd_getDepVarValueUnit(i, lvdSubLog, taskStr, refBodyId, celBodyData, false);
            end
        end

        dataEvtNums(i) = maSubLog(i,13);
    end
    close(hWaitBar);

    plotMethods = [lvdData.script.evts.plotMethod];
    if(any(plotMethods == EventPlottingMethodEnum.SkipFirstState))
        evtIndsToInsertNaNBetween = find(plotMethods == EventPlottingMethodEnum.SkipFirstState);

        stateInds = [];
        for(i=1:length(evtIndsToInsertNaNBetween))
            evtInd = evtIndsToInsertNaNBetween(i);
            stateInd = find(maSubLog(:,13) == evtInd,1,'first');
            if(stateInd > 1)
                stateInds(end+1) = stateInd;
            end
        end

        numIndepVars = size(indepVarValues,2);
        numDepVars = size(depVarValues,2);
        for(i=1:length(stateInds))
            indepVarValues = [indepVarValues(1:stateInds(i)-1,:); NaN(1,numIndepVars); indepVarValues(stateInds(i)+1:end,:)];
            depVarValues = [depVarValues(1:stateInds(i)-1,:); NaN(1,numDepVars); depVarValues(stateInds(i)+1:end,:)];

%             if(i < length(stateInds))
%                 stateInds(i+1:end) = stateInds(i+1:end)+1;  %accounts for the fact that we're inserting data
%             end
        end
    end

    useEvtLineColor = logical(handles.useEvtLineColorsCheckbox.Value);
    evts = [lvdData.script.evts];

    figNum = 100;
    if(get(handles.useSubplotCheckbox,'Value'))
        subPlotMaxX = str2double(get(handles.subPlotSizeXText,'String'));
        subPlotMaxY = str2double(get(handles.subPlotSizeYText,'String'));

        hFig = figure(figNum);
        whitebg(hFig, bgColor);
        plotNum = 0;
        for(i = 1:size(depVarValues,2))
            plotNum = plotNum  +1;
            if(plotNum > subPlotMaxX*subPlotMaxY)
                figNum = figNum + 1;
                hFig = figure(figNum);
                plotNum = 1;
            end

            data = depVarValues(:,i);

            taskInd = taskInds(i);
            taskStr = contentsDep{taskInd};

            subplot(subPlotMaxX,subPlotMaxY,plotNum);
            plotData(hFig, indepVarValues, data, lineColor, useEvtLineColor, evts, dataEvtNums, lineType, lineWidth, indepVarStr, taskStr, bgColor, indepVarUnits, indepTimeUnitMult, depVarUnits{i}, maStateLog, startTimeUT, endTimeUT, celBodyData, handles.lvd_GraphicalAnalysisGUI);
        end
    else
        for(i = 1:size(depVarValues,2)) %#ok<*NO4LP>
            data = depVarValues(:,i);

            taskInd = taskInds(i);
            taskStr = contentsDep{taskInd};

            hFig = figure(figNum+i);
            whitebg(hFig, bgColor);
            plotData(hFig, indepVarValues, data, lineColor, useEvtLineColor, evts, dataEvtNums, lineType, lineWidth, indepVarStr, taskStr, bgColor, indepVarUnits, indepTimeUnitMult, depVarUnits{i}, maStateLog, startTimeUT, endTimeUT, celBodyData, handles.lvd_GraphicalAnalysisGUI);
        end
    end

    if(get(handles.generateTextOutputCheckbox,'Value'))
        matSave = getappdata(handles.ma_LvdMainGUI,'current_save_location');
        [pathstr,name,~] = fileparts(matSave);
        if(isempty(pathstr))
            pathstr = uigetdir(pwd,'Select folder to save tabular text output');
            name = 'UntitledMission';
        end
        csvFilename = [pathstr,'\',name,'_GraphicalAnalysis_',datestr(now,'yyyymmdd_HHMMSS'),'.csv'];

        indepVarUnitStr = indepVarUnits;
        if(~isempty(indepVarUnitStr))
            indepVarUnitStr = [' [',indepVarUnitStr,']'];
        else
            indepVarUnitStr = '';
        end

        taskStrs = [indepVarStr,indepVarUnitStr,','];
        for(i = 1:length(taskInds)) %#ok<*NO4LP>
            taskInd = taskInds(i);
            taskStr = contentsDep{taskInd};

                depVarUnitStr = depVarUnits{i};
                if(~isempty(depVarUnitStr))
                    depVarUnitStr = [' [',depVarUnitStr,']']; %#ok<*AGROW>
                else
                    depVarUnitStr = '';
                end

                taskStr = [taskStr,depVarUnitStr];

            taskStrs = [taskStrs,taskStr,','];
        end
        taskStrs = [taskStrs,'\n'];
        if(pathstr ~= 0)
            fid = fopen(csvFilename,'wt+');
            fprintf(fid,taskStrs);
            fclose(fid);

            M = [indepVarValues(:,1),depVarValues];
            dlmwrite(csvFilename, M, '-append','precision', 15);

            msgbox(sprintf('Tabular output written to file: \n%s',csvFilename), 'Tabular Output', 'help');
        end
    end

function plotData(hFig, indepVarValues, data, lineColor, useEvtLineColor, evts, dataEvtNums, lineType, lineWidth, indepVarStr, taskStr, bgColor, indepVarUnitStr, indepTimeUnitMult, depVarUnitStr, maStateLog, startTimeUT, endTimeUT, celBodyData, hGAFig)
    xLineValue = getappdata(hGAFig,'xLineValue');
    yLineValue = getappdata(hGAFig,'yLineValue');

    hold on;
    for(i=1:length(evts))
        evt = evts(i);
        eventNum = evt.getEventNum();

        bool = dataEvtNums == eventNum;

        subIndVal = indepVarValues(bool,1);
        subData = data(bool);

        switch(evt.plotMethod)
            case EventPlottingMethodEnum.PlotContinuous
                %nothing

            case EventPlottingMethodEnum.SkipFirstState
                subIndVal = subIndVal(2:end);
                subData = subData(2:end);

%                 maStateLog =

            case EventPlottingMethodEnum.DoNotPlot
                maStateLog(maStateLog(:,13) == eventNum,:) = [];

                continue;

            otherwise
                error('Unknown event plotting method: %s', EventPlottingMethodEnum.DoNotPlot.name);
        end

        if(useEvtLineColor)
            lineColor = evt.colorLineSpec.color.color;
            plot(subIndVal, subData, 'Color',lineColor, 'LineStyle',lineType, 'LineWidth',lineWidth);
        else
            plot(subIndVal, subData, 'Color',lineColor, 'LineStyle',lineType, 'LineWidth',lineWidth);
        end
    end

    minData = min(data);
    maxData = max(data);
    if(minData == maxData)
        minData = minData - 0.75;
        maxData = maxData + 0.75;
    end
    onePercData = (maxData-minData)/100;

    if(~isempty(xLineValue))
        if(xLineValue >= min(indepVarValues(:,1)) && xLineValue <= max(indepVarValues(:,1)))
            if(strcmpi(bgColor,'c'))
                markerLineColor = 'w';
            else
                markerLineColor = 'c';
            end
            plot([xLineValue xLineValue], [minData maxData],markerLineColor,'LineWidth',0.25);
        end
    end

    if(~isempty(yLineValue))
        if(yLineValue >= min(data) && yLineValue <= max(data))
            if(strcmpi(bgColor,'c'))
                markerLineColor = 'w';
            else
                markerLineColor = 'c';
            end
            plot([min(indepVarValues(:,1)) max(indepVarValues(:,1))], [yLineValue yLineValue],markerLineColor,'LineWidth',0.25);
        end
    end

    subLog = maStateLog(maStateLog(:,1) >= startTimeUT & maStateLog(:,1) <= endTimeUT,:);
    subLogUnsorted = subLog;
    subLog = sortrows(subLog,[1]);
    subLog = unique(subLog,'rows');

    hShowMan = findobj('Tag','showEventTerminationCheckbox');
    if(get(hShowMan,'Value') && strcmpi(get(hShowMan,'Enable'), 'on'))
        if(strcmpi(bgColor,'r'))
            evtEndLineColor = 'w';
        else
            evtEndLineColor = 'r';
        end

        allEventNums = subLogUnsorted(:,13);
        x = diff(allEventNums)~=0;
        inds = find(x);
        inds = [inds; length(allEventNums)];

        minData = min(data);
        maxData = max(data);
        if(minData == maxData)
            minData = minData - 0.75;
            maxData = maxData + 0.75;
        end

        for(i=1:length(inds))
            ind = inds(i);

            eventTime = subLogUnsorted(ind,1)*indepTimeUnitMult;
            indepVarEventLoc = indepVarValues(indepVarValues(:,2)==eventTime,1);
            indepVarEventLoc = indepVarEventLoc(1);

            evtNum = subLogUnsorted(ind,13);

            plot([indepVarEventLoc indepVarEventLoc], [minData, maxData],evtEndLineColor,'LineWidth',0.25);
            text(indepVarEventLoc,maxData-8*onePercData,sprintf(' Event %u End ',evtNum),'Color',evtEndLineColor);

        end
    end

    hShowSoI = findobj('Tag','showSoITransCheckbox');
    if(get(hShowSoI,'Value') && strcmpi(get(hShowSoI,'Enable'), 'on'))
        if(strcmpi(bgColor,'m'))
            soiLineColor = 'w';
        else
            soiLineColor = 'm';
        end

        allBodyIDs = subLog(:,8);
        x = diff(allBodyIDs)~=0;
        inds = find(x);
        for(i=1:length(inds))
            ind = inds(i)+1;

            bodyLog = subLog(ind,:);
            bodyID = bodyLog(1,8);
            bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);

            if(bodyLog(1,1) == startTimeUT)
                continue;
            end
            eventTime = bodyLog(1,1)*indepTimeUnitMult;
            indepVarEventLoc = indepVarValues(indepVarValues(:,2)==eventTime,1);
            indepVarEventLoc = indepVarEventLoc(1);

            minData = min(data);
            maxData = max(data);
            if(minData == maxData)
                minData = minData - 0.75;
                maxData = maxData + 0.75;
            end

            plot([indepVarEventLoc indepVarEventLoc], [minData, maxData],soiLineColor,'LineWidth',0.25);
            text(indepVarEventLoc,maxData-2*onePercData,[' To ',bodyInfo.name],'Color',soiLineColor);
        end
    end

    hShowPeri = findobj('Tag','showPeriCheckbox');
    if(get(hShowPeri,'Value') && strcmpi(get(hShowPeri,'Enable'), 'on'))
        if(strcmpi(bgColor,'g'))
            periLineColor = 'w';
        else
            periLineColor = 'g';
        end

        periCnt = 1;
        allBodyIDs = subLog(:,8);
        x = diff(allBodyIDs)~=0;
        inds = find(x)+1;
        inds = [1 inds' length(allBodyIDs)+1];
        for(i=1:length(inds)-1)
            ind = inds(i);
            nextInd = inds(i+1)-1;

            bodyLog = subLog(ind:nextInd,:);
            bodyID = bodyLog(1,8);
            bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);

            [~, ~, ~, ~, ~, tru] = vect_getKeplerFromState(bodyLog(:,2:4)',bodyLog(:,5:7)',bodyInfo.gm);
            tru = angleNegPiToPi(tru);

            for(j=2:length(tru))
                tru1 = tru(j-1);
                tru2 = tru(j);

%                 if(((tru1 > tru2 && abs(tru1-tru2)>pi) || (tru1 < 0 && tru2 >= 0)) && bodyLog(j-1,8)==bodyLog(j,8))
                if(((tru1 < 0 && tru2 >= 0)) && bodyLog(j-1,8)==bodyLog(j,8))
                    eventTime = bodyLog(j,1)*indepTimeUnitMult;
                    indepVarEventLoc = indepVarValues(indepVarValues(:,2)==eventTime,1);
                    indepVarEventLoc = indepVarEventLoc(1);

                    minData = min(data);
                    maxData = max(data);
                    if(minData == maxData)
                        minData = minData - 0.75;
                        maxData = maxData + 0.75;
                    end

                    plot([indepVarEventLoc indepVarEventLoc], [minData, maxData],periLineColor,'LineWidth',0.25);
                    text(indepVarEventLoc,maxData-4*onePercData,[' P',num2str(periCnt)],'Color',periLineColor);
                    periCnt = periCnt + 1;
                end
            end
        end
    end

	hShowApo = findobj('Tag','showApoCheckbox');
    if(get(hShowApo,'Value') && strcmpi(get(hShowApo,'Enable'), 'on'))
        if(strcmpi(bgColor,'b'))
            apoLineColor = 'w';
        else
            apoLineColor = 'b';
        end

        apoCnt = 1;
        allBodyIDs = subLog(:,8);
        x = diff(allBodyIDs)~=0;
        inds = find(x)+1;
        inds = [1 inds' length(allBodyIDs)+1];
        for(i=1:length(inds)-1)
            ind = inds(i);
            nextInd = inds(i+1)-1;

            bodyLog = subLog(ind:nextInd,:);
            bodyID = bodyLog(1,8);
            bodyInfo = getBodyInfoByNumber(bodyID, celBodyData);

            [~, ~, ~, ~, ~, tru] = vect_getKeplerFromState(bodyLog(:,2:4)',bodyLog(:,5:7)',bodyInfo.gm);

            for(j=2:length(tru))
                tru1 = tru(j-1);
                tru2 = tru(j);

                if(tru1 < pi && tru2 >= pi && bodyLog(j-1,8)==bodyLog(j,8))
                    eventTime = bodyLog(j,1)*indepTimeUnitMult;
                    indepVarEventLoc = indepVarValues(indepVarValues(:,2)==eventTime,1);
                    indepVarEventLoc = indepVarEventLoc(1);

                    minData = min(data);
                    maxData = max(data);
                    if(minData == maxData)
                        minData = minData - 0.75;
                        maxData = maxData + 0.75;
                    end

                    plot([indepVarEventLoc indepVarEventLoc], [minData, maxData],apoLineColor,'LineWidth',0.25);
                    text(indepVarEventLoc,maxData-6*onePercData,[' A',num2str(apoCnt)],'Color',apoLineColor);
                    apoCnt = apoCnt + 1;
                end
            end
        end
    end

    hGridOn = findobj('Tag','showGridCheckboxGA');
    if(get(hGridOn,'Value'))
        grid on;
    else
        grid off;
    end

    if(~isempty(indepVarUnitStr))
        indepVarUnitStr = [' [',indepVarUnitStr,']'];
    else
        indepVarUnitStr = '';
    end

    if(~isempty(depVarUnitStr))
        depVarUnitStr = [' [',depVarUnitStr,']'];
    else
        depVarUnitStr = '';
    end

    xlabel([indepVarStr,indepVarUnitStr]);
    ylabel([taskStr,depVarUnitStr]);

    hold off;

    dcmObj = datacursormode;
    set(dcmObj,'UpdateFcn',@dataTipFormatFunc,'Enable','on');

function errMsg = validateInputs(handles)
%     maData = getappdata(handles.ma_MainGUI,'ma_data');
%     celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');
    lvdData = getappdata(handles.lvd_GraphicalAnalysisGUI,'lvdData');
    celBodyData = lvdData.celBodyData;
    stateLog = lvdData.stateLog.getMAFormattedStateLogMatrix(true);

    errMsg = {};

    stateLogMinUT = floor(min(stateLog(:,1))*10000)/10000;
    stateLogMaxUT = ceil(max(stateLog(:,1))*10000)/10000;

    value = str2double(get(handles.startTimeText,'String'));
    enteredStr = get(handles.startTimeText,'String');
    numberName = 'Start Time (UT)';
    lb = stateLogMinUT;
    ub = stateLogMaxUT;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    value = str2double(get(handles.endTimeText,'String'));
    enteredStr = get(handles.endTimeText,'String');
    numberName = 'End Time (UT)';
    lb = stateLogMinUT;
    ub = stateLogMaxUT;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        startUTEntered = str2double(get(handles.startTimeText,'String'));

        value = str2double(get(handles.endTimeText,'String'));
        enteredStr = get(handles.endTimeText,'String');
        numberName = 'End Time (UT)';
        lb = startUTEntered;
        ub = stateLogMaxUT;
        isInt = false;
        errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);
    end

    if(get(handles.useSubplotCheckbox,'Value'))
        value = str2double(get(handles.subPlotSizeXText,'String'));
        enteredStr = get(handles.subPlotSizeXText,'String');
        numberName = 'Sub Plot X Size';
        lb = 1;
        ub = 10;
        isInt = true;
        errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

        value = str2double(get(handles.subPlotSizeYText,'String'));
        enteredStr = get(handles.subPlotSizeYText,'String');
        numberName = 'Sub Plot Y Size';
        lb = 1;
        ub = 10;
        isInt = true;
        errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);
    end

    value = str2double(get(handles.lineWidthText,'String'));
    enteredStr = get(handles.lineWidthText,'String');
    numberName = 'Line Width';
    lb = 0.25;
    ub = 5;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

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

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

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

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

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

% Hints: get(hObject,'String') returns contents of startTimeText as text
%        str2double(get(hObject,'String')) returns contents of startTimeText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

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

% Hints: get(hObject,'String') returns contents of endTimeText as text
%        str2double(get(hObject,'String')) returns contents of endTimeText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

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

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

% --------------------------------------------------------------------
function enterUTAsDateTime_Callback(hObject, eventdata, handles)
% hObject    handle to enterUTAsDateTime (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    secUT = enterUTAsDateTimeGUI(str2double(get(gco, 'String')));
    if(secUT >= 0)
        set(gco, 'String', num2str(secUT));
    end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function output_txt = dataTipFormatFunc(obj,event_obj)
% Display the position of the data cursor
% obj          Currently not used (empty)
% event_obj    Handle to event object
% output_txt   Data cursor text string (string or cell array of strings).
    pos = get(event_obj,'Position');
    output_txt = {['X: ',num2str(pos(1),'%12.5f')],...
        ['Y: ',num2str(pos(2),'%12.5f')]};

    % If there is a Z-coordinate in the position, display it as well
    if length(pos) > 2
        output_txt{end+1} = ['Z: ',num2str(pos(3),'%12.5f')];
    end

% --- Executes on button press in markerLinesButton.
function markerLinesButton_Callback(hObject, eventdata, handles)
% hObject    handle to markerLinesButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    xLineValue = getappdata(handles.lvd_GraphicalAnalysisGUI,'xLineValue');
    yLineValue = getappdata(handles.lvd_GraphicalAnalysisGUI,'yLineValue');

    defAns = cell(1,2);
    if(~isempty(xLineValue))
        defAns{1} = num2str(xLineValue);
    else
        defAns{1} = '';
    end
    if(~isempty(yLineValue))
        defAns{2} = num2str(yLineValue);
    else
        defAns{2} = '';
    end

    answer = inputdlg({'Draw a vertical line at X=? (Blank to clear)';
                       'Draw a horizontal line at Y=? (Blank to clear)'},...
                       'Marker Lines',...
                        1,...
                        defAns);
	answer = strtrim(answer);
    if(isempty(answer))
        return;
    end

    newX = str2double(answer{1});
    if(isnan(newX))
        newXStr = [];
    else
        newXStr = newX;
    end

    newY = str2double(answer{2});
    if(isnan(newY))
        newYStr = [];
    else
        newYStr = newY;
    end

    setappdata(handles.lvd_GraphicalAnalysisGUI,'xLineValue',newXStr);
    setappdata(handles.lvd_GraphicalAnalysisGUI,'yLineValue',newYStr);

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

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

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

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

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

% --------------------------------------------------------------------
function setTimeFromScriptMenu_Callback(hObject, eventdata, handles)
% hObject    handle to setTimeFromScriptMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    lvdData = getappdata(handles.lvd_GraphicalAnalysisGUI,'lvdData');
    stateLog = lvdData.stateLog.getMAFormattedStateLogMatrix(false);

    h = gco;
    if(strcmpi(h.Tag,'startTimeText'))
        set(gco,'String', num2str(min(stateLog(:,1)), '%1.15f'));
    elseif(strcmpi(h.Tag,'endTimeText'))
        set(gco,'String', num2str(max(stateLog(:,1)), '%1.15f'));
    else
        return;
    end

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

% Hint: get(hObject,'Value') returns toggle state of useEvtLineColorsCheckbox
    if(hObject.Value)
        handles.lineColorCombo.Enable = 'off';
    else
        handles.lineColorCombo.Enable = 'on';
    end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function tapas_print_logo()
%% Print the logo of tapas.

%
% aponteeduardo@gmail.com
% copyright (C) 2017
%

disp( '_______            _____                _____       _____           ____                ');
disp( '   |              |     |              |_____|     |     |         |                    ');
disp( '   |              |-----|              |           |-----|          ----|               ');
disp(['   | RANSLATIONAL |     |LGORITHMS FOR |SYCHIATRY  |     |DVANCING  ____|CIENCE         ','']);
fprintf('\n');

end

author: translationalneuromodeling

repo: tapas


text:
classdef SetKinematicStateEPSrcState < matlab.mixin.SetGet
    %SetKinematicStateEPSrcState Summary of this class goes here
    %   Detailed explanation goes here

    properties
        src AbstractLaunchVehicleElectricalPowerSrcSnk

        srcStateToSet(1,1) logical = true;

        inheritSrcState(1,1) logical = true;
        inheritSrcStateFrom(1,1) InheritStateEnum = InheritStateEnum.InheritFromLastState;
        inheritSrcStateFromEvent LaunchVehicleEvent = LaunchVehicleEvent.empty(1,0);
    end

    methods
        function obj = SetKinematicStateEPSrcState(src)
            obj.src = src;
        end

        function updateStateLogEntry(obj, newStateLogEntry, stateLog)
            srcState = obj.getSrcState(newStateLogEntry);

            if(obj.inheritSrcState)
                if(obj.inheritSrcStateFrom == InheritStateEnum.InheritFromSpecifiedEvent && ...
                   not(isempty(obj.inheritSrcStateFromEvent)) && ...
                   not(isempty(obj.inheritSrcStateFromEvent.getEventNum())) && ...
                   obj.inheritSrcStateFromEvent.getEventNum() > 0)

                    evtStateLog = stateLog.getLastStateLogForEvent(obj.inheritSrcStateFromEvent);
                    if(not(isempty(evtStateLog)))
                        evtSrcState = obj.getSrcState(evtStateLog);
                        srcState.setActiveState(evtSrcState.getActiveState());
                    end
                end
            else
                srcState.setActiveState(obj.srcStateToSet);
            end
        end

        function listboxStr = getListboxStr(obj)
            listboxStr = {};
            for(i=1:length(obj))
                listboxStr{i} = obj(i).src.getName(); %#ok<AGROW>
            end
        end
    end

    methods(Access=private)
        function srcState = getSrcState(obj, stateLogEntry)
            srcStates = stateLogEntry.getAllPwrSrcsStates();
            srcState = srcStates(getEpsSrcComponent(srcStates) == obj.src);
        end
    end
end