text:
% Plot steady state objects
gSS = reshape(ggSS,I,2);
g_a = (lla(2) / (lla(1) + lla(2))) * gSS(:,1) ...
    + (lla(1) / (lla(1) + lla(2))) * gSS(:,2);

figure
hold on
f = bar(a / (wSS * (1 - ttau) * zAvg),g_a,'histc');
sh=findall(gcf,'marker','*'); delete(sh);
set(f,'FaceColor',[.03,.24,.8],'EdgeColor',[.8,.24,.03]);
xlim([min(a / (wSS * (1 - ttau) * zAvg)) .8*max(a / (wSS * (1 - ttau) * zAvg))])
xlabel('Net worth to average income','interpreter','latex')
ylabel('Mass of households','interpreter','latex')
title('Steady State Distribution of Assets','interpreter','latex','fontsize',14)
grid on
alpha(0.9)
set(gcf,'color','w')
hold off

% Plot steady state MPCs
tau_MPC = 1;
J = 2;
N_MPC = 21;
dt_MPC = tau_MPC / (N_MPC - 1);

C_stacked = zeros(I*J,N_MPC );
ctilde = zeros(I*J,1);
C_stacked(:,N_MPC) = 0;

B = (1/dt_MPC) * speye(I*J) - A;
c_stacked = reshape(cSS,I*J,1);

for n=N_MPC-1:-1:1
    vec = c_stacked + C_stacked(:,n+1)/dt_MPC;
    C_stacked(:,n) = B\vec;
end

C = reshape(C_stacked(:,1),I,J);
MPC = (C(2:I,:) - C(1:I-1,:)) ./ (aa(2:I,:) - aa(1:I-1,:));

figure
hold on
plot(a(2:I) / (wSS * (1 - ttau) * zAvg),MPC(:,1),'linewidth',1.5,'linestyle','-','color',[.03,.24,.8])
plot(a(2:I) / (wSS * (1 - ttau) * zAvg),MPC(:,2),'linewidth',1.5,'linestyle','-','color',[.8,.24,.03])
plot(a(2:I) / (wSS * (1 - ttau) * zAvg),ones(I-1,1)*MPC(.8*I-1,2),'linewidth',1.5,'linestyle','--','color','k')
xlim([min(a(2:I) / (wSS * (1 - ttau) * zAvg)) .8*max(a / (wSS * (1 - ttau) * zAvg))])
xlabel('Net worth to average income','interpreter','latex')
ylabel('MPC','interpreter','latex')
text(3,.05,'$\leftarrow z=0 $','Fontsize',20,'interpreter','latex','Color',[.8,.24,.03]);
text(1,0.25,'$\leftarrow z=1 $','Fontsize',20,'interpreter','latex','Color',[.03,.24,.8]);
set(gcf,'color','w')
title('MPCs in steady state','interpreter','latex','fontsize',14)
alpha(0.7)
grid on
hold off
drawnow

author: gregkaplan

repo: phact

save_path: github-repos/MATLAB/gregkaplan-phact


text:
function grad = getPartialGradient(problem, x, I, storedb, key)
% Computes the gradient of a subset of terms in the cost function at x.
%
% function grad = getPartialGradient(problem, x, I)
% function grad = getPartialGradient(problem, x, I, storedb)
% function grad = getPartialGradient(problem, x, I, storedb, key)
%
% Assume the cost function described in the problem structure is a sum of
% many terms, as
%
%    f(x) = sum_i f_i(x) for i = 1:d,

% where d is specified as d = problem.ncostterms.
%
% For a subset I of 1:d, getPartialGradient obtains the gradient of the
% partial cost function
%
%    f_I(x) = sum_i f_i(x) for i = I.
%
% storedb is a StoreDB object, key is the StoreDB key to point x.
%
% See also: getGradient canGetPartialGradient getPartialEuclideanGradient

% This file is part of Manopt: www.manopt.org.
% Original author: Nicolas Boumal, June 28, 2016
% Contributors:
% Change log:
%
%   Feb. 10, 2020 (NB):
%       Allowing M.egrad2rgrad to take (storedb, key) as extra inputs.

    % Allow omission of the key, and even of storedb.
    if ~exist('key', 'var')
        if ~exist('storedb', 'var')
            storedb = StoreDB();
        end
        key = storedb.getNewKey();
    end

    % Make sure I is a row vector, so that it is natural to loop over it
    % with " for i = I ".
    I = (I(:)).';

    if isfield(problem, 'partialgrad')
    %% Compute the partial gradient using partialgrad.

        % Check whether this function wants to deal with storedb or not.
        switch nargin(problem.partialgrad)
            case 2
                grad = problem.partialgrad(x, I);
            case 3
                % Obtain, pass along, and save the store for x.
                store = storedb.getWithShared(key);
                [grad, store] = problem.partialgrad(x, I, store);
                storedb.setWithShared(store, key);
            case 4
                % Pass along the whole storedb (by reference), with key.
                grad = problem.partialgrad(x, I, storedb, key);
            otherwise
                up = MException('manopt:getPartialGradient:badpartialgrad', ...
                    'partialgrad should accept 2, 3 or 4 inputs.');
                throw(up);
        end

    elseif canGetPartialEuclideanGradient(problem)
    %% Compute the partial gradient using the Euclidean partial gradient.

        egrad = getPartialEuclideanGradient(problem, x, I, storedb, key);
        % Convert to the Riemannian gradient
        switch nargin(problem.M.egrad2rgrad)
            case 2
                grad = problem.M.egrad2rgrad(x, egrad);
            case 4
                grad = problem.M.egrad2rgrad(x, egrad, storedb, key);
            otherwise
                up = MException('manopt:getPartialGradient:egrad2rgrad', ...
                    'egrad2rgrad should accept 2 or 4 inputs.');
                throw(up);
        end

    else
    %% Abandon computing the partial gradient.

        up = MException('manopt:getPartialGradient:fail', ...
            ['The problem description is not explicit enough to ' ...
             'compute the partial gradient of the cost.']);
        throw(up);

    end

end

author: NicolasBoumal

repo: manopt


text:
function [ sparserL , sparserA, sparserW ] = gsp_graph_sparsify_old(L,epsilon)
% The graph sparsification algorithm of D. A. Spielman and N. Srivastava,
% "Graph sparsification by effective resistances," SIAM J. Comput.,
% vol. 40, no. 6, pp. 1913-1926, 2011.

N=size(L,1);

% Epsilon should be between 1/sqrt(N) and 1, with a larger epsilon leading to a sparser graph
if ( (epsilon <= 1/sqrt(N)) || (epsilon >1) )
    error('Epsilon out of required range');
end

% Compute resistance distances, and check if the original graph is
% connected
resistance_distances = gsp_compute_resistance_distances_old(L);
W=diag(diag(L))-L;
W(W<1e-10)=0;
W=sparse(W);
original_connected=gsp_check_connectivity_undirected(W);
if (original_connected==0)
    warning('Original graph not connected before sparsification');
end

% Initialize the probability distribution that will be used to select edges in the sparsified graph
[start_nodes,end_nodes,weights] = find(tril(W));
weights=max(0,weights);
Re=max(0,resistance_distances(sub2ind(size(resistance_distances),start_nodes,end_nodes)));
Pe=weights.*Re;
Pe=Pe/sum(Pe);

max_tries=10; % maximum number of tries to get a connected graph

for ii=1:max_tries

    % Set Q
    C0=1/30; % Rudelson, 1996 Random Vectors in the Isotropic Position (too hard to figure out actual C0)
    C= 4*C0; % Rudelson and Vershynin, 2007, Thm. 3.1
    q=round(9*C^2*N*log(N)/(epsilon^2));

    % Choose random edges in the new graph according the probability
    % distribution initialized above
    results=gendist(Pe',q,1);
    spin_counts=hist(results,1:length(Pe'));
    per_spin_weights=weights./(q*Pe);

    % Tally the new weights and form the new graph
    new_weights=spin_counts'.*per_spin_weights;
    sparserW=sparse(start_nodes,end_nodes,new_weights,N,N);
    sparserW=sparserW+sparserW';
    sparserL=diag(sum(sparserW))-sparserW;
    sparserD=diag(diag(sparserL));
    sparserW=sparserD-sparserL;
    sparserA=sign(sparserW);

    % Check if new graph is connected. If not, reduce epsilon and try again
    new_graph_connected=gsp_check_connectivity_undirected(sparserA);
    if new_graph_connected
        break;
    elseif ii==max_tries
        warning('Despite attempts to reduce epsilon, sparsified graph is disconnected');
    else
        epsilon=epsilon-(epsilon-1/sqrt(N))/2;
    end
end

end

repo: gspbox


text:
function mpc = case9target
%CASE9TARGET    Target injection power flow data for 9 bus, 3 generator case.
%   Please see CASEFORMAT for details on the case file format.
%
%   Modified version of case9.m used as target for example CPF.

%   MATPOWER

%% MATPOWER Case Format : Version 2
mpc.version = '2';

%%-----  Power Flow Data  -----%%
%% system MVA base
mpc.baseMVA = 100;

%% bus data
%	bus_i	type	Pd	Qd	Gs	Bs	area	Vm	Va	baseKV	zone	Vmax	Vmin
mpc.bus = [
	1	3	0	0	0	0	1	1	0	345	1	1.1	0.9;
	2	2	0	0	0	0	1	1	0	345	1	1.1	0.9;
	3	2	0	0	0	0	1	1	0	345	1	1.1	0.9;
	4	1	0	0	0	0	1	1	0	345	1	1.1	0.9;
	5	1	305.4	123.15	0	0	1	1	0	345	1	1.1	0.9;
	6	1	0	0	0	0	1	1	0	345	1	1.1	0.9;
	7	1	214.11	71.09	0	0	1	1	0	345	1	1.1	0.9;
	8	1	0	0	0	0	1	1	0	345	1	1.1	0.9;
	9	1	235.61	81.44	0	0	1	1	0	345	1	1.1	0.9;
];

%% generator data
%	bus	Pg	Qg	Qmax	Qmin	Vg	mBase	status	Pmax	Pmin	Pc1	Pc2	Qc1min	Qc1max	Qc2min	Qc2max	ramp_agc	ramp_10	ramp_30	ramp_q	apf
mpc.gen = [
	1	72.3	27.03	300	-300	1.04	100	1	250	10	0	0	0	0	0	0	0	0	0	0	0;
	2	248	0	300	-300	1.025	100	1	300	10	0	0	0	0	0	0	0	0	0	0	0;
	3	124.59	0	300	-300	1.025	100	1	270	10	0	0	0	0	0	0	0	0	0	0	0;
];

%% branch data
%	fbus	tbus	r	x	b	rateA	rateB	rateC	ratio	angle	status	angmin	angmax
mpc.branch = [
	1	4	0	0.0576	0	250	250	250	0	0	1	-360	360;
	4	5	0.017	0.092	0.158	250	250	250	0	0	1	-360	360;
	5	6	0.039	0.17	0.358	150	150	150	0	0	1	-360	360;
	3	6	0	0.0586	0	300	300	300	0	0	1	-360	360;
	6	7	0.0119	0.1008	0.209	150	150	150	0	0	1	-360	360;
	7	8	0.0085	0.072	0.149	250	250	250	0	0	1	-360	360;
	8	2	0	0.0625	0	250	250	250	0	0	1	-360	360;
	8	9	0.032	0.161	0.306	250	250	250	0	0	1	-360	360;
	9	4	0.01	0.085	0.176	250	250	250	0	0	1	-360	360;
];

%%-----  OPF Data  -----%%
%% generator cost data
%	1	startup	shutdown	n	x1	y1	...	xn	yn
%	2	startup	shutdown	n	c(n-1)	...	c0
mpc.gencost = [
	2	1500	0	3	0.11	5	150;
	2	2000	0	3	0.085	1.2	600;
	2	3000	0	3	0.1225	1	335;
];

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function threshold = getAdaptiveThreshold(prob_map, obj_coords, cfg)
%GETADAPTIVETHRESHOLD Returns the threshold to separate foreground from
%background/surroundings based on cumulative histograms
% Parameters:
%   prob_map   [MxNx1] probability map
%   obj_coords Object rectangle defined as a 4 element vector: [x,y,w,h]
%   cfg        DAT configuration

% Object region
obj_prob_map = imcrop(prob_map, obj_coords);
H_obj =  hist(obj_prob_map(:), cfg.adapt_thresh_prob_bins);
H_obj = H_obj./sum(H_obj);
cum_H_obj = cumsum(H_obj);

% Surroundings
H_dist = hist(prob_map(:), cfg.adapt_thresh_prob_bins);
% Remove object information
H_dist = H_dist - H_obj;
H_dist = H_dist./sum(H_dist);
cum_H_dist = cumsum(H_dist);

k = zeros(size(cum_H_obj));
for i = 1:length(k)-1, k(i) = cum_H_obj(i+1) - cum_H_obj(i); end
x = abs(cum_H_obj - (1 - cum_H_dist)) + (cum_H_obj < 1 - cum_H_dist) + (1 - k);
[~,i] = min(x);
%Final threshold result should lie between 0.4 and 0.7 to be not too restrictive
threshold = max(.4,min(.7, cfg.adapt_thresh_prob_bins(i)));

author: flyers

repo: drone-tracking


text:
classdef MimLocalModelCache < CoreBaseClass

    properties (Access = private)
        Controller
        ModelDictionary
    end

    methods
        function obj = MimLocalModelCache(controller)
            obj.Controller = controller;
            obj.ModelDictionary = containers.Map;
        end

        function entry = getModelCacheEntry(obj, modelName)
            if ~obj.ModelDictionary.isKey(modelName)
                obj.ModelDictionary(modelName) = MimLocalModelCacheEntry([], [], obj.Controller, modelName);
            end
            entry = obj.ModelDictionary(modelName);
        end

        function clear(obj)
            obj.ModelDictionary = containers.Map();
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
import spx.cluster.ssc.OMP_REPR_METHOD;
import spx.cluster.ssc.SSC_OMP;

method = OMP_REPR_METHOD.CLASSIC_OMP_C;
method = OMP_REPR_METHOD.FLIPPED_OMP_MATLAB;
method = OMP_REPR_METHOD.BATCH_FLIPPED_OMP_MATLAB;
method = OMP_REPR_METHOD.BATCH_FLIPPED_OMP_C;
method = OMP_REPR_METHOD.BATCH_OMP_C;

% maximum dimension for each subspace
D = 10;
% Number of dimensions to which the digits data should be
% approximated.
pca_dim = 500;
% preparation of dataset
digit_set = 0:9;
% Number of subspaces
K = length(digit_set);
rnorm_thr  = 1e-3;
if ~exist('md')
    fprintf('MNIST dataset has not been loaded.\n');
    md = spx.data.image.ChongMNISTDigits;
end
num_samples_per_digit = 50;
cluster_sizes = num_samples_per_digit*ones(1, K);
% total number of samples
S = sum(cluster_sizes);
% identify sample indices for each digit
sample_list = [];
for k=1:K
    digit = digit_set(k);
    digit_indices = md.digit_indices(digit);
    num_digit_samples = length(digit_indices);
    % initialize the random number generator for repeatability
    rng(k);
    choices = randperm(num_digit_samples, cluster_sizes(k));
    selected_indices = digit_indices(choices);
    sample_list = [sample_list selected_indices];
end
[Y, true_labels] = md.selected_samples(sample_list);
% Perform PCA to reduce dimensionality
Y = spx.la.pca.low_rank_approx(Y, pca_dim);
%% Perform SSC-OMP using first method.
rng default;
tstart = tic;
solver = SSC_OMP(Y, D, K, rnorm_thr, method);
result = solver.solve();
total = toc(tstart);
fprintf('time: %.2f seconds\n', total);
labels = result.Labels;
% time to compute representations
repr = result.representation_time;
%% Time to compare the clustering
comparer = spx.cluster.ClusterComparison(true_labels+1, labels);
comparison_result = comparer.fMeasure();
comparer.printF1MeasureResult(comparison_result);

author: indigits

repo: sparse-plex


text:
function vl_test_imintegral

I = ones(5,6);

correct = [1     2     3     4     5     6;
           2     4     6     8    10    12;
           3     6     9    12    15    18;
           4     8    12    16    20    24;
           5    10    15    20    25    30;];

if ~all(all(slow_imintegral(I) == correct))
    fprintf('test_imintegral: FAIL slow ones test\n');
    keyboard;
end

if ~all(all(vl_imintegral(I) == correct))
    fprintf('test_imintegral: FAIL ones test\n');
    keyboard;
end

I = repmat(ones(5,6), [1 1 3]);
integral = vl_imintegral(I);
if ~all(all(all(integral == repmat(correct,[1 1 3]))))
    fprintf('test_imintegral: FAIL multidimensional ones test\n');
    keyboard;
end

ntest = 50;
for i = 1:ntest
    I = rand(5);
    integral = vl_imintegral(I);
    slow_integral = slow_imintegral(I);
    err = abs(integral - slow_integral);
    if max(err(:)) > 0.00001
        fprintf('test_imintegral: FAIL random test\n');
        keyboard;
    end
end

fprintf('test_imintegral: passed.\n');

% The slow but obvious way
function integral = slow_imintegral(I)
integral = zeros(size(I));
for k = 1:size(I,3)
    for r = 1:size(I,1)
        for c = 1:size(I,2)
            integral(r,c,k) = sum(sum(I(1:r,1:c,k)));
        end
    end
end

author: jianxiongxiao

repo: ProfXkit


text:
function [a b c] = parseThreePoints(varargin)
%PARSETHREEPOINTS Parse three points from variable length input array
%
%   [A B C] = parseThreePoints(PTS);
%   [A B C] = parseThreePoints(P1, P2, P3);
%   [A B C] = parseThreePoints(VERTICES, INDS);
%
%   Example
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-12-09,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

% extract input args
if nargin == 1
    % inputs are 3 points packed into a 3-by-2 array
    var = varargin{1};
    a = var(1,:);
    b = var(2,:);
    c = var(3,:);

elseif nargin == 3
    % inputs are 3 separate points
    a = varargin{1};
    b = varargin{2};
    c = varargin{3};

elseif nargin == 2
    % inputs are a vertex array, and index array
    pts = varargin{1};
    inds = varargin{2};
    a = pts(inds(1), :);
    b = pts(inds(2), :);
    c = pts(inds(3), :);
end

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
function prob_test130 ( )

%*****************************************************************************80
%
%% TEST130 tests POWER_MEAN, POWER_SAMPLE, POWER_VARIANCE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  nsample = 1000;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST130\n' );
  fprintf ( 1, '  For the Power PDF:\n' );
  fprintf ( 1, '  POWER_MEAN computes the mean;\n' );
  fprintf ( 1, '  POWER_SAMPLE samples;\n' );
  fprintf ( 1, '  POWER_VARIANCE computes the variance.\n' );

  a = 2.0;
  b = 3.0;

  check = power_check ( a, b );

  if ( ~check );
    fprintf ( 1, '\n' );
    fprintf ( 1, 'TEST130 - Fatal error!\n' );
    fprintf ( 1, '  The parameters are not legal.\n' );
    return
  end

  mean = power_mean ( a, b );
  variance = power_variance ( a, b );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  PDF parameter A =             %14f\n', a );
  fprintf ( 1, '  PDF parameter B =             %14f\n', b );
  fprintf ( 1, '  PDF mean =                    %14f\n', mean );
  fprintf ( 1, '  PDF variance =                %14f\n', variance );

  for i = 1 : nsample
    [ x(i), seed ] = power_sample ( a, b, seed );
  end

  mean = r8vec_mean ( nsample, x );
  variance = r8vec_variance ( nsample, x );
  xmax = max ( x(1:nsample) );
  xmin = min ( x(1:nsample) );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Sample size =     %6d\n', nsample );
  fprintf ( 1, '  Sample mean =     %14f\n', mean );
  fprintf ( 1, '  Sample variance = %14f\n', variance );
  fprintf ( 1, '  Sample maximum =  %14f\n', xmax );
  fprintf ( 1, '  Sample minimum =  %14f\n', xmin );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function MB = storage(x)
% return size of doubles matrix of size x in megabytes

MB= prod(x)*8/1024/1024;

end

author: karpathy

repo: Random-Forest-Matlab


text:
function c8_log_test ( )

%*****************************************************************************80
%
%% C8_LOG_TEST tests C8_LOG.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 February 2015
%
%  Author:
%
%    John Burkardt
%
  seed = 123456678;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'C8_LOG_TEST\n' );
  fprintf ( 1, '  C8_LOG computes the logarithm of a C8.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, ...
    '       C1=C8_UNIFORM_01          C2=C8_LOG(C1)             C3=C8_EXP(C2))\n' );
  fprintf ( 1, '     ---------------------     ---------------------     ---------------------\n' );
  fprintf ( 1, '\n' );

  for test = 1 : 10

    [ c1, seed ] = c8_uniform_01 ( seed );
    c2 = c8_log ( c1 );
    c3 = c8_exp ( c2 );

    fprintf ( 1, '  (%12f  %12f)  (%12f  %12f)  (%12f  %12f)\n', ...
      real ( c1 ), imag ( c1 ), real ( c2 ), imag ( c2 ), real ( c3 ), imag ( c3 ) );

  end

  return
end


text:
function p06_limit_test ( option )

%*****************************************************************************80
%
%% P06_LIMIT_TEST seeks limit points for problem 6.
%
%  Discussion:
%
%    We want to find points X such that TAN(7) = 0.
%
%    The number of limit points that may be expected depends on the option:
%
%    There are five options, which vary in the value they fix the
%    elevator value X(6):
%
%      Option   Elevator Value    Limit Points
%
%       1        -0.050              1
%       2        -0.008              3
%       3         0.0                2
%       4         0.05               1
%       5         0.1                1
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 October 2008
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Raman Mehra, William Kessel, James Carroll,
%    Global stability and contral analysis of aircraft at high angles of attack,
%    Technical Report CR-215-248-1, -2, -3,
%    Office of Naval Research, June 1977.
%
%    Rami Melhem, Werner Rheinboldt,
%    A Comparison of Methods for Determining Turning Points of Nonlinear Equations,
%    Computing,
%    Volume 29, Number 3, September 1982, pages 201-226.
%
%    Albert Schy, Margery Hannah,
%    Prediction of Jump Phenomena in Roll-coupled Maneuvers of Airplanes,
%    Journal of Aircraft,
%    Volume 14, Number 4, 1977,  pages 375-382.
%
%    John Young, Albert Schy, Katherine Johnson,,
%    Prediction of Jump Phenomena in Aircraft Maneuvers, Including
%    Nonlinear Aerodynamic Effects,
%    Journal of Guidance and Control,
%    Volume 1, Number 1, 1978, pages 26-31.
%
%  Parameters:
%
%    Input, integer OPTION, the option index.
%    1, X(6) fixed at -0.050, X(7) free, X(8) fixed at 0.0;
%    2, X(6) fixed at -0.008, X(7) free, X(8) fixed at 0.0;
%    3, X(6) fixed at  0.000, X(7) free, X(8) fixed at 0.0;
%    4, X(6) fixed at  0.050, X(7) free, X(8) fixed at 0.0;
%    5, X(6) fixed at  0.100, X(7) free, X(8) fixed at 0.0.
%
  problem = 6;
  lim = 7;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'P06_LIMIT_TEST\n' );
  fprintf ( 1, '  Compute a series of solutions for problem 6.\n' );
  fprintf ( 1, '  We are trying to find limit points X such that\n' );
  fprintf ( 1, '  TAN(%d) = 0.\n', lim );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The option chosen is %d\n', option );
  fprintf ( 1, '\n' );
  fprintf ( 1, '   #   Tan(7)     X1       X2       X3       X4       X5       X6       X7      X8\n' );
  fprintf ( 1, '                Roll     Pitch    Yaw      Attack   Sideslip Elevator Aileron Rudder\n' );
  fprintf ( 1, '\n' );
%
%  Get problem size.
%
  nvar = p00_nvar ( problem, option );

  lim_num = 0;
%
%  Get starting point.
%
  x2 = p00_start ( problem, option, nvar );
%
%  Get the tangent vector.
%
  tan2 = p00_tan ( problem, option, nvar, x2 );
%
%  For correction of initial point, use variable index 7.
%
  par_index = 7;
%
%  Force F(X) = 0.
%
  step = -1;
  fprintf ( 1, '  %2d %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\n', ...
    step, tan2(lim), x2(1:nvar) );

  [ x2, status ] = p00_newton ( problem, option, nvar, x2, par_index );

  if ( status < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Newton iteration failed on starting point.\n' );
    return
  end

  tan2 = p00_tan ( problem, option, nvar, x2 );

  step = 0;
  fprintf ( 1, '  %2d %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\n', ...
    step, tan2(lim), x2(1:nvar) );
%
%  Get stepsize.
%
  [ h, hmin, hmax ] = p00_stepsize ( problem, option );
%
%  LOOP:
%
  step_max = 30;

  for step = 1 : step_max
%
%  Save old data as X1, TAN1.
%
    x1 = x2;
    tan1 = tan2;

    h_reduction = 0;
%
%  Use X1 + H * TAN1 as a starting estimate for Newton iteration.
%
    while ( 1 )

      if ( hmax < abs ( h ) )
        h = hmax * r8_sign ( h );
      end

      if ( abs ( h ) < hmin )
        h = hmin * r8_sign ( h );
      end

      x2 = x1 + h * tan1;

      par_index = 0;
      [ x2, status ] = p00_newton ( problem, option, nvar, x2, par_index );
%
%  If we didn't get it, can we try again?
%
      if ( status < 0 )

        if ( abs ( h ) <= hmin )
          fprintf ( 1, '\n' );
          fprintf ( 1, '  Cannot decrease stepsize any more.\n' );
          fprintf ( 1, '  Cannot complete the computation.\n' );
          return
        else
          h = h / 4.0;
          h_reduction = h_reduction + 1;
        end
%
%  We computed the point.
%  Should we change the stepsize?
%
      else

        if ( h_reduction == 0 )

          if ( status <= 1 )
            h = h * 4.0;
          elseif ( status <= 3 )
            h = h * 2.0;
          elseif ( 12 <= status )
            h = h / 4.0;
          elseif ( 8 <= status )
            h = h / 2.0;
          end

        end

        break;

      end

    end
%
%  Compute the tangent vector.
%
    tan2 = p00_tan ( problem, option, nvar, x2 );
%
%  Check for a limit point.
%
    if ( tan1(lim) * tan2(lim) <= 0.0 )
      [ x, tan, status ] = p00_limit ( problem, option, nvar, x1, tan1, x2, tan2, lim );
      fprintf ( 1, '   L %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\n', ...
        tan(lim), x(1:nvar) );
      lim_num = lim_num + 1;
    end

    fprintf ( 1, '  %2d %8.1e %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f\n', ...
      step, tan2(lim), x2(1:nvar) );

    if ( step == step_max )
      break
    end

  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of limit points found was %d\n', lim_num );

  return
end


text:
function dat = interpolate(dat, varargin)
% Interpolate over missing values in image_vector object
%
% :Usage:
% ::
%
%    dat = interpolate(dat, varargin)
%
% :Input:
%    image_vector object (dat; e.g., an fmri_data object)
%
% Use when there are some missing values in the mask image
% Performs 3-D linear interpolation to fill in all values in the original
% mask.
%
% e.g., For a standard brain image space that is 91 x 109 x 91, you may
% have 300,000 in-mask values. Only 150,000 of these may be defined in the
% image, however, and the rest are missing (0 or NaN).
% This function will return a dat image with non-missing values for all
% 300,000 voxels (the "in-mask" space).
% It will not return values for all voxels in the 91 x 109 x 91 space,
% however.
%
% :Note:
% This function does not upsample the data now, but could be extended
% to do so fairly easily.
%

upsamplevalue = 1; % values > 1 would upsample the data

SPACE = define_sampling_space(dat.volInfo, upsamplevalue);

% voldata = reconstruct_image(dat);
% voldata(voldata(:) == 0 | isnan(voldata(:))) = 0;

xyzfull = dat.volInfo.xyzlist;

dat = remove_empty(dat);
wh = ~dat.removed_voxels;
x = xyzfull(wh, 1);
y = xyzfull(wh, 2);
z = xyzfull(wh, 3);

% interpolation of scattered data
% note: y and x are reversed in some Matlab functions, such as this one - OK
Vq = griddata(y, x, z, double(dat.dat),  SPACE.X, SPACE.Y, SPACE.Z, 'linear');

datnew = Vq(:);
datnew = datnew(dat.volInfo.wh_inmask);

dat.dat = datnew;
dat.removed_voxels = false;

if upsamplevalue > 1
    % Need to re-create image space and dims from scratch
    % up-sample mask as well

end

end % function

% view
%slice(SPACE.X, SPACE.Y, SPACE.Z, Vq,[6 30 60],2,[10 40 70]), shading flat

% resampled_dat = interp3(x, y, z, dat.dat, SPACE.X, SPACE.Y, SPACE.Z);
% resampled_dat = interp3(SPACE.Xo, SPACE.Yo, SPACE.Zo, voldata, SPACE.X, SPACE.Y, SPACE.Z);

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function [source_features,target_features] = SURF2(I1,I2)

    [H, W, ~] = size(I1);
    grayI1 = rgb2gray(I1);
    grayI2 = rgb2gray(I2);

%     [f1, vpts1] = getSURFFeatures(grayI1);
%     [f2, vpts2] = getSURFFeatures(grayI2);
    threshold = 10;
    points1 = detectSURFFeatures(grayI1, 'MetricThreshold', threshold);
    points2 = detectSURFFeatures(grayI2, 'MetricThreshold', threshold);
    [f1, vpts1] = extractFeatures(grayI1, points1);
    [f2, vpts2] = extractFeatures(grayI2, points2);

    index_pairs = matchFeatures(f1, f2) ;
    matched_pts1 = vpts1(index_pairs(:, 1), :);
    matched_pts2 = vpts2(index_pairs(:, 2), :);

    [n,~] = size(matched_pts1);

    source_features = zeros(n,2);
    target_features = zeros(n,2);

    for i=1:n
        source_features(i,:) = matched_pts1(i, :).Location;
        target_features(i,:) = matched_pts2(i, :).Location;
    end

    valid = source_features(:, 1) > 0 & source_features(:, 2) > 0 ...
        & source_features(:, 1) < W & source_features(:, 2) < H ...
        & target_features(:, 1) > 0 & target_features(:, 2) > 0 ...
        & target_features(:, 1) < W & target_features(:, 2) < H;
    source_features = source_features(valid, :);
    target_features = target_features(valid, :);
%     source_features = matched_pts1;
%     target_features = matched_pts2;
end

function [f, vpts] = getSURFFeatures(I)
    meshSize = 1;
    threshold = 100;
    [H, W] = size(I);
    f = [];
    vpts = [];
    for row = 1:meshSize
        for col = 1:meshSize
            nMore = 1000;
            roi = [1 + (col - 1) * W / meshSize, 1 + (row - 1) * H / meshSize, W / meshSize, H / meshSize];
            pNew = detectSURFFeatures(I, 'ROI', roi, 'MetricThreshold', threshold);
            while (size(pNew, 1) < nMore) && threshold > 10
                threshold = threshold - 10;
                pNew = detectSURFFeatures(I, 'ROI', roi, 'MetricThreshold', threshold);
            end
            while nMore * 2 < size(pNew, 1) && threshold < 200
                threshold = threshold + 20;
                pNew = detectSURFFeatures(I, 'ROI', roi, 'MetricThreshold', threshold);
            end
            if nMore < size(pNew, 1)
                ordering = randperm(length(pNew));
                pNew = pNew(ordering);
                pNew = pNew(1:nMore);
            end
            [fNew, vptsNew] = extractFeatures(I, pNew);
            f = cat(1, f, fNew);
            vpts = cat(1, vpts, vptsNew.Location);
        end
    end
end

author: SuTanTank

repo: VideoStitchingViaShakinessRemoving


text:
function writeMSH(filename,V,T,F)
  % WRITEMSH  write a tet mesh to gmsh's .msh file format
  %
  % writeMSH(filename,V,T,F)
  %
  % Inputs:
  %   V  #V by dim=3 list of vertex positions
  %   T  #T by 4 list of tet indices
  %   F  #F by 3 list of triangle indices

  %disp(['writing: ',filename]);
  fp = fopen(filename,'w');
  % Write header
  fprintf(fp,'$MeshFormat\n');
  % http://www.manpagez.com/info/gmsh/gmsh-2.2.2/gmsh_63.php
  fprintf(fp,'%d %d %d\n',2,0,8);
  fprintf(fp,'$EndMeshFormat\n');
  % write nodes
  fprintf(fp,'$Nodes\n');
  fprintf(fp,'%d\n',size(V,1));
  fprintf(fp,'%d %0.17g %0.17g %0.17g\n',[1:size(V,1);V']);
  fprintf(fp,'$EndNodes\n');
  % write elements
  fprintf(fp,'$Elements\n');
  fprintf(fp,'%d\n',size(T,1)+size(F,1));
  % write tets
  if ~isempty(T)
    fprintf(fp,'%d 4 2 0 1 %d %d %d %d\n',[1:size(T,1);T']);
  end
  if ~isempty(F)
    fprintf(fp,'%d 2 2 0 1 %d %d %d\n',[size(T,1)+(1:size(F,1));F']);
  end
  fprintf(fp,'$EndElements\n');
  fclose(fp);
end

author: alecjacobson

repo: gptoolbox


text:
function sig = fix_length(sig,N)
%FIX_LENGTH pads zeros or removes entries from signal accroding to length N
%
%   Usage: sig = fix_length(sig,N)
%
%   Input parameters:
%       sig - input signal (matrix with sigs as columns)
%       N   - number of samples size(sig,1) should be
%
%   Output paramteres:
%       sig - corrected sig
%
%   FIX_LENGTH(sig,N) pads zeros or removes the end of the given signal in
%   order to have a sig with a size(sig,1)==N.
%
%   see also: fix_irs_length, convolution

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

%% ===== Checking of input  parameters ==================================
nargmin = 2;
nargmax = 2;
narginchk(nargmin,nargmax);

%% ===== Fix IR ==========================================================
% Length of IR
samples = size(sig,1);
channels = size(sig,2);

if samples<N
    % Append zeros if to short
    sig = [sig; zeros(N-samples,channels)];
else
    % Remove the end of the IR, if to long
    sig = sig(1:N,:);
end

author: sfstoolbox

repo: sfs-matlab


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% vertex.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [n0,x,y,x1,x2,f1,f2] = vertex(j,n,u,v,v1,x0,f0,ipar,isplit,
% ichild,z,f,l,L)
% computes the base vertex x and the opposite vertex y of the box # j
% of MCS and the 'neighboring vertices' x1 and x2 and their function
% values f1 and f2 needed for separable quadratic interpolation
% Input:
% j       label of the box whose vertices etc. are to be computed
%         (in the main program mcs.m)
% n       dimension of the problem
% [u,v]   original box
% v1      opposite vertex of the original box
% x0(1:n,1:max(L)) coordinates used in the initialization list
%         x^0 = (x0(1,l(1)),...,x0(n,l(n)) base vertex of the original
%	  box
% f0(1:max(L),1:n) function values appertaining to the initialization
%	  list
%         f0(m,i) is the function value at x = (x0(1,istar(1)),...,
%         x0(i-1,istar(i-1)),x0(i,m),x0(i+1,l(i+1)),...,x0(n,l(n)))
% f0(1:max(L),m), m > n  function values appertaining to a later box
%         split according to the initialization list
% ipar(m) label of the parent of box m
% isplit(m) = -(splitting index) of box m  if it is split in the
%             initialization procedure
%           = splitting index of box m  otherwise
% ichild(m) = -(number which child box m is)  if box m was generated
%             by splitting according to the initialization list (in
%             the initialization procedure or later)
%           = number which child box m is  otherwise
% z(1:2,:)  z(1,m) = value of the isplit(m)th coordinate of the base
%           vertex of box m
%           z(2,m) = k  if box m is split according to the
%                       initialization list and f0(:,k) contains the
%                       function values obtained by splitting the box
%           z(2,m) = splitting value of box m  otherwise
% f(1:2,:)  f(1,m) = function value at the base vertex of box m
%           f(2,m) = function value at the splitting point of box m
%                    (if z(2,m) ~= Inf)
% l(1:n)  pointer defining the initial base vertex x^0 (see above)
% L(1:n)  the init. list contains L(i) values for coordinate i
% Output:
% n0(1:n)  n0(i) indicates that the ith coordinate has been split n0(i)
%          times in the history of box j
% x(1:n)   base vertex of box j
% y(1:n)   opposite vertex of box j
% x1(1:n), x2(1:n), f1(1:n), f2(1:n)
%          x1(i) and x2(i) and the corresponding function values f1(i)
%          and f2(i) are used for quadratic interpolation in the ith
%          coordinate
% Since it is not always possible to find for each i two vertices that
% differ from x only in coordinate i, we have to generate 'fictitious'
% vertices and function values using the assumption that the function
% is separable
% Uses the following functions/m-files:
% updtf.m
% vert1.m
% vert2.m
% vert3.m

function [n0,x,y,x1,x2,f1,f2] = vertex(j,n,u,v,v1,x0,f0,ipar,isplit,ichild,z,f,l,L)
% initialization
% The coordinates of x, y, x1 and x2 are initially set to Inf to
% indicate that these quantities haven't been found yet in the course of
% pursuing the history of box j
x = Inf*ones(n,1);
y = Inf*ones(n,1);
x1 = Inf*ones(n,1);
x2 = Inf*ones(n,1);
f1 = zeros(n,1);
f2 = zeros(n,1);
n0 = zeros(n,1);
fold = f(1,j);
m = j;
while m > 1
  i = abs(isplit(ipar(m)));
  n0(i) = n0(i) + 1;
  if ichild(m) == 1
    if x(i) == Inf | x(i) == z(1,ipar(m))
      [x(i),x1(i),x2(i),f1(i),f2(i)] = vert1(2,z(:,ipar(m)),f(:,ipar(m)),x1(i),x2(i),f1(i),f2(i));
    else
      [f1,f2,fold] = updtf(n,i,x1,x2,f1,f2,fold,f(1,ipar(m)));
      [x1(i),x2(i),f1(i),f2(i)] = vert2(1,x(i),z(:,ipar(m)),f(:,ipar(m)),x1(i),x2(i),f1(i),f2(i));
    end
  elseif ichild(m) >= 2
    [f1,f2,fold] = updtf(n,i,x1,x2,f1,f2,fold,f(1,ipar(m)));
    if x(i) == Inf | x(i) == z(2,ipar(m))
      [x(i),x1(i),x2(i),f1(i),f2(i)] = vert1(1,z(:,ipar(m)),f(:,ipar(m)),x1(i),x2(i),f1(i),f2(i));
    else
      [x1(i),x2(i),f1(i),f2(i)] = vert2(2,x(i),z(:,ipar(m)),f(:,ipar(m)),x1(i),x2(i),f1(i),f2(i));
    end
  end
  if 1 <= ichild(m) & ichild(m) <= 2 & y(i) == Inf
    y(i) = split1(z(1,ipar(m)),z(2,ipar(m)),f(1,ipar(m)),f(2,ipar(m)));
  end
  if ichild(m) < 0
    % box m was generated by splitting according to the init. list
    % x0(i,j1) = ith coordinate of the base vertex of box m
    % the ith coordinate of the opposite vertex is the golden section
    % split of x0(i,j2) and x0(i,j2+1) for 1 <= j2 <= L(i) - 1, it is
    % u(i) for j1 = 1 and v(i) for j2 = L(i)
    % x0(i,j1+j3) = ith coordinate of the 'neighboring vertex'
    if u(i) < x0(i,1)
      j1 = ceil(abs(ichild(m))/2);
      j2 = floor(abs(ichild(m))/2);
      if (abs(ichild(m))/2 < j1  & j1 > 1) | j1 == L(i)
        j3 = -1;
      else
        j3 = 1;
      end
    else
      j1 = floor(abs(ichild(m))/2) + 1;
      j2 = ceil(abs(ichild(m))/2);
      if abs(ichild(m))/2 + 1 > j1 & j1 < L(i)
        j3 = 1;
      else
        j3 = -1;
      end
    end
    if isplit(ipar(m)) < 0 % box m was generated in the init. procedure
      k = i;
    else
      k = z(2,ipar(m));
      % box m was generated by a later split according to the init.
      % list; k points to the corresponding function values
    end
    if j1 ~= l(i) | (x(i) ~= Inf & x(i) ~= x0(i,l(i)))
      [f1,f2,fold] = updtf(n,i,x1,x2,f1,f2,fold,f0(l(i),k));
    end
    if x(i) == Inf | x(i) == x0(i,j1)
      x(i) = x0(i,j1);
      if x1(i) == Inf
        [x1(i),x2(i),f1(i),f2(i)] = vert3(j1,x0(i,:),f0(:,k),L(i),x1(i),x2(i),f1(i),f2(i));
      elseif x2(i) == Inf & x1(i) ~= x0(i,j1+j3)
        x2(i) = x0(i,j1+j3);
        f2(i) = f2(i) + f0(j1+j3,k);
      elseif x2(i) == Inf
        if j1 ~= 1 & j1 ~= L(i)
          x2(i) = x0(i,j1-j3);
          f2(i) = f2(i) + f0(j1-j3,k);
        else
          x2(i) = x0(i,j1+2*j3);
          f2(i) = f2(i) + f0(j1+2*j3,k);
        end
      end
    else
      if x1(i) == Inf
        x1(i) = x0(i,j1);
        f1(i) = f1(i) + f0(j1,k);
        if x(i) ~= x0(i,j1+j3)
          x2(i) = x0(i,j1+j3);
          f2(i) = f2(i) + f0(j1+j3,k);
        end
      elseif x2(i) == Inf
        if x1(i) ~= x0(i,j1)
          x2(i) = x0(i,j1);
          f2(i) = f2(i) + f0(j1,k);
        elseif x(i) ~= x0(i,j1+j3)
          x2(i) = x0(i,j1+j3);
          f2(i) = f2(i) + f0(j1+j3,k);
        else
          if j1 ~= 1 & j1 ~= L(i)
            x2(i) = x0(i,j1-j3);
            f2(i) = f2(i) + f0(j1-j3,k);
          else
            x2(i) = x0(i,j1+2*j3);
            f2(i) = f2(i) + f0(j1+2*j3,k);
          end
        end
      end
    end
    if y(i) == Inf
      if j2 == 0
        y(i) = u(i);
      elseif j2 == L(i)
        y(i) = v(i);
      else
        y(i) = split1(x0(i,j2),x0(i,j2+1),f0(j2,k),f0(j2+1,k));
      end
    end
  end
  m = ipar(m);
end
for i = 1:n
  if x(i) == Inf
    x(i) = x0(i,l(i));
    [x1(i),x2(i),f1(i),f2(i)] = vert3(l(i),x0(i,:),f0(:,i),L(i),x1(i),x2(i),f1(i),f2(i));
  end
  if y(i) == Inf
     y(i) = v1(i);
  end
end

author: lacerbi

repo: optimviz

save_path: github-repos/MATLAB/lacerbi-optimviz


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

    % Last Modified by GUIDE v2.5 19-Jul-2020 08:59:13

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

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

    grndObjs = varargin{1};
    setappdata(hObject,'grndObjs',grndObjs);

    handles = populateGUI(grndObjs, handles);

    % Update handles structure
    guidata(hObject, handles);

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

function handles = populateGUI(grndObjs, handles)
    listboxStr = grndObjs.getListboxStr();
    handles.groundObjListbox.String = listboxStr;

    if(length(listboxStr) >= 1)
        handles.groundObjListbox.Value = 1;
    end

    celBodyData = grndObjs.lvdData.celBodyData;
    populateBodiesCombo(celBodyData, handles.celestialBodyCombo);

    grndObj = getSelectedGroundObj(handles);
    updateGuiForGroundObj(grndObj, handles);

function updateGuiForGroundObj(grndObj, handles)
    if(not(isempty(grndObj)))
        grndObjs = getappdata(handles.lvd_EditGroundObjectsGUI,'grndObjs');
        celBodyData = grndObjs.lvdData.celBodyData;

        handles.groundObjectNameText.String = grndObj.name;
        handles.groundObjDescText.String = grndObj.desc;

        [~, sortedBodyInfo] = ma_getSortedBodyNames(celBodyData);
        sortedBodyInfo = [sortedBodyInfo{:}];

        ind = find(grndObj.centralBodyInfo == sortedBodyInfo,1,'first');
        handles.celestialBodyCombo.Value = ind;

        handles.groundObjColorCombo.String = ColorSpecEnum.getListboxStr();
        handles.groundObjColorCombo.Value = ColorSpecEnum.getIndForName(grndObj.markerColor.name);

        handles.groundObjMarkerShapeCombo.String = MarkerStyleEnum.getListboxStr();
        handles.groundObjMarkerShapeCombo.Value = MarkerStyleEnum.getIndForName(grndObj.markerShape.name);

        handles.groundObjLineColorCombo.String = ColorSpecEnum.getListboxStr();
        handles.groundObjLineColorCombo.Value = ColorSpecEnum.getIndForName(grndObj.grdTrkLineColor.name);

        handles.groundObjLineSpecCombo.String = LineSpecEnum.getListboxStr();
        handles.groundObjLineSpecCombo.Value = LineSpecEnum.getIndForName(grndObj.grdTrkLineSpec.name);

        handles.initialTimeText.String = fullAccNum2Str(grndObj.initialTime);
        handles.extrapolateTimesCheckbox.Value = double(grndObj.extrapolateTimes);
        handles.loopGroundObjTrackCheckbox.Value = double(grndObj.loopWayPts);

        handles.waypointsListbox.String = grndObj.getWayListboxStr();

        wayPt = getSelectedWayPt(handles);
        updateGuiForWayPt(wayPt, grndObj, handles);

        toggleEnableForGuiElements('on', handles);
    else
        handles.groundObjectNameText.String = '';
        handles.groundObjDescText.String = '';
        handles.initialTimeText.String = '';

        updateGuiForWayPt(LaunchVehicleGroundObjectWayPt.empty(1,0), grndObj, handles);
        toggleEnableForGuiElements('off', handles);
    end

    setWayPtDeleteButtonEnable(handles);
    setGrndObjDeleteButtonEnable(handles);

function updateGuiForWayPt(wayPt, grndObj, handles)
    if(not(isempty(wayPt)))
        handles.waypointLatText.String = fullAccNum2Str(rad2deg(wayPt.getLatitude()));
        handles.waypointLongText.String = fullAccNum2Str(rad2deg(wayPt.getLongitude()));
        handles.waypointAltText.String = fullAccNum2Str(wayPt.getAltitude());
        handles.timeToNextWaypointText.String = fullAccNum2Str(wayPt.getTimesToNextWaypt());

        updateDistanceLabel(handles);
    else
        handles.waypointLatText.String = '';
        handles.waypointLongText.String = '';
        handles.waypointAltText.String = '';
        handles.timeToNextWaypointText.String = '';
        handles.distToNextWaypointLabel.String = '';

        handles.waypointsListbox.String = {};
    end

    setWayPtDeleteButtonEnable(handles);

function updateDistanceLabel(handles)
    grndObj = getSelectedGroundObj(handles);
    wayPt = getSelectedWayPt(handles);

    wayPt2 = grndObj.getNextWaypt(wayPt);
    if(not(isempty(wayPt2)))
        wayPtDistStr = fullAccNum2Str(grndObj.getDistanceBetweenWayPts(wayPt, wayPt2));
    else
        wayPtDistStr = '--';
    end

    handles.distToNextWaypointLabel.String = wayPtDistStr;

function wayPt = getSelectedWayPt(handles)
    grndObj = getSelectedGroundObj(handles);

    ind = handles.waypointsListbox.Value;
    wayPt = grndObj.getWayPointAtInd(ind);

function grndObj = getSelectedGroundObj(handles)
    grndObjs = getappdata(handles.lvd_EditGroundObjectsGUI,'grndObjs');

    ind = handles.groundObjListbox.Value;
    grndObj = grndObjs.getGroundObjAtInd(ind);

function toggleEnableForGuiElements(enableStr, handles)
    handles.groundObjListbox.Enable = enableStr;
    handles.removeGroundObjButton.Enable = enableStr;

    handles.groundObjectNameText.Enable = enableStr;
    handles.groundObjDescText.Enable = enableStr;

    handles.celestialBodyCombo.Enable = enableStr;

    handles.groundObjColorCombo.Enable = enableStr;
    handles.groundObjMarkerShapeCombo.Enable = enableStr;
    handles.groundObjLineColorCombo.Enable = enableStr;
    handles.groundObjLineSpecCombo.Enable = enableStr;

    handles.initialTimeText.Enable = enableStr;
    handles.extrapolateTimesCheckbox.Enable = enableStr;
    handles.loopGroundObjTrackCheckbox.Enable = enableStr;

    handles.waypointsListbox.Enable = enableStr;
    handles.moveWaypointDownButton.Enable = enableStr;
    handles.moveWaypointUpButton.Enable = enableStr;
    handles.addWaypointButton.Enable = enableStr;
    handles.removeWaypointButton.Enable = enableStr;

    handles.waypointLatText.Enable = enableStr;
    handles.waypointLongText.Enable = enableStr;
    handles.waypointAltText.Enable = enableStr;
    handles.timeToNextWaypointText.Enable = enableStr;
    handles.distToNextWaypointLabel.Enable = enableStr;

function setGrndObjDeleteButtonEnable(handles)
    grndObjs = getappdata(handles.lvd_EditGroundObjectsGUI,'grndObjs');
    numGrndObjs = grndObjs.getNumGroundObj();

    if(numGrndObjs > 0)
        handles.removeGroundObjButton.Enable = 'on';
    else
        handles.removeGroundObjButton.Enable = 'off';
    end

function setWayPtDeleteButtonEnable(handles)
    grndObj = getSelectedGroundObj(handles);

    if(not(isempty(grndObj)))
        numWayPts = grndObj.getNumWayPts();

        if(numWayPts > 1)
            handles.removeWaypointButton.Enable = 'on';
        else
            handles.removeWaypointButton.Enable = 'off';
        end
    else
        handles.removeWaypointButton.Enable = 'off';
    end

    % --- Outputs from this function are returned to the command line.
function varargout = lvd_EditGroundObjectsGUI_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
    if(isempty(handles))
        varargout{1} = false;
    else
        varargout{1} = true;
        close(handles.lvd_EditGroundObjectsGUI);
    end

    % --- Executes on selection change in groundObjListbox.
function groundObjListbox_Callback(hObject, eventdata, handles)
    % hObject    handle to groundObjListbox (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 groundObjListbox contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from groundObjListbox
    grndObj = getSelectedGroundObj(handles);
    updateGuiForGroundObj(grndObj, handles);

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

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

    % --- Executes on button press in addGroundObjButton.
function addGroundObjButton_Callback(hObject, eventdata, handles)
    % hObject    handle to addGroundObjButton (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    grndObjs = getappdata(handles.lvd_EditGroundObjectsGUI,'grndObjs');
    celBodyData = grndObjs.lvdData.celBodyData;

    grndObj = LaunchVehicleGroundObject.getDefaultObj(celBodyData);
    grndObjs.addGroundObj(grndObj);

    handles.groundObjListbox.String = grndObjs.getListboxStr();
    handles.groundObjListbox.Value = grndObjs.getNumGroundObj();
    updateGuiForGroundObj(grndObj, handles);

    setGrndObjDeleteButtonEnable(handles);

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

    grndObj = getSelectedGroundObj(handles);

    tf = grndObj.isInUse();
    if(tf == false)
        grndObjs.removeGroundObj(grndObj);
        numGrndObjs = grndObjs.getNumGroundObj();

        grndObjs.lvdData.viewSettings.removeGrdObjFromViewProfiles(grndObj);

        handles.groundObjListbox.String = grndObjs.getListboxStr();

        if(handles.groundObjListbox.Value > numGrndObjs)
            handles.groundObjListbox.Value = numGrndObjs;
        end

        grndObj = getSelectedGroundObj(handles);
        updateGuiForGroundObj(grndObj, handles);
        setGrndObjDeleteButtonEnable(handles);
    else
        errordlg('The selected ground object could not be deleted.  It is in use as a constraint or geometric point.  Remove ground object dependecies first.','Could Not Delete Ground Object');
    end

function groundObjectNameText_Callback(hObject, eventdata, handles)
    % hObject    handle to groundObjectNameText (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 groundObjectNameText as text
    %        str2double(get(hObject,'String')) returns contents of groundObjectNameText as a double
    grndObj = getSelectedGroundObj(handles);
    grndObj.name = get(hObject,'String');

    grndObjs = getappdata(handles.lvd_EditGroundObjectsGUI,'grndObjs');
    handles.groundObjListbox.String = grndObjs.getListboxStr();

    % --- Executes during object creation, after setting all properties.
function groundObjectNameText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to groundObjectNameText (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 groundObjDescText_Callback(hObject, eventdata, handles)
    % hObject    handle to groundObjDescText (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 groundObjDescText as text
    %        str2double(get(hObject,'String')) returns contents of groundObjDescText as a double
    grndObj = getSelectedGroundObj(handles);
    grndObj.desc = get(hObject,'String');

    % --- Executes during object creation, after setting all properties.
function groundObjDescText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to groundObjDescText (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 groundObjColorCombo.
function groundObjColorCombo_Callback(hObject, eventdata, handles)
    % hObject    handle to groundObjColorCombo (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 groundObjColorCombo contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from groundObjColorCombo
    grndObj = getSelectedGroundObj(handles);

    contents = cellstr(get(hObject,'String'));
    str = contents{get(hObject,'Value')};

    grndObj.markerColor = ColorSpecEnum.getEnumForListboxStr(str);

    % --- Executes during object creation, after setting all properties.
function groundObjColorCombo_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to groundObjColorCombo (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 groundObjLineSpecCombo.
function groundObjLineSpecCombo_Callback(hObject, eventdata, handles)
    % hObject    handle to groundObjLineSpecCombo (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 groundObjLineSpecCombo contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from groundObjLineSpecCombo
    grndObj = getSelectedGroundObj(handles);

    contents = cellstr(get(hObject,'String'));
    str = contents{get(hObject,'Value')};

    grndObj.grdTrkLineSpec = LineSpecEnum.getEnumForListboxStr(str);

    % --- Executes during object creation, after setting all properties.
function groundObjLineSpecCombo_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to groundObjLineSpecCombo (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 waypointsListbox.
function waypointsListbox_Callback(hObject, eventdata, handles)
    % hObject    handle to waypointsListbox (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 waypointsListbox contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from waypointsListbox
    grndObj = getSelectedGroundObj(handles);
    wayPt = getSelectedWayPt(handles);
    updateGuiForWayPt(wayPt, grndObj, handles);

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

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

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

    initialTime = grndObj.initialTime;
    frameToUse = grndObj.centralBodyInfo.getBodyFixedFrame();
    wayPt = LaunchVehicleGroundObjectWayPt.getDefaultWayPt(initialTime, frameToUse);
    grndObj.addWaypoint(wayPt);

    handles.waypointsListbox.String = grndObj.getWayListboxStr();
    handles.waypointsListbox.Value = grndObj.getNumWayPts();
    updateGuiForWayPt(wayPt, grndObj, handles);

    setWayPtDeleteButtonEnable(handles);

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

    wayPt = getSelectedWayPt(handles);
    grndObj.removeWaypoint(wayPt);
    numWayPts = grndObj.getNumWayPts();

    handles.waypointsListbox.String = grndObj.getWayListboxStr();

    if(handles.waypointsListbox.Value > numWayPts)
        handles.waypointsListbox.Value = numWayPts;
    end

    wayPt = getSelectedWayPt(handles);
    updateGuiForWayPt(wayPt, grndObj, handles);
    setWayPtDeleteButtonEnable(handles);

    % --- Executes on button press in extrapolateTimesCheckbox.
function extrapolateTimesCheckbox_Callback(hObject, eventdata, handles)
    % hObject    handle to extrapolateTimesCheckbox (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 extrapolateTimesCheckbox
    grndObj = getSelectedGroundObj(handles);
    grndObj.extrapolateTimes = logical(get(hObject,'Value'));

    % --- Executes on button press in loopGroundObjTrackCheckbox.
function loopGroundObjTrackCheckbox_Callback(hObject, eventdata, handles)
    % hObject    handle to loopGroundObjTrackCheckbox (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 loopGroundObjTrackCheckbox
    grndObj = getSelectedGroundObj(handles);
    grndObj.loopWayPts = logical(get(hObject,'Value'));

    wayPt = getSelectedWayPt(handles);
    updateGuiForWayPt(wayPt, grndObj, handles);

function initialTimeText_Callback(hObject, eventdata, handles)
    % hObject    handle to initialTimeText (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 initialTimeText as text
    %        str2double(get(hObject,'String')) returns contents of initialTimeText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    grndObj = getSelectedGroundObj(handles);

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'Initial Time';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        grndObj.initialTime = value;
    else
        hObject.String = fullAccNum2Str(grndObj.initialTime);

        msgbox(errMsg,'Invalid Initial Time Value','error');
    end

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

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

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

    wayPtNum = get(handles.waypointsListbox,'Value');
    grndObj.moveWayPtAtIndexDown(wayPtNum);

    if(wayPtNum < grndObj.getNumWayPts())
        set(handles.waypointsListbox,'Value',wayPtNum+1);
    end

    handles.waypointsListbox.String = grndObj.getWayListboxStr();

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

    wayPtNum = get(handles.waypointsListbox,'Value');
    grndObj.moveWayPtAtIndexUp(wayPtNum);

    if(wayPtNum > 1)
        set(handles.waypointsListbox,'Value',wayPtNum-1);
    end

    handles.waypointsListbox.String = grndObj.getWayListboxStr();

function waypointLatText_Callback(hObject, eventdata, handles)
    % hObject    handle to waypointLatText (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 waypointLatText as text
    %        str2double(get(hObject,'String')) returns contents of waypointLatText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    wayPt = getSelectedWayPt(handles);

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'Waypoint Latitude';
    lb = -90;
    ub = 90;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        wayPt.setLatitude(deg2rad(value));

        grndObj = getSelectedGroundObj(handles);
        handles.waypointsListbox.String = grndObj.getWayListboxStr();
        updateDistanceLabel(handles);
    else
        hObject.String = fullAccNum2Str(rad2deg(wayPt.getLatitude()));

        msgbox(errMsg,'Invalid Waypoint Latitude Value','error');
    end

    % --- Executes during object creation, after setting all properties.
function waypointLatText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to waypointLatText (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 waypointLongText_Callback(hObject, eventdata, handles)
    % hObject    handle to waypointLongText (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 waypointLongText as text
    %        str2double(get(hObject,'String')) returns contents of waypointLongText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    wayPt = getSelectedWayPt(handles);

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'Waypoint Longitude';
    lb = -360;
    ub = 360;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        wayPt.setLongitude(deg2rad(value));

        grndObj = getSelectedGroundObj(handles);
        handles.waypointsListbox.String = grndObj.getWayListboxStr();
        updateDistanceLabel(handles);
    else
        hObject.String = fullAccNum2Str(rad2deg(wayPt.getLongitude()));

        msgbox(errMsg,'Invalid Waypoint Longitude Value','error');
    end

    % --- Executes during object creation, after setting all properties.
function waypointLongText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to waypointLongText (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 waypointAltText_Callback(hObject, eventdata, handles)
    % hObject    handle to waypointAltText (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 waypointAltText as text
    %        str2double(get(hObject,'String')) returns contents of waypointAltText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    wayPt = getSelectedWayPt(handles);

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'Waypoint Altitude';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        wayPt.setAltitude(value);

        grndObj = getSelectedGroundObj(handles);
        handles.waypointsListbox.String = grndObj.getWayListboxStr();
        updateDistanceLabel(handles);
    else
        hObject.String = fullAccNum2Str(wayPt.getAltitude());

        msgbox(errMsg,'Invalid Waypoint Altitude Value','error');
    end

    % --- Executes during object creation, after setting all properties.
function waypointAltText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to waypointAltText (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 timeToNextWaypointText_Callback(hObject, eventdata, handles)
    % hObject    handle to timeToNextWaypointText (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 timeToNextWaypointText as text
    %        str2double(get(hObject,'String')) returns contents of timeToNextWaypointText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    wayPt = getSelectedWayPt(handles);

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'Time to Next Waypoint';
    lb = 0.001;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        wayPt.timeToNextWayPt = value;

        grndObj = getSelectedGroundObj(handles);
        handles.waypointsListbox.String = grndObj.getWayListboxStr();
        updateDistanceLabel(handles);
    else
        hObject.String = fullAccNum2Str(wayPt.timeToNextWayPt);

        msgbox(errMsg,'Invalid Time to Next Waypoint Value','error');
    end

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

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

    % --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
    % hObject    handle to saveAndCloseButton (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    errMsg = {};
    if(isempty(errMsg))
        uiresume(handles.lvd_EditGroundObjectsGUI);
    else
        msgbox(errMsg,'Errors were found while editing ground objects.','error');
    end

    % --- Executes on selection change in celestialBodyCombo.
function celestialBodyCombo_Callback(hObject, eventdata, handles)
    % hObject    handle to celestialBodyCombo (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 celestialBodyCombo contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from celestialBodyCombo
    grndObjs = getappdata(handles.lvd_EditGroundObjectsGUI,'grndObjs');
    celBodyData = grndObjs.lvdData.celBodyData;
    [~, sortedBodyInfo] = ma_getSortedBodyNames(celBodyData);

    grndObj = getSelectedGroundObj(handles);

    ind = hObject.Value;
    grndObj.centralBodyInfo = sortedBodyInfo{ind};

    % --- Executes during object creation, after setting all properties.
function celestialBodyCombo_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to celestialBodyCombo (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 during object creation, after setting all properties.
function distToNextWaypointLabel_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to distToNextWaypointLabel (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    empty - handles not created until after all CreateFcns called

    % --- Executes on selection change in groundObjLineColorCombo.
function groundObjLineColorCombo_Callback(hObject, eventdata, handles)
    % hObject    handle to groundObjLineColorCombo (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 groundObjLineColorCombo contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from groundObjLineColorCombo
    grndObj = getSelectedGroundObj(handles);

    contents = cellstr(get(hObject,'String'));
    str = contents{get(hObject,'Value')};

    grndObj.grdTrkLineColor = ColorSpecEnum.getEnumForListboxStr(str);

    % --- Executes during object creation, after setting all properties.
function groundObjLineColorCombo_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to groundObjLineColorCombo (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 groundObjMarkerShapeCombo.
function groundObjMarkerShapeCombo_Callback(hObject, eventdata, handles)
    % hObject    handle to groundObjMarkerShapeCombo (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 groundObjMarkerShapeCombo contents as cell array
    %        contents{get(hObject,'Value')} returns selected item from groundObjMarkerShapeCombo
    grndObj = getSelectedGroundObj(handles);

    contents = cellstr(get(hObject,'String'));
    str = contents{get(hObject,'Value')};

    grndObj.markerShape = MarkerStyleEnum.getEnumForListboxStr(str);

    % --- Executes during object creation, after setting all properties.
function groundObjMarkerShapeCombo_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to groundObjMarkerShapeCombo (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 enterUTAsDateTimeMenu_Callback(hObject, eventdata, handles)
    % hObject    handle to enterUTAsDateTimeMenu (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', fullAccNum2Str(secUT));
        initialTimeText_Callback(handles.initialTimeText, [], handles);
    end

    % --------------------------------------------------------------------
function getUTFromKSPMenu_Callback(hObject, eventdata, handles)
    % hObject    handle to getUTFromKSPMenu (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    secUT = readDoublesFromKSPTOTConnect('GetUT', '', true);
    if(secUT >= 0)
        set(gco, 'String', fullAccNum2Str(secUT));
        initialTimeText_Callback(handles.initialTimeText, [], handles);
    end

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

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function nesp = nonempty_sp(sp)
% Returns the indices of non-empty sp

nesp = [];
for sus = 1:length(sp)
    if sp{sus}.size > 0
        nesp = [nesp, sus];
    end
end

author: Cloud-CV

repo: object-proposals


text:
function regQAPlanC(planC, scanNumV, structNumV, viewV, marginS)

% function imgFilesC = regQAPlanC(planC, scanNumV, structNumV, viewV)
% Usage: outputs image file (s) with review of segmented regions between
% coregistered scans
% Inputs
% planC: CERR object
% scanNumV: list of scan numbers of coregistered scans for comparison, 1xN array
% structNumV: list of structure numbers for comparison. A new image will be
%                output for each struct
% viewV: 1x3 array, indicating how many slices in each view you want to see
% marginS: padding zoom around ROI view

if ischar(planC)
    if exist(planC,'file')
        disp('String filename of planC passed.');
        planC = loadPlanC(planC);
    else
        error('planC filename is not valid path');
    end
end

indexS = planC{end};

if ~exist('marginS','var')
    marginS = 20;
end

if nargin < 2
    scanNumV = 1;
end

scanC = {};

structureListC = {planC{indexS.structures}.structureName};

% get structure mask(s), add error handling for no mask
for i = 1:numel(structNumV)
    structIndex = structNumV(i);
    maskC{i} = getStrMask(structIndex,planC);
    structNameC{i} = structureListC{structIndex};
    cmapC{i} = [rand rand rand];
end

viewNameC = {'sagittal','coronal','axial'};

maskNet3M = zeros(size(maskC{1}));

for i = 1:numel(structNumV)
    mask3M = maskC{i};
    maskNet3M = maskNet3M + mask3M;
end

% get scans
Nscan = numel(scanNumV);
for i = 1:Nscan
    scanIndex = scanNumV(i);
    scanC{i} = getScanArray(scanIndex, planC);
    cmean{i} = mean(scanC{i}(find(maskNet3M)));
    cstd{i} = std(scanC{i}(find(maskNet3M)));
end

for k = 1:3 %views x-,y-,z-plane
    if viewV(k)~=0
        N = viewV(k);

        if k == 1
            for j = 1:numel(scanC)
                rscanC{j} = permute(scanC{j},[2 3 1]);
                rmaskC{j} = permute(maskC{j},[2 3 1]);
            end
            rmaskNet3M = permute(maskNet3M,[2 3 1]);
        elseif k == 2
            for j = 1:numel(scanC)
                rscanC{j} = permute(scanC{j},[3 1 2]);
                rmaskC{j} = permute(maskC{j},[3 1 2]);
            end
            rmaskNet3M = permute(maskNet3M,[3 1 2]);
        else
            rscanC = scanC;
            rmaskC= maskC;
            rmaskNet3M = maskNet3M;
        end

        idx = find(rmaskNet3M);
        [x,y,z] = ind2sub(size(rmaskNet3M),idx);
        minV = [min(x) min(y) min(z)];
        maxV = [max(x) max(y) max(z)];

        incr = floor((maxV(3) - minV(3))/(N + 1));
        if incr < 1
            sliceV = minV(3):maxV(3);
            N = numel(sliceV);
        else
            sliceV = minV(3) + incr*(1:N);
        end
        %get extents
        r1 = [minV(1) - marginS,maxV(1) + marginS];
        if r1(1) < 0
            r1(1) = 0;
        end
        if r1(2) > size(rmaskNet3M,1)
            r1(2) = size(rmaskNet3M,1);
        end
        r2 = [minV(2) - marginS,maxV(2) + marginS];
        if r2(1) < 0
            r2(1) = 0;
        end
        if r2(2) > size(rmaskNet3M,2)
            r2(2) = size(rmaskNet3M,2);
        end

        if N > 5
            ha = [];
            for o = 1:floor(N/5)
                figure;
                ha0 = tight_subplot(5,Nscan,[.01 .03],[.1 .01],[.01 .01]);
                ha = [ha; ha0];
            end
            figure;
            ha0 = tight_subplot(mod(N,5),Nscan,[.01 .03],[.1 .01],[.01 .01]);
            ha = [ha; ha0];
        else
            figure;
            ha = tight_subplot(N,Nscan,[.01 .03],[.1 .01],[.01 .01]);
        end

        for n = 1:N

            for j = 1:Nscan
                rscan3M = rscanC{j};
                slice2M = rscan3M(r1(1):r1(2),r2(1):r2(2),sliceV(n));
                rmaskNet2M = rmaskNet3M(r1(1):r1(2),r2(1):r2(2),sliceV(n));

%                 cmean = mean(slice2M(find(rmaskNet2M)));
%                 cstd = std(slice2M(find(rmaskNet2M)));

                %                 subplot(N,Nscan,(n-1)*Nscan + j); image       sc(slice2M);
                axes(ha((n-1)*Nscan + j)); imagesc(slice2M);
                axis equal; axis off; colormap(gray); caxis([cmean{j} - cstd{j},cmean{j}+cstd{j}]); hold on;

                for z = 1:numel(rmaskC)
                    rmask3M = rmaskC{z};
                    mask2M = rmask3M(r1(1):r1(2),r2(1):r2(2),sliceV(n));
                    [B,~,Nb,~] = bwboundaries(mask2M);
                    for b = 1:Nb
                        bd = B{b};
                        plot(bd(:,2), bd(:,1),'Color',cmapC{z},'LineWidth',2);
                    end
                end
            end
        end

    end
end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
%GETLABTYPE Get label type of dataset
%
%    LABTYPE = GETLABTYPE(A)
%
% Returns the label type of dataset A.

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function figh=hlp_viewGraphicsResource(rscName,hax)
% render a SIFT graphical resource (.jpg, .png, ...) in a figure
% Inputs:
%   rscName:    relative path and name of resource. Path is relative to
%               <sift-root>/resources
%   hax:        optional axis in which to plot image
%
%
% Author: Tim Mullen 2013, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

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

if nargin<2 || isempty(ax)
    hax = [];
end
if isempty(rscName)
    return; end
% remove leading/trailing whitespace
rscName = strtrim(rscName);
if ispc
    strrep(rscName,'/','\');
else
    strrep(rscName,'\','/');
end
% remove any leading slash
if strcmp(rscName(1),filesep)
    rscName(1) = []; end
% get sift rootpath
siftroot = fileparts(utl_whichfile('StartSift.m'));
% construct resource path
rscPath = [siftroot filesep 'resources' filesep rscName];
% check that file exists
if ~exist(rscPath,'file')
    error('SIFT:hlp_viewGraphicsResource:badResourcePath','Resource [%s] does not exist',rscPath);
end
[pathstr name ext] = fileparts(rscPath);
% display resource in figure
im = imread(rscPath);
if isempty(im)
    error('SIFT:hlp_viewGraphicsResource:badResource','Resource [%s] cannot be loaded',rscPath);
end
if isempty(hax)
    figh=figure('Name',[name ext]);
    hax=axes('parent',figh,'position',[0.01 0.01 0.98 0.98]);
end
% render the graphic
image(im,'parent',hax);
axis(hax,'off');
axis(hax,'image');

repo: REST


text:
function [mCatNew, mMagShift] =calc_magerr(mCat,mDeltaMag)
    % calculate magnitude shifts
    %
    % Example:  [mCatNew, mHyposhift]=calc_magerr(mCatalog,mDeltaMag)
    % Input parameter:
    % mCat    Earthquake catalog in zmap format
    % mDelta Error bounds given provided by network ( [dLon, dLat, dDepth] )
    % nDim  0 : error bounds in lon / lat, 1: errorbounds in [km]
    %
    % Output parameter
    % mCatNew Shifted hypocenter
    % mHyposhift   Values by which hypocenters were shifted
    %
    % Author
    % van Stiphout, Thomas
    % vanstiphout@sed.ethz.ch
    % Created
    % 09 Aug 2007
    %
    % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    report_this_filefun();

    % reset random number generator
    rng('shuffle');
    % create randomly distributed errors within given errorbounds
    mMagShift=roundn((rand(size(mCat,1),1)*2-1).*mDeltaMag,-1);

    % add error to the catalog hypocenters
    mCatNew=mCat;
    mCatNew(:,6)=mCatNew(:,6)+mMagShift(:,1);
end

author: CelsoReyes


text:
function cmap = ft_colormap(varargin)

% FT_COLORMAP is a wrapper function with the same usage as the normal COLORMAP
% function, but it also knows about the colormaps from BREWERMAP and some colormaps
% from MATPLOTLIB. The recommended colormaps include 'parula', 'cividis', 'balance',
% and '*RdBu'.
%
% Use as
%   ft_colormap(name)
%   ft_colormap(name, n)
%   ft_colormap(handle, name)
%   ft_colormap(handle, name, n)
%
% The name is a string that specifies the colormap (see below). The optional handle
% can be used to specify the current figure (which is the default, see GCF) or the
% current axes (see GCA). The optional parameter n determines the number of steps or
% unique colors in the map (by default 64).
%
% The colormaps from MATLAB include 'parula', 'jet', 'hsv', 'hot', 'cool', 'spring',
% 'summer', 'autumn', 'winter', 'gray', 'bone', 'copper', 'pink', 'lines',
% 'colorcube', 'prism', and 'flag'.
%
% The colormaps from MATPLOTLIB include 'cividis', 'inferno', 'magma', 'plasma',
% 'tab10', 'tab20', 'tab20b', 'tab20c', 'twilight', and 'viridis'.
%
% The colormaps from BREWERMAP include 'BrBG', 'PRGn', 'PiYG', 'PuOr', 'RdBu',
% 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'Accent', 'Dark2', 'Paired', 'Pastel1',
% 'Pastel2', 'Set1', 'Set2', 'Set3', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens',
% 'Greys', 'OrRd', 'Oranges', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds',
% 'YlGn', 'YlGnBu', 'YlOrBr', and 'YlOrRd', plus their reverse when prefixed with '*'.
%
% The colormaps from CMOCEAN include 'thermal', 'haline', 'solar', 'ice', 'gray',
% 'oxy', 'deep', 'dense', 'algae', 'matter', 'turbid', 'speed', 'amp', 'tempo',
% 'rain', 'phase', 'topo', 'balance', 'delta', 'curl', 'diff', and 'tarn'.
%
% The colormaps from COLORCET include 'blueternary', 'coolwarm', 'cyclicgrey',
% 'depth', 'divbjy', 'fire', 'geographic', 'geographic2', 'gouldian', 'gray',
% 'greenternary', 'grey', 'heat', 'phase2', 'phase4', 'rainbow', 'rainbow2',
% 'rainbow3', 'rainbow4', 'redternary', 'reducedgrey', 'yellowheat', and all the ones
% with symbolic names.
%
% To reverse any of these these colormaps you can add a minus sign in front, like
% '-phase', '-balance' or '-RdBu'.
%
% Relevant publications:
% - Crameri et al. 2020. The misuse of colour in science communication. https://doi.org/10.1038/s41467-020-19160-7
% - Cooper et al. 2021. Over the rainbow: Guidelines for meaningful use of colour maps in neurophysiology. https://doi.org/10.1016/j.neuroimage.2021.118628
% - Kovesi 2015, Good colour maps: How to design them. https://doi.org/10.48550/arXiv.1509.03700
%
% See also COLORMAP, COLORMAPEDITOR, BREWERMAP, MATPLOTLIB, CMOCEAN, COLORCET

% Copyright (C) 2022, Jan-Mathijs Schoffelen, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% 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$

ft_hastoolbox('brewermap', 2);  % check and give a warning if it cannot be added
ft_hastoolbox('matplotlib', 2); % check and give a warning if it cannot be added
ft_hastoolbox('cmocean', 2);
ft_hastoolbox('colorcet', 2);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% interpret the input arguments

% please note that ishandle('parula') returns a logical array
% hence the all(ishandle(...)), which in that case returns false

if nargin==0
  % apply the default colormap
  handle = gcf;
  name   = 'default';
  n      = 64;

elseif nargin==1 && isnumeric(varargin{1})
  % the user specified an Nx3 array as colormap
  handle = gcf;
  name   = varargin{1}; % note that this is not a string, it is dealt with below
  n      = nan;

elseif nargin==1 && all(ishandle(varargin{1}))
  % apply the default colormap on the specified handle
  handle = varargin{1};
  name   = 'default';
  n      = 64;

elseif nargin==1 && ischar(varargin{1})
  % apply the specified colormap on the current figure
  handle = gcf;
  name   = varargin{1};
  n      = 64;

elseif nargin==2 && all(ishandle(varargin{1}))
  % apply the specified colormap on the specified handle
  handle = varargin{1};
  name   = varargin{2};
  n      = 64;

elseif nargin==2 && ischar(varargin{1})
  % apply the specified colormap with specified N on the current figure
  handle = gcf;
  name   = varargin{1};
  n      = varargin{2};

elseif nargin==3 && all(ishandle(varargin{1}))
  % apply the specified colormap with specified N on the specified handle
  handle = varargin{1};
  name   = varargin{2};
  n      = varargin{3};

else
  ft_error('incorrect input arguments');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the colormap

% the ones from brewermap are not m-files on disk
brewerlist = repmat(brewermap('list'), [2 1]);
% also include the reverse ones
for k = 1:numel(brewerlist)/2
  brewerlist{k} = sprintf('*%s', brewerlist{k});
end

% the ones from cmocean are not m-files on disk
cmoceanlist = {
  'thermal'
  'haline'
  'solar'
  'ice'
  'gray'
  'oxy'
  'deep'
  'dense'
  'algae'
  'matter'
  'turbid'
  'speed'
  'amp'
  'tempo'
  'rain'
  'phase'
  'topo'
  'balance'
  'delta'
  'curl'
  'diff'
  'tarn'
  };
% also include the reverse ones
for k = 1:numel(cmoceanlist)
  cmoceanlist{end+1} = sprintf('-%s', cmoceanlist{k});
end

% the ones from colorcet are not m-files on disk
colorcetlist = {
  'blueternary'
  'coolwarm'
  'cyclicgrey'
  'depth'
  'divbjy'
  'fire'
  'geographic'
  'geographic2'
  'gouldian'
  'gray'
  'greenternary'
  'grey'
  'heat'
  'phase2'
  'phase4'
  'rainbow'
  'rainbow2'
  'rainbow3'
  'rainbow4'
  'redternary'
  'reducedgrey'
  'yellowheat'
  };
% also include the reverse ones
for k = 1:numel(colorcetlist)
  colorcetlist{end+1} = sprintf('-%s', colorcetlist{k});
end

if isnumeric(name)
  % the user specified an Nx3 array as colormap
  cmap = name;
elseif ismember(name, brewerlist)
  cmap = brewermap(n, name);
elseif startsWith(name, '-') && ismember(name(2:end), brewerlist)
  cmap = brewermap(n, strrep(name, '-', '*'));
elseif ismember(name, cmoceanlist)
  cmap = cmocean(name, n);
elseif ismember(name, colorcetlist)
  cmap = colorcet(name, 'n', n, 'reverse', false);
elseif startsWith(name, '-') && ismember(name(2:end), colorcetlist)
  cmap = colorcet(name(2:end), 'n', n, 'reverse', true);
elseif isequal(name, 'default')
  % requires separate handling, because there's no function called default,
  % the default is taken care of by colormap
  cmap = name;
else
  % this works both for the MATLAB and the MATPLOTLIB colormaps
  % which have the different colormaps available as an m-file
  if name(1)=='-'
    cmap = flipud(feval(name(2:end), n));
  else
    cmap = feval(name, n);
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% apply the colormap and/or return it

if nargout>0
  % apply it to the specified figure or axis and return it as a Nx3 array
  colormap(handle, cmap)
else
  % only apply it to the current figure
  colormap(handle, cmap)
  clear cmap
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip