text:
function src_dirs_rad = sphESPRIT(Us)
%SPHESPRIT DoA estimation using ESPRIT in the SHD
%
%   This routine spherical ESPRIT method to SH signals and returns the
%   analyzed DoAs without a grid search. It implements the 3-recurrence
%   relationship variant proposed by Jo & Choi in
%
%   B. Jo and J.-W. Choi, “Parametric direction-of-arrival estimation with
%   three recurrence relations of spherical harmonics,”
%   J. Acoust. Soc. Amer.,vol. 145, no. 1, pp. 480–488, Jan. 2019.
%
%   Subspace approaches such as ESPRIT can offer higher spatial resolution
%   than beamforming approaches such as the steered-response power, as long
%   as the source signals are not correlated between them and with the
%   reverberant/diffuse sound.
%
%   Inputs:
%       Us: (order+1)^2xK signal subspace taken from the first K eigenvectors
%       of the spatial correlation matrix, after sorting in eigenvalue
%       descending order
%
%   Outputs:
%       est_dirs:   nSrcx2 [azi elev] of estimated directions from
%           peak-finding
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SPHESPRIT.M - 5/3/2019
% Archontis Politis, archontis.politis@tuni.fi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[LambdaXYp, LambdaXYm, LambdaZ] = getLambda(Us);
[PsiXYp, PsiXYm, PsiZ] = getPsi(Us, LambdaXYp, LambdaXYm, LambdaZ);
[V, ~] = eig(PsiXYp, PsiZ, 'qz'); % A*V = B*V*D -> [V,D]=eig(A,B).
PhiXYp = V\(PsiXYp*V);
PhiXYm = V\(PsiXYm*V);
PhiZ   = V\(PsiZ*V);
phiX   = real(diag(PhiXYp+PhiXYm)/2);
phiY   = real(diag(PhiXYp-PhiXYm)/(2i));
phiZ   = real(diag(PhiZ));

azim = atan2(phiY,phiX);
elev = atan2(phiZ,sqrt(phiX.^2+phiY.^2));
src_dirs_rad = [azim elev];

end

function Ynimu = getYnimu(Ynm, ni, mu)

N = sqrt(size(Ynm,2))-1;
[idx_nimu, idx_nm] = muni2q(N,ni,mu);
Ynimu = zeros(size(Ynm,1),N^2);
Ynimu(:,idx_nimu) = Ynm(:,idx_nm);

end

function [idx_nimu, idx_nm] = muni2q(order,ni,mu)

nm = [];
for n=0:order-1
    nm = [nm; n*ones(2*n+1,1) (-n:n)'];
end
nimu = [nm(:,1)+ni nm(:,2)+mu];
qnm = nm(:,1).^2+nm(:,1)+nm(:,2)+1;
qnimu = nimu(:,1).^2+nimu(:,1)+nimu(:,2)+1;
idx_valid = find(abs(nimu(:,2))<=nimu(:,1));
idx_nm = qnimu(idx_valid);
idx_nimu = qnm(idx_valid);

end

function Wnimu = getWnimu(order, mm, ni, mu)

nm = [];
for n=0:order-1
    nm = [nm; n*ones(2*n+1,1) (-n:n)'];
end
if mm==1
    nimu = [nm(:,1)+ni nm(:,2)+mu];
elseif mm==-1
    nimu = [nm(:,1)+ni -nm(:,2)+mu];
end
w_nimu = sqrt( (nimu(:,1)-nimu(:,2)-1).*(nimu(:,1)-nimu(:,2))./((2*nimu(:,1)-1).*(2*nimu(:,1)+1)) );
Wnimu = diag(w_nimu);

end

function Vnimu = getVnimu(order, ni, mu)

nm = [];
for n=0:order-1
    nm = [nm; n*ones(2*n+1,1) (-n:n)'];
end
nimu = [nm(:,1)+ni nm(:,2)+mu];
v_nimu = sqrt( (nimu(:,1)-nimu(:,2)).*(nimu(:,1)+nimu(:,2)) ./((2*nimu(:,1)-1).*(2*nimu(:,1)+1)) );
Vnimu = diag(v_nimu);

end

function [PsiXYp, PsiXYm, PsiZ] = getPsi(Us, LambdaXYp, LambdaXYm, LambdaZ)

pinvUs = pinv(getYnimu(Us.',0,0).');
PsiXYp = pinvUs*LambdaXYp;
PsiXYm = pinvUs*LambdaXYm;
PsiZ   = pinvUs*LambdaZ;

end

function [PhiXYp, PhiXYm, PhiZ] = getPhi(src_dirs_rad)

PhiZ = diag(cos(src_dirs_rad(:,2)));
PhiXYp = diag( sin(src_dirs_rad(:,2)).*exp(1i*src_dirs_rad(:,1)) );
PhiXYm = diag( sin(src_dirs_rad(:,2)).*exp(-1i*src_dirs_rad(:,1)) );

end

function [LambdaXYp, LambdaXYm, LambdaZ] = getLambda(Us)

order = sqrt(size(Us,1))-1;
LambdaXYp =  getWnimu(order, 1,1,-1)*getYnimu(Us.', 1,-1).' - getWnimu(order,-1,0,0)*getYnimu(Us.',-1,-1).';
LambdaXYm = -getWnimu(order,-1,1,-1)*getYnimu(Us.', 1, 1).' + getWnimu(order, 1,0,0)*getYnimu(Us.',-1, 1).';
LambdaZ   =  getVnimu(order,   0, 0)*getYnimu(Us.',-1, 0).' + getVnimu(order,   1,0)*getYnimu(Us.', 1, 0).';

end

author: polarch

repo: Spherical-Array-Processing


text:
function [rt, f, g] = twodsin(A, u0, v0, M, N)
%TWODSIN Compare for-loops vs. vectorization.
%   The comparison is based on implementing the function f(x, y) =
%   Asin(u0x + v0y) for x = 0, 1, 2,..., M - 1 and y = 0, 1, 2,...,
%   N - 1. The inputs to the function are M and N and the constants
%   in the function.
%
%   Sample M-file used in Chapter 2.

%   Copyright 2002-2004 R. C. Gonzalez, R. E. Woods, & S. L. Eddins
%   Digital Image Processing Using MATLAB, Prentice-Hall, 2004
%   $Revision: 1.3 $  $Date: 2003/10/13 00:53:47 $

% First implement using for loops.

tic   % Start timing.

for r = 1:M
   u0x = u0*(r - 1);
   for c = 1:N
      v0y = v0*(c - 1);
      f(r, c) = A*sin(u0x + v0y);
   end
end

t1 = toc;   % End timing.

%	Now implement using vectorization.  Call the image g.

tic   % Start timing.

r = 0:M - 1;
c = 0:N - 1;
[C, R] = meshgrid(c, r);
g = A*sin(u0*R + v0*C);

t2 = toc;   % End timing.

%	Compute the ratio of the two times.

rt = t1/(t2 + eps); % Use eps in case t2 is close to 0

repo: weiyanmin


text:
% Script to create two drees files from ddbs stucture.
%1st file consists of all trials.
%2nd file consists of expected dvhs and the confidence bounds for the expeced dvhs.

fileName1 = '';
filename2 = '';

%File containing all DVHs
ddbsOriginal = ddbs;
numOriginalPatients = length(ddbs);
for iPat = 1:numOriginalPatients
    for iTrial = 1:length(ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.allTrials)
        dvh_tmp = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.allTrials{iTrial};
        ddbs(end+1) = ddbs(iPat);
        ddbs(end).dvh_Rectum_shift_0pt25cm = dvh_tmp;
    end
end

ddbs(1:numOriginalPatients) = [];
ddbs = rmfield(ddbs,'dvh_Rectum_shift_0pt25cm_rectum');
save(fileName1,'ddbs');

%File containing expected DVHs and the confidence bounds
ddbs = ddbsOriginal;
numOriginalPatients = length(ddbs);
for iPat = 1:numOriginalPatients
    ddbs(iPat).dvh_Rectum_shift_0pt25cm_Expected = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.meanM;

    ddbs(iPat).dvh_Rectum_shift_0pt25cm_Minus1Sigma = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.Minus1SigmaM;
    ddbs(iPat).dvh_Rectum_shift_0pt25cm_Minus2Sigma = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.Minus2SigmaM;
    ddbs(iPat).dvh_Rectum_shift_0pt25cm_Minus3Sigma = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.Minus3SigmaM;

    ddbs(iPat).dvh_Rectum_shift_0pt25cm_Plus1Sigma = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.Plus1SigmaM;
    ddbs(iPat).dvh_Rectum_shift_0pt25cm_Plus2Sigma = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.Plus2SigmaM;
    ddbs(iPat).dvh_Rectum_shift_0pt25cm_Plus3Sigma = ddbs(iPat).dvh_Rectum_shift_0pt25cm_rectum.Plus3SigmaM;
end

ddbs(1:numOriginalPatients) = [];
ddbs = rmfield(ddbs,'dvh_Rectum_shift_0pt25cm_rectum');
save(fileName2,'ddbs');

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function Rinv = est_calcInvCovMat(AR,C,invCov,mode,MAXITER)
%
% For any M-variate VAR[p] process fit to data X = [X1, X2, ... Xn],
% this function returns the [(Mp)^2 x (Mp)^2] covariance (or inverse covariance)
% matrix of the process. This is a block-toeplitz, hermitian matrix with
% format as described in [2].
%
% Briefly, let M=nvars, and Rhat be comprised of M x M submatrices
%
%           Rhat(u,v) = [R11(u,v) ... R1M
%                           ...        ...
%                        RM1(u,v) ... RMM(u,v)]
%
% where Rij(u,v) = cov(Xi(t-u),Xj(t-v)) for i,j=1:M and u,v = 1:p. Then
% Rhat is the (cross-)covariance matrix of the VAR[p] process up to lag p
% with inverse covariance matrix Rinv = inverse(Rhat).
%
% Inputs:
%
%   AR:     [nvars x nvar*morder] matrix of vector autoregressive
%           coefficients
%   C:      nvars x nvars noise covariance matrix
%   invCov: {def: 1}
%           true: return inverse of processes covariance matrix
%           fase: return process covariance matrix
%   mode:   {def: 3} Determines the method used to compute the covariance matrix
%           1: uses the standard approach from [2]
%           2: same as 1, but using sparse matrices.
%           3: uses the iterative doubling algorithm of Anderson and Moore
%              as proposed in [1]. For large matrices, generally much faster
%              and less memory intensive.
%   MAXITER:{def: 100}
%           Number of iterations for doubling algorithm (mode=3)
%
% Outputs:
%
%   Rinv:   [(nvars*p)^2 x (nvars*p)^2] (inverse) covariance matrix of the
%           VAR[p] process.
%
%
% References:
%
% [1] Barone, (1987) J. of Time series Analysis vol. 8 no. 2
% [2] Lutkepohl, H. (2007) New Introduction to Time Series Analysis.
% Springer. Sec 2.1.4.
%
% See Also: est_calcInvCovMatFourier(), est_calcInvCovMatPDC
%
% Author: Tim Mullen 2010, 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<4
    mode = 3;
end
if nargin<3
    invCov = 1;    % if 0, don't invert covariance matrix
end
if nargin<4
    MAXITER = 100;
end

% make sure the noise covariance matrix is valid
C = covfixer(C);

switch mode

    case 1

        % Standard covariance estimation. See [2] sec. 2.1.4

        M = size(C,1);          % nchans
        p = size(AR,2)/M;       % model order
        Mp=M*p;

        A = zeros(Mp);
        A(1:M,1:Mp) = AR;
        A(M+1:end,1:end-M) = eye(Mp-M);
        Eu = zeros(Mp);
        Eu(1:M,1:M) = C;

        Rinv = (eye(Mp^2)-kron(A,A))\Eu(:);

%         Rinv = reshape(Rinv,Mp,Mp)\eye(Mp);

        Rinv = inverse(reshape(Rinv,Mp,Mp));

    case 2

        % same as 1, but sparse approach

        M = size(C,1);          % nchans
        p = size(AR,2)/M;       % model order
        Mp=M*p;

        A = spalloc(Mp,Mp,M*Mp+M);
        A(1:M,1:Mp) = AR;
        A(M+1:end,1:end-M) = eye(Mp-M);

        Eu = spalloc(Mp,Mp,M^2);
        Eu(1:M,1:M) = single(C);

        Rinv = (speye(Mp^2)-kron(A,A))\Eu(:);

        % Rinv = symmlq(speye(Mp^2)-kron(A,A),Eu(:),1e-6,100);

        Rinv = full(reshape(Rinv,Mp,Mp)\speye(Mp));

    case 3

        % Anderson-Moore/Barone Doubling Algorithm [1]

        M = size(C,1);          % nchans
        p = size(AR,2)/M;       % model order
        Mp=M*p;
        A = zeros(Mp);
        A(1:M,1:Mp) = AR;
        A(M+1:end,1:end-M) = eye(Mp-M);

        K = [eye(M); zeros(M*(p-1),M)];
        N = {K*C*K'};
        N{2} = zeros(size(N{1}));

        for t=1:MAXITER
            N{2} = A*N{1}*A'+N{1};
            A = A^2;
            if norm(N{2}(:)-N{1}(:))<1e-15
                break
            end
            N{1}=N{2};
        end

        if t==MAXITER
            warning('SIFT:est_calcInvCovMat', 'Anderson-Moore did not converge. Results may be innacurate.\n');
        end

        % Rinv = L*N{2}*L';

        % ensure that the covariance matrix is a valid covariance matrix
        N{2} = covfixer(N{2});

        if invCov
            Rinv = inverse(N{2});
        else
            Rinv = N{2};
        end

end

repo: REST


text:
%% --- tutorial script for spectral analysis ---

% This tutorial demonstrates the use of BCILAB to learn basic predictive models using
% spectral properties of the data, here operating on motor cortex idle oscillations.
%
% The used data set contains a sequence of trials in which a subject was instructed to imagine
% moving either the left hand or the right hand. Markers in the data set indicate the timing and
% type of these instructions (types are: 'StimulusCode_2' and 'StimulusCode_3').
%
% Notes: StimulusCode_1 indicates onset of a "resting" / "relaxing" condition.
%
% Data courtesy of Romain Grandchamp, CERCO, Toulouse, France. Reference:
%   Romain Grandchamp, Arnaud Delorme, "NeuroTRIP: A Framework for Bridging between Open Source Software. Application to Training a Brain Machine Interface,"
%   Fifth International Conference on Signal Image Technology and Internet Based Systems, pp.451-457, 2009
%
%#ok<*ASGLU,*NASGU,*SNASGU> % turn off a few editor warnings...

%% --- using the Common Spatial Pattern method ---

% load the data set (BCI2000 format)
traindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);

% define the approach (here: Common Spatial Patterns without any customization)
myapproach = 'CSP';

% learn a predictive model
[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});
disp(['training mis-classification rate: ' num2str(trainloss*100,3) '%']);

% visualize results
bci_visualize(lastmodel)

%% --- using the Common Spatial Pattern method with some custom options ---

% load the data set (BCI2000 format)
traindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);

% define the approach
% Note: The settings found in the GUI "Review/Edit Approach" Panel can be translated literally
%       into cell array representations as below. Each paradigm has a few top-level parameter groups
%       (for CSP: SignalProcessing, FeatureExtraction, etc), which in turn have sub-parameters
%       (e.g., SignalProcessing has EpochExtraction, SpectralSelection, Resampling, etc.), and so
%       on. Some parameters are numbers, strings, cell arrays, etc. You only need to specify those
%	    parameters where you actually want to deviate from the paradigm's defaults.
%
% For illustratory purposes, we use a different window relative to the target markers (0.5s to 3s after),
% and a somewhat customized FIR frequency filter with a pass-band between ~7.5Hz and ~27Hz.
myapproach = {'CSP' 'SignalProcessing',{'EpochExtraction',[0.5 3],'FIRFilter',[7 8 26 28]}};

% learn a predictive model
[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});
disp(['training mis-classification rate: ' num2str(trainloss*100,3) '%']);

% visualize results
bci_visualize(lastmodel)

%% --- applying the CSP model to some data (here: same data) ---

% apply the previously learned model to a data set (querying it for each target marker in the data)
[prediction,loss,teststats,targets] = bci_predict(lastmodel,traindata);

% display the results
disp(['test mis-classification rate: ' num2str(loss*100,3) '%']);
disp(['  predicted classes: ',num2str(round(prediction{2}*prediction{3})')]);  % class probabilities * class values
disp(['  true classes     : ',num2str(round(targets)')]);

%% --- the same using pseudo-online processing ---

% This function is quite flexible, but here we only ask it to query the BCI seconds after each of the given markers
[predictions,latencies] = onl_simulate(traindata,lastmodel,'markers',{'StimulusCode_2','StimulusCode_3'},'offset',3);

% now check the prediction accuracy by hand (we knew the correct target label at each of the markers)
accuracy = mean(argmax(predictions') == targets');
disp(['pseudo-online mis-classification rate: ' num2str((1-accuracy)*100,3) '%']);

%% --- using the Spectrally weighted Common Spatial Pattern (Spec-CSP) method ---
% this method automatically learns the spectral filters (within a pre-defined range), but it
% may run into a local optimum or over-fit spuriously correlated bands

% load the data set
traindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);

% define the approach
myapproach = {'SpecCSP' 'SignalProcessing',{'EpochExtraction',[0.5 3]}};

% learn a predictive model
[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'}); %#ok<>

% visualize results
bci_visualize(lastmodel)

%% --- test the learned model in simulated real-time processing ---
% ( click into the figure to stop the update (and make sure that your click was registered) )

% load feedback session
testdata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/feedback/DanielS001R01.dat','channels',1:29);

% play it back in real time
run_readdataset('Dataset',testdata);

% process data in real time using lastmodel, and visualize outputs
run_writevisualization('Model',lastmodel, 'VisFunction','bar(y);ylim([0 1])');

% make sure that the online processing gets terminated...
disp('Click into the figure to stop online processing.');
waitforbuttonpress; onl_clear; close(gcf);

%% --- train an alternative model with parameter search ---
% (over possible values for the number of pattern pairs, using CSP; note: this takes quite some time!)
% (the number of pattern pairs found optimal should be 3 in this case)

% load the data set (BCI2000 format)
traindata = io_loadset('bcilab:/userdata/tutorial/imag_movements1/calib/DanielS001R01.dat','channels',1:29);

% define approach
myapproach = {'CSP' 'Prediction',{'FeatureExtraction',{'PatternPairs',search(1,2,3)}}};

% learn the model
[trainloss,lastmodel,laststats] = bci_train('Data',traindata,'Approach',myapproach,'TargetMarkers',{'StimulusCode_2','StimulusCode_3'});
disp(['training mis-classification rate: ' num2str(trainloss*100,3) '%']);

% visualize results
bci_visualize(lastmodel);


text:
function t_modcost(quiet)
%T_MODCOST  Tests for code in MODCOST.

%   MATPOWER
%   Copyright (c) 2010-2016, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

if nargin < 1
    quiet = 0;
end

n_tests = 162;

t_begin(n_tests, quiet);

%% define named indices into data matrices
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;
[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;

%% generator cost data
%	1	startup	shutdown	n	x1	y1	...	xn	yn
%	2	startup	shutdown	n	c(n-1)	...	c0
gencost0 = [
	2	0	0	3	0.01	0.1	1	0	0	0	0	0;
	2	0	0	5	0.0006	0.005	0.04	0.3	2	0	0	0;
	1	0	0	4	0	0	10	200	20	600	30	1200;
	1	0	0	4	-30	-2400	-20	-1800	-10	-1000	0	0;
];

%%-----  scalar values for alpha  -----
gencost = modcost(gencost0, 5, 'SCALE_F');

t = 'modcost SCALE_F - quadratic';
t_is(totcost(gencost, [0;0;0;0])/5, [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0])/5, [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0])/5, [1.24;2;0;0], 8, t);

t = 'modcost SCALE_F - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0])/5, [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0])/5, [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0])/5, [1;2.8096;0;0], 8, t);

t = 'modcost SCALE_F - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ])/5, [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0])/5, [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0])/5, [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0])/5, [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0])/5, [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0])/5, [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0])/5, [1;2;1500;0], 8, t);

t = 'modcost SCALE_F - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ])/5, [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10])/5, [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15])/5, [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20])/5, [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25])/5, [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30])/5, [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35])/5, [1;2;0;-2700], 8, t);

gencost = modcost(gencost0, 2, 'SCALE_X');

t = 'modcost SCALE_X - quadratic';
t_is(totcost(gencost, [0;0;0;0]*2), [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0]*2), [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0]*2), [1.24;2;0;0], 8, t);

t = 'modcost SCALE_X - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0]*2), [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0]*2), [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0]*2), [1;2.8096;0;0], 8, t);

t = 'modcost SCALE_X - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ]*2), [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0]*2), [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0]*2), [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0]*2), [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0]*2), [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0]*2), [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0]*2), [1;2;1500;0], 8, t);

t = 'modcost SCALE_X - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ]*2), [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10]*2), [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15]*2), [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20]*2), [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25]*2), [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30]*2), [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35]*2), [1;2;0;-2700], 8, t);

gencost = modcost(gencost0, 3, 'SHIFT_F');

t = 'modcost SHIFT_F - quadratic';
t_is(totcost(gencost, [0;0;0;0])-3, [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0])-3, [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0])-3, [1.24;2;0;0], 8, t);

t = 'modcost SHIFT_F - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0])-3, [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0])-3, [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0])-3, [1;2.8096;0;0], 8, t);

t = 'modcost SHIFT_F - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ])-3, [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0])-3, [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0])-3, [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0])-3, [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0])-3, [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0])-3, [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0])-3, [1;2;1500;0], 8, t);

t = 'modcost SHIFT_F - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ])-3, [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10])-3, [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15])-3, [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20])-3, [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25])-3, [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30])-3, [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35])-3, [1;2;0;-2700], 8, t);

gencost = modcost(gencost0, -4, 'SHIFT_X');

t = 'modcost SHIFT_X - quadratic';
t_is(totcost(gencost, [0;0;0;0]-4), [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0]-4), [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0]-4), [1.24;2;0;0], 8, t);

t = 'modcost SHIFT_X - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0]-4), [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0]-4), [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0]-4), [1;2.8096;0;0], 8, t);

t = 'modcost SHIFT_X - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ]-4), [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0]-4), [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0]-4), [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0]-4), [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0]-4), [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0]-4), [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0]-4), [1;2;1500;0], 8, t);

t = 'modcost SHIFT_X - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ]-4), [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10]-4), [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15]-4), [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20]-4), [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25]-4), [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30]-4), [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35]-4), [1;2;0;-2700], 8, t);

t = 'modcost empty gencost';
gencost = modcost([], 7);
t_ok(isempty(gencost), t);

%%-----  vector values for alpha  -----
alpha = [10; 9; 8; 7];
gencost = modcost(gencost0, alpha, 'SCALE_F');

t = 'modcost vector SCALE_F - quadratic';
t_is(totcost(gencost, [0;0;0;0])./alpha, [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0])./alpha, [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0])./alpha, [1.24;2;0;0], 8, t);

t = 'modcost vector SCALE_F - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0])./alpha, [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0])./alpha, [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0])./alpha, [1;2.8096;0;0], 8, t);

t = 'modcost vector SCALE_F - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ])./alpha, [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0])./alpha, [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0])./alpha, [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0])./alpha, [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0])./alpha, [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0])./alpha, [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0])./alpha, [1;2;1500;0], 8, t);

t = 'modcost vector SCALE_F - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ])./alpha, [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10])./alpha, [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15])./alpha, [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20])./alpha, [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25])./alpha, [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30])./alpha, [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35])./alpha, [1;2;0;-2700], 8, t);

gencost = modcost(gencost0, alpha, 'SCALE_X');

t = 'modcost vector SCALE_X - quadratic';
t_is(totcost(gencost, [0;0;0;0].*alpha), [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0].*alpha), [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0].*alpha), [1.24;2;0;0], 8, t);

t = 'modcost vector SCALE_X - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0].*alpha), [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0].*alpha), [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0].*alpha), [1;2.8096;0;0], 8, t);

t = 'modcost vector SCALE_X - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ].*alpha), [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0].*alpha), [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0].*alpha), [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0].*alpha), [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0].*alpha), [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0].*alpha), [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0].*alpha), [1;2;1500;0], 8, t);

t = 'modcost vector SCALE_X - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ].*alpha), [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10].*alpha), [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15].*alpha), [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20].*alpha), [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25].*alpha), [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30].*alpha), [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35].*alpha), [1;2;0;-2700], 8, t);

gencost = modcost(gencost0, alpha, 'SHIFT_F');

t = 'modcost vector SHIFT_F - quadratic';
t_is(totcost(gencost, [0;0;0;0])-alpha, [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0])-alpha, [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0])-alpha, [1.24;2;0;0], 8, t);

t = 'modcost vector SHIFT_F - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0])-alpha, [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0])-alpha, [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0])-alpha, [1;2.8096;0;0], 8, t);

t = 'modcost vector SHIFT_F - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ])-alpha, [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0])-alpha, [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0])-alpha, [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0])-alpha, [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0])-alpha, [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0])-alpha, [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0])-alpha, [1;2;1500;0], 8, t);

t = 'modcost vector SHIFT_F - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ])-alpha, [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10])-alpha, [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15])-alpha, [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20])-alpha, [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25])-alpha, [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30])-alpha, [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35])-alpha, [1;2;0;-2700], 8, t);

gencost = modcost(gencost0, -alpha, 'SHIFT_X');

t = 'modcost vector SHIFT_X - quadratic';
t_is(totcost(gencost, [0;0;0;0]-alpha), [1;2;0;0], 8, t);
t_is(totcost(gencost, [1;0;0;0]-alpha), [1.11;2;0;0], 8, t);
t_is(totcost(gencost, [2;0;0;0]-alpha), [1.24;2;0;0], 8, t);

t = 'modcost vector SHIFT_X - 4th order polynomial';
t_is(totcost(gencost, [0;0;0;0]-alpha), [1;2;     0;0], 8, t);
t_is(totcost(gencost, [0;1;0;0]-alpha), [1;2.3456;0;0], 8, t);
t_is(totcost(gencost, [0;2;0;0]-alpha), [1;2.8096;0;0], 8, t);

t = 'modcost vector SHIFT_X - pwl (gen)';
t_is(totcost(gencost, [0;0;5;0 ]-alpha), [1;2;100;0], 8, t);
t_is(totcost(gencost, [0;0;10;0]-alpha), [1;2;200;0], 8, t);
t_is(totcost(gencost, [0;0;15;0]-alpha), [1;2;400;0], 8, t);
t_is(totcost(gencost, [0;0;20;0]-alpha), [1;2;600;0], 8, t);
t_is(totcost(gencost, [0;0;25;0]-alpha), [1;2;900;0], 8, t);
t_is(totcost(gencost, [0;0;30;0]-alpha), [1;2;1200;0], 8, t);
t_is(totcost(gencost, [0;0;35;0]-alpha), [1;2;1500;0], 8, t);

t = 'modcost vector SHIFT_X - pwl (load)';
t_is(totcost(gencost, [0;0;0;-5 ]-alpha), [1;2;0;-500], 8, t);
t_is(totcost(gencost, [0;0;0;-10]-alpha), [1;2;0;-1000], 8, t);
t_is(totcost(gencost, [0;0;0;-15]-alpha), [1;2;0;-1400], 8, t);
t_is(totcost(gencost, [0;0;0;-20]-alpha), [1;2;0;-1800], 8, t);
t_is(totcost(gencost, [0;0;0;-25]-alpha), [1;2;0;-2100], 8, t);
t_is(totcost(gencost, [0;0;0;-30]-alpha), [1;2;0;-2400], 8, t);
t_is(totcost(gencost, [0;0;0;-35]-alpha), [1;2;0;-2700], 8, t);

t = 'modcost vector empty gencost';
gencost = modcost([], alpha);
t_ok(isempty(gencost), t);

t_end;

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
%SCHEMER_IMPORT Import a MATLAB color scheme
%   SCHEMER_IMPORT() with no input will prompt the user to locate the
%   color theme source file via the GUI.
%
%   SCHEMER_IMPORT(FILENAME) imports the color scheme options given in
%   the file FILENAME.
%
%   SCHEMER_IMPORT(FILENAME, INCLUDEBOOLS) can control whether boolean
%   preferences are included in import (default: FALSE). If INCLUDEBOOLS
%   is set to true, boolean preference options such as whether to
%   highlight autofixable errors, or to show variables with shared scope in
%   a different colour will also be overridden, should they be set in the
%   input file.
%
%   SCHEMER_IMPORT(INCLUDEBOOLS, FILENAME), with a boolean or numeric input
%   followed by a string input, will also work as above because the input
%   order is reversible.
%
%   SCHEMER_IMPORT(INCLUDEBOOLS) with a single boolean input will open the
%   GUI to pick the file, and will load boolean preferences in accordance
%   with INCLUDEBOOLS.
%
%   RET = SCHEMER_IMPORT(...) returns 1 on success, 0 on user
%   cancellation at input file selection screen, -1 on fopen error, and -2
%   on any other error.
%
%   NOTE:
%   The file to import can either be a color scheme file as generated by
%   SCHEMER_EXPORT, or an entire MATLAB preferences file such as the file
%   you will find located at FULLFILE(PREFDIR,'matlab.prf'). This could be
%   a MATLAB preferences file taken from a different computer or previous
%   MATLAB installation. However, if you are importing from a matlab.prf
%   file instead of a color scheme .prf file you should be aware that any
%   colour preferences which have been left as the defaults on preference
%   panels which the user has not visited on the origin system of the
%   matlab.prf file will not be present in the file, and hence not updated
%   on import.
%
%   The MATLAB preference options which will be overwritten by
%   SCHEMER_IMPORT are:
%   - All settings in the Color pane of Preferencs
%   - All colour settings in the Color > Programming Tools pane, but no
%     checkboxes
%   - From Editor/Debugger > Display pane, the following:
%      - Highlight current line (colour, but not whether to)
%      - Right-hand text limit (colour and thickness, but not on/off)
%   - From Editor/Debugger > Language, the syntax highlighting colours for
%     each language.
%
%   Once the current colour preferences are overridden they cannot be
%   undone, so it is recommended that you export your current preferences
%   with SCHEMER_EXPORT before importing a new theme if you think you
%   may wish to revert.
%
%   This is not necessary if you are using the default MATLAB color scheme
%   which ships with the installation, as SCHEMER comes with a copy of the
%   MATLAB default color scheme (default.prf).
%
%   If you wish to revert to the default MATLAB color scheme, it is
%   recommended you import the file default.prf included in this
%   package. This will reset Editor/Debugger>Display colours, colours for
%   syntax highlighting in additional languages, as well as the colours set
%   in the Colors pane. You can also revert the colors by clicking
%   "Restore Default Colors" in the MATLAB preference panel interface, but
%   this will be less effective because there are several panels which set
%   syntax colours and not all of them have a restore button.
%
%   For more details on how to get and set MATLAB preferences with
%   commands, see the following URL.
%   http://undocumentedmatlab.com/blog/changing-system-preferences-programmatically/
%
%   See also SCHEMER_EXPORT, PREFDIR.

% Copyright (c) 2013-2016,  Scott C. Lowe <scott.code.lowe@gmail.com>
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

% Known issues:
%
% 1. Text colour of automatically highlighted variables does not change
%    colour immediately. This is an issue with matlab; if you change the main
%    text colour in the preferences pane, highlighted variables will still
%    have the old text colour until matlab is restarted.
%
% 2. Java exception is thrown when first trying to update the setting
%    Editor.VariableHighlighting.Color. This only happens the first
%    time SCHEMER_IMPORT is run, so the current fix is to catch the error
%    and then try again. However, it might be possible for other Java
%    exceptions get thrown under other mysterious circumstances, which could
%    cause the function to fail.

function varargout = schemer_import(fname, inc_bools)

% ------------------------ Parameters -------------------------------------
SCHEMER_VERSION = 'v1.4.0';

% ------------------------ Input handling ---------------------------------
% ------------------------ Default inputs ---------------------------------
if nargin<2
    inc_bools = false; % Default off, so only override extra options if intended
end
if nargin<1
    fname = []; % Ask user to select file
end
% Input switching
if nargin>=1 && ~ischar(fname) && ~isempty(fname)
    if ~islogical(fname) && ~isnumeric(fname)
        error('Invalid input argument 1');
    end
    if nargin==1
        % First input omitted
        inc_bools = fname;
        fname = [];
    elseif ischar(inc_bools)
        % Inputs switched
        tmp = fname;
        fname = inc_bools;
        inc_bools = tmp;
        clear tmp;
    else
        error('Invalid combination of inputs');
    end
end

% ------------------------ Check for file ---------------------------------
filefilt = ...
   {'*.prf'      , 'MATLAB preference files (*.prf)'   ; ...
    '*.prf;*.txt', 'Text and pref files (*.prf, *.txt)'; ...
    '*'          ,  'All Files'                        };

if ~isempty(fname)
    if ~exist(fname, 'file')
        error('Specified file does not exist');
    end
else
    % Dialog asking for input filename
    % Need to make this dialogue include .txt by default, at least
    [filename, pathname] = uigetfile(filefilt);
    % End if user cancels
    if isequal(filename, 0);
        if nargout>0; varargout{1} = 0; end;
        return;
    end
    fname = fullfile(pathname, filename);
end

% ------------------------ Catch block ------------------------------------
% Somewhat inexplicably, a Java exception is thrown the first time we try
% to set 'Editor.VariableHighlighting.Color'.
% But if we try again immediately, it can be set without any problems.
% The issue is very consistent.
% The solution is to try to set this colour along with all the others,
% catch the exception when it occurs, and then attempt to set all the
% preferences again.
try
    [varargout{1:nargout}] = main(fname, inc_bools);
catch ME
    if ~strcmp(ME.identifier, 'MATLAB:Java:GenericException');
        rethrow(ME);
    end
    % disp('Threw and ignored a Java exception. Retrying.');
    [varargout{1:nargout}] = main(fname, inc_bools);
end

end

% ======================== Main code ======================================
function varargout = main(fname, inc_bools)

% ------------------------ Parameters -------------------------------------
% Names of boolean preferences which should always be imported
names_boolean = {                                   ...
    'ColorsUseSystem'                               ... % Color:    Desktop:    Use system colors
};
% Names of boolean preferences which the user can choose whether to import
names_boolextra = {                                 ...
    'ColorsUseMLintAutoFixBackground'               ... % Color>PT: Analyser:   autofix highlight
    'Editor.VariableHighlighting.Automatic'         ... % Color>PT: Var&fn:     auto highlight
    'Editor.NonlocalVariableHighlighting'           ... % Color>PT: Var&fn:     with shared scope
    'EditorCodepadHighVisible'                      ... % Color>PT: CellDisp:   highlight cells
    'EditorCodeBlockDividers'                       ... % Color>PT: CellDisp:   show lines between cells
    'Editorhighlight-caret-row-boolean'             ... % Editor>Display:       Highlight current line
    'EditorRightTextLineVisible'                    ... % Editor>Display:       Show Right-hand text limit
};
% Names of preferences for which the values are integers
names_integer = {                                   ...
    'EditorRightTextLimitLineWidth'                 ... % Editor>Display:       Right-hand text limit Width
};
% Names of preferences for which the values are strings
%   column 1: name of preference
%   column 2: a regex which the string must match if it is to be exported
%             use '.' or '.+' to allow any non-empty string to be output
%             use  '' or '.*' for anything, including empty strings
%             use '\S' for anything except empty or whitespace-only strings
%             use '^str1|str2|str3$' to allow only a finite set of strings
names_string = {                                    ...
    'Editor.Language.Java.method'                       , ... % Java: Show methods
        '^(none|bold|italic)$'                             ; ...
};
% Names of colour preferences, and their default value if not present in
% the .prf file
%    column 1: name of preference
%    column 2: default value.
%               - Empty if no default,
%               - Integer if specific colour,
%               - String if inherited from another colour setting (which
%                   should appear higher up in the list)
%               - Cell array of strings to take the average colour from
%    column 3: whether a restart is required if this value changes
names_color = { ...
    'ColorsText'                                        , ... % Color:    Desktop:    main text colour
        ''                                              , ...
        false                                               ; ...
    'ColorsBackground'                                  , ... % Color:    Desktop:    main background
        ''                                              , ...
        true                                                ; ...
    'Colors_M_Errors'                                   , ... % Color:    Syntax:     errors
        -65536                                          , ...
        true                                                ; ...
    'Colors_M_Warnings'                                 , ... % Color>PT: Analyser:   warnings
        -27648                                          , ...
        true                                                ; ...
    'Colors_M_Keywords'                                 , ... % Color:    Syntax:     keywords
        'ColorsText'                                    , ...
        false                                               ; ...
    'Colors_M_Comments'                                 , ... % Color:    Syntax:     comments
        {'ColorsText','ColorsBackground'}               , ...
        false                                               ; ...
    'Colors_M_Strings'                                  , ... % Color:    Syntax:     strings
        'ColorsText'                                    , ...
        false                                               ; ...
    'Colors_M_UnterminatedStrings'                      , ... % Color:    Syntax:     unterminated strings
        'Colors_M_Errors'                               , ...
        false                                               ; ...
    'Colors_M_SystemCommands'                           , ... % Color:    Syntax:     system commands
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Colors_HTML_HTMLLinks'                             , ... % Color:    Other:      hyperlinks
        'ColorsText'                                    , ...
        false                                               ; ...
    'Color_CmdWinWarnings'                              , ... % Color:    Other:      Warning messages
        'Colors_M_Warnings'                             , ...
        false                                               ; ...
    'Color_CmdWinErrors'                                , ... % Color:    Other:      Error messages
        'Colors_M_Errors'                               , ...
        false                                               ; ...
    'ColorsMLintAutoFixBackground'                      , ... % Color>PT: Analyser:   autofix
        'ColorsBackground'                              , ...
        false                                               ; ...
    'Editor.VariableHighlighting.Color'                 , ... % Color>PT: Var&fn:     highlight
        'ColorsBackground'                              , ...
        true                                                ; ...
    'Editor.NonlocalVariableHighlighting.TextColor'     , ... % Color>PT: Var&fn:     with shared scope
        'ColorsText'                                    , ...
        false                                               ; ...
    'Editorhighlight-lines'                             , ... % Color>PT: CellDisp:   highlight
        'ColorsBackground'                              , ...
        false                                               ; ...
    'Editorhighlight-caret-row-boolean-color'           , ... % Editor>Display:       Highlight current line Color
        'Editorhighlight-lines'                         , ...
        false                                               ; ...
    'EditorRightTextLimitLineColor'                     , ... % Editor>Display:       Right-hand text limit line Color
        -5723992                                        , ...
        false                                               ; ...

    'Editor.Language.MuPAD.Color.keyword'               , ... % MuPAD: Keywords
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Editor.Language.MuPAD.Color.operator'              , ... % MuPAD: Operators
        'Colors_M_SystemCommands'                       , ...
        false                                               ; ...
    'Editor.Language.MuPAD.Color.block-comment'         , ... % MuPAD: Comments
        'Colors_M_Comments'                             , ...
        false                                               ; ...
    'Editor.Language.MuPAD.Color.option'                , ... % MuPAD: Options
        'Colors_M_UnterminatedStrings'                  , ...
        false                                               ; ...
    'Editor.Language.MuPAD.Color.string'                , ... % MuPAD: Strings
        'Colors_M_Strings'                              , ...
        false                                               ; ...
    'Editor.Language.MuPAD.Color.function'              , ... % MuPAD: System Functions
        {'Colors_M_Keywords','ColorsBackground'}        , ...
        false                                               ; ...
    'Editor.Language.MuPAD.Color.constant'              , ... % MuPAD: Constants
        'Editor.NonlocalVariableHighlighting.TextColor' , ...
        false                                               ; ...

    'Editor.Language.TLC.Color.Colors_M_SystemCommands' , ... % TLC: Commands
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Editor.Language.TLC.Color.Colors_M_Keywords'       , ... % TLC: Macros
        'Colors_M_SystemCommands'                       , ...
        false                                               ; ...
    'Editor.Language.TLC.Color.Colors_M_Comments'       , ... % TLC: Comments
        'Colors_M_Comments'                             , ...
        false                                               ; ...
    'Editor.Language.TLC.Color.string-literal'          , ... % TLC: C Strings
        'Colors_M_Strings'                              , ...
        false                                               ; ...

    'Editor.Language.C.Color.keywords'                  , ... % C/C++: Keywords
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Editor.Language.C.Color.line-comment'              , ... % C/C++: Comments
        'Colors_M_Comments'                             , ...
        false                                               ; ...
    'Editor.Language.C.Color.string-literal'            , ... % C/C++: Strings
        'Colors_M_Strings'                              , ...
        false                                               ; ...
    'Editor.Language.C.Color.preprocessor'              , ... % C/C++: Preprocessor
        'Colors_M_SystemCommands'                       , ...
        false                                               ; ...
    'Editor.Language.C.Color.char-literal'              , ... % C/C++: Characters
        'Colors_M_UnterminatedStrings'                  , ...
        false                                               ; ...
    'Editor.Language.C.Color.errors'                    , ... % C/C++: Bad characters
        'Colors_M_Errors'                               , ...
        false                                               ; ...

    'Editor.Language.Java.Color.keywords'               , ... % Java: Keywords
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Editor.Language.Java.Color.line-comment'           , ... % Java: Comments
        'Colors_M_Comments'                             , ...
        false                                               ; ...
    'Editor.Language.Java.Color.string-literal'         , ... % Java: Strings
        'Colors_M_Strings'                              , ...
        false                                               ; ...
    'Editor.Language.Java.Color.char-literal'           , ... % Java: Characters
        'Colors_M_UnterminatedStrings'                  , ...
        false                                               ; ...

    'Editor.Language.VHDL.Color.Colors_M_Keywords'      , ... % VHDL: Keywords
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Editor.Language.VHDL.Color.operator'               , ... % VHDL: Operators
        'Colors_M_SystemCommands'                       , ...
        false                                               ; ...
    'Editor.Language.VHDL.Color.Colors_M_Comments'      , ... % VHDL: Comments
        'Colors_M_Comments'                             , ...
        false                                               ; ...
    'Editor.Language.VHDL.Color.string-literal'         , ... % VHDL: Strings
        'Colors_M_Strings'                              , ...
        false                                               ; ...

    'Editor.Language.Verilog.Color.Colors_M_Keywords'   , ... % Verilog: Keywords
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Editor.Language.Verilog.Color.operator'            , ... % Verilog: Operators
        'Colors_M_SystemCommands'                       , ...
        false                                               ; ...
    'Editor.Language.Verilog.Color.Colors_M_Comments'   , ... % Verilog: Comments
        'Colors_M_Comments'                             , ...
        false                                               ; ...
    'Editor.Language.Verilog.Color.string-literal'      , ... % Verilog: Strings
        'Colors_M_Strings'                              , ...
        false                                               ; ...

    'Editor.Language.XML.Color.error'                   , ... % XML: Error
        'Colors_M_Errors'                               , ...
        false                                               ; ...
    'Editor.Language.XML.Color.tag'                     , ... % XML: Tag
        'Colors_M_Keywords'                             , ...
        false                                               ; ...
    'Editor.Language.XML.Color.attribute'               , ... % XML: Attribute name
        'Colors_M_UnterminatedStrings'                  , ...
        false                                               ; ...
    'Editor.Language.XML.Color.operator'                , ... % XML: Operator
        'Colors_M_SystemCommands'                       , ...
        false                                               ; ...
    'Editor.Language.XML.Color.value'                   , ... % XML: Attribute value
        'Colors_M_Strings'                              , ...
        false                                               ; ...
    'Editor.Language.XML.Color.comment'                 , ... % XML: Comment
        'Colors_M_Comments'                             , ...
        false                                               ; ...
    'Editor.Language.XML.Color.doctype'                 , ... % XML: DOCTYPE declaration
        'Colors_HTML_HTMLLinks'                         , ...
        false                                               ; ...
    'Editor.Language.XML.Color.ref'                     , ... % XML: Character
        'Colors_M_UnterminatedStrings'                  , ...
        false                                               ; ...
    'Editor.Language.XML.Color.pi-content'              , ... % XML: Processing instruction
        'Colors_HTML_HTMLLinks'                         , ...
        false                                               ; ...
    'Editor.Language.XML.Color.cdata-section'           , ... % XML: CDATA section
        'Editor.NonlocalVariableHighlighting.TextColor' , ...
        false                                               ; ...

    'Editor.Language.VRML.Color.keyword'                , ... % VRML: Keywords
        'Editor.Language.XML.Color.doctype'             , ...
        false                                               ; ...
    'Editor.Language.VRML.Color.node-keyword'           , ... % VRML: Node types
        'Editor.Language.XML.Color.tag'                 , ...
        false                                               ; ...
    'Editor.Language.VRML.Color.field-keyword'          , ... % VRML: Fields
        'Editor.Language.XML.Color.attribute'           , ...
        false                                               ; ...
    'Editor.Language.VRML.Color.data-type-keyword'      , ... % VRML: Data types
        'Editor.Language.XML.Color.cdata-section'       , ...
        false                                               ; ...
    'Editor.Language.VRML.Color.terminal-symbol'        , ... % VRML: Terminal symbols
        'Editor.Language.XML.Color.operator'            , ...
        false                                               ; ...
    'Editor.Language.VRML.Color.comment'                , ... % VRML: Comments
        'Editor.Language.XML.Color.comment'             , ...
        false                                               ; ...
    'Editor.Language.VRML.Color.string'                 , ... % VRML: Strings
        'Editor.Language.XML.Color.value'               , ...
        false                                               ; ...

    'Editor.Language.VRMLX3DV.Color.keyword'            , ... % VRML/X3DV: Keywords
        'Editor.Language.VRML.Color.keyword'            , ...
        false                                               ; ...
    'Editor.Language.VRMLX3DV.Color.node-keyword'       , ... % VRML/X3DV: Node types
        'Editor.Language.VRML.Color.node-keyword'       , ...
        false                                               ; ...
    'Editor.Language.VRMLX3DV.Color.field-keyword'      , ... % VRML/X3DV: Fields
        'Editor.Language.VRML.Color.field-keyword'      , ...
        false                                               ; ...
    'Editor.Language.VRMLX3DV.Color.data-type-keyword'  , ... % VRML/X3DV: Data types
        'Editor.Language.VRML.Color.data-type-keyword'  , ...
        false                                               ; ...
    'Editor.Language.VRMLX3DV.Color.terminal-symbol'    , ... % VRML/X3DV: Terminal symbols
        'Editor.Language.VRML.Color.terminal-symbol'    , ...
        false                                               ; ...
    'Editor.Language.VRMLX3DV.Color.comment'            , ... % VRML/X3DV: Comments
        'Editor.Language.VRML.Color.comment'            , ...
        false                                               ; ...
    'Editor.Language.VRMLX3DV.Color.string'             , ... % VRML/X3DV: Strings
        'Editor.Language.VRML.Color.string'             , ...
        false                                               ; ...
};

verbose = 0;

% ------------------------ Setup ------------------------------------------
if nargout==0
    varargout = {};
else
    varargout = {-2};
end
if inc_bools
    names_boolean = [names_boolean names_boolextra];
end
needs_restart = false;

% ------------------------ Check file seems okay --------------------------
% Read in the contents of the entire file
flestr = fileread(fname);
% Search for occurances of main text colour
txtprf = regexp(flestr, '\sColorsText=(?<pref>[^#\s]+)\s', 'names');
if isempty(txtprf)
    error('Text colour not present in colorscheme file:\n%s', fname);
elseif length(txtprf) > 1
    error('Text colour defined multiple times in colorscheme file:\n%s', fname);
end
% Search for occurances of main background colour
bkgprf = regexp(flestr, '\sColorsBackground=(?<pref>[^#\s]+)\s', 'names');
if isempty(bkgprf)
    error('Background colour not present in colorscheme file:\n%s', fname);
elseif length(bkgprf) > 1
    error('Background colour defined multiple times in colorscheme file:\n%s', fname);
end
% Make sure the main text and background colours are not exactly the same
if strcmp(txtprf.pref, bkgprf.pref)
    error('Main text and background colours are the same in this file:\n%s', fname);
end

% ------------------------ File stuff -------------------------------------
% Open for read access only
fid = fopen(fname, 'r', 'n');
if isequal(fid, -1);
    if nargout>0; varargout{1} = -1; end;
    return;
end
% Add a cleanup object incase of failure
finishup = onCleanup(@() fclose(fid));

% ------------------------ Read and Write ---------------------------------
% Initialise tracker for unset colours
isColorSet = false(size(names_color, 1), 1);
% Loop over prf file
while ~feof(fid)
    % Get one line of preferences/theme file
    l = fgetl(fid);

    % Ignore empty lines and lines which begin with #
    if length(l)<1 || strcmp('#', l(1))
        if verbose; disp('Comment'); end;
        continue;
    end

    % Look for name pref pair, seperated by '='
    %    Must be at begining of string (hence ^ anchor)
    %    Cannot contain comment marker (#)
    n = regexp(l, '^(?<name>[^=#]+)=(?<pref>[^#]+)', 'names');

    % If no match, continue and scan next line
    if isempty(n)
        if verbose; disp('No match'); end;
        continue;
    end

    % Trim whitespace from pref
    n.pref = strtrim(n.pref);

    if ismember(n.name, names_boolean)
        % Deal with boolean type
        switch lower(n.pref)
            case 'btrue'
                % Preference is true
                com.mathworks.services.Prefs.setBooleanPref(n.name, 1);
                if verbose; fprintf('Set bool true %s\n', n.name); end
            case 'bfalse'
                % Preference is false
                com.mathworks.services.Prefs.setBooleanPref(n.name, 0);
                if verbose; fprintf('Set bool false %s\n', n.name); end
            otherwise
                % Shouldn't be anything else
                warning('Bad boolean for %s: %s', n.name, n.pref);
        end

    elseif ismember(n.name, names_integer)
        % Deal with integer type
        if ~strcmpi('I', n.pref(1))
            warning('Bad integer pref for %s: %s', n.name, n.pref);
            continue;
        end
        int = str2double(n.pref(2:end));
        com.mathworks.services.Prefs.setIntegerPref(n.name, int);
        if verbose; fprintf('Set integer %d for %s\n', int, n.name); end

    elseif ismember(n.name,names_string(:, 1))
        % Deal with string type
        if ~strcmpi('S', n.pref(1))
            warning('Bad string pref for %s: %s', n.name, n.pref);
            continue;
        end
        str = n.pref(2:end);
        % Look up which of the preference settings this is
        [~, idx] = ismember(n.name, names_string(:, 1));
        % Check that the setting allowed by the regex it must satisfy
        if isempty(regexp(str, names_string{idx, 2}, ...
                    'start', 'emptymatch'))
            % If not, we can't set the value to be this
            warning('Invalid string for %s: %s', n.name, str);
            continue;
        end
        com.mathworks.services.Prefs.setStringPref(n.name, str);
        if verbose; fprintf('Set string %s for %s\n', str, n.name); end

    elseif ismember(n.name, names_color(:, 1))
        % Deal with colour type (final type to consider)
        if ~strcmpi('C', n.pref(1))
            warning('Bad color for %s: %s', n.name, n.pref);
            continue;
        end
        [~, idx] = ismember(n.name, names_color(:, 1));
        % Get the current setting for this parameter
        previousVal = ...
            com.mathworks.services.Prefs.getColorPref(names_color{idx, 1});
        % Set the colour to the target value
        rgb = str2double(n.pref(2:end));
        jc = java.awt.Color(rgb);
        com.mathworks.services.Prefs.setColorPref(n.name, jc);
        com.mathworks.services.ColorPrefs.notifyColorListeners(n.name);
        if verbose
            fprintf('Set color (%3.f, %3.f, %3.f) for %s\n', ...
                jc.getRed, jc.getGreen, jc.getBlue, n.name);
        end
        % Note that we have allocated this colour
        isColorSet(idx) = true;
        % Check if the colour has changed
        if names_color{idx, 3} && ~isequal(previousVal, jc)
            needs_restart = true;
        end

    else
        % Silently ignore irrelevant preferences
        % (This means you can load a whole matlab.prf file and anything not
        % listed above as relevant to the color scheme will be ignored.)

    end

end

% Check that at least one colour was actually set
if ~any(isColorSet)
    error('Did not find any colour settings in file\n%s', fname);
    if nargout>0; varargout{1} = -2; end;
    return;
end

% For colours which have not been set by the color scheme, we set them from
% a backup
% Get a row vector of indices of all unset colours
unsetColorIndices = find(~isColorSet)';
% Loop over unset colours
for idx=unsetColorIndices
    % Get the backup setting for this colour parameter
    backupVal = names_color{idx, 2};
    % Get the current setting for this parameter
    previousVal = ...
        com.mathworks.services.Prefs.getColorPref(names_color{idx, 1});

    clear jc; % Clear variable

    % Switch based on the type of backup
    if isempty(backupVal)
        % No backup is set
        continue;

    elseif iscell(backupVal)
        % Backup is one of several methods of which involve refactoring one
        % or more other colours
        % Get an RGB value for the colour through whichever method
        if all(cellfun(@ischar, backupVal))
            % Backup is a list of other names to sample and average
            % Initialise a holding matrix
            RGB = nan(numel(backupVal), 3);
            for i=1:numel(backupVal)
                % Load each of the other colours
                jc = com.mathworks.services.Prefs.getColorPref(backupVal{i});
                % Put the R, G, B values into the holding matrix
                RGB(i, 1) = jc.getRed;
                RGB(i, 2) = jc.getGreen;
                RGB(i, 3) = jc.getBlue;
            end
            % Take the average of each RGB value from the other colours
            RGB = mean(RGB);

        elseif length(backupVal)==2
            % Backup is a name of a colour and a scale factor to apply
            jc = com.mathworks.services.Prefs.getColorPref(backupVal{1});
            % Get the R, G, B values
            RGB = [jc.getRed, jc.getGreen, jc.getBlue];
            % Rescale them
            RGB = RGB * backupVal{2};

        else
            error('Bad backup cell for %s', names_color{idx, 1});

        end
        % Turn the RGB value into a Java color object
        % Ensure RGB is integer and does not exceed 255
        RGB = min(255, round(RGB));
        % Convert to a float
        RGB = RGB/255;
        % Make a Java color object for this colour
        jc = java.awt.Color(RGB(1), RGB(2), RGB(3));

    elseif ischar(backupVal)
        % The backup colour is a reference to another colour
        % Look up the colour from the backup reference
        jc = com.mathworks.services.Prefs.getColorPref(backupVal);

    elseif isnumeric(backupVal) && numel(backupVal)==1
        % The backup colour is a specific colour
        % Make a java color object for this specific colour
        jc = java.awt.Color(backupVal);

    else
        error('Bad backup value for %s', names_color{idx, 1});

    end
    % Assign the neglected colour to be this Java colour object from the
    % backup
    com.mathworks.services.Prefs.setColorPref(names_color{idx, 1}, jc);
    com.mathworks.services.ColorPrefs.notifyColorListeners(names_color{idx, 1});

    % Check if the colour has changed
    if names_color{idx, 3} && ~isequal(previousVal, jc)
        needs_restart = true;
    end

end

% ------------------------ Tidy up ----------------------------------------
% fclose(fid); % Don't need to close as it will autoclose
if nargout>0; varargout{1} = 1; end;

if inc_bools
    fprintf('Imported color scheme WITH boolean options from\n%s\n', fname);
else
    fprintf('Imported color scheme WITHOUT boolean options from\n%s\n', fname);
end
if needs_restart
    disp('Some changes require MATLAB to be restarted to be activated.');
end

end

author: scottclowe

repo: matlab-schemer


text:
function area = triangle_area ( xa, ya, xb, yb, xc, yc )

%*****************************************************************************80
%
%% TRIANGLE_AREA computes the signed area of a triangle.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 February 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real XA, YA, XB, YB, XC, YC, the vertices.
%
%    Output, real AREA, the signed area of the triangle.
%
  area = 0.5 * ( ( xb - xa ) * ( yc - ya ) ...
               - ( xc - xa ) * ( yb - ya ) );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [overlap] = check_overlap_ellipses(lnk,circles,dlnk,nglnk,ndxy,image_size,x0,y0,a0,b0,theta0)

ix0 = ceil(x0/dlnk);
iy0 = ceil(y0/dlnk);

ndx1 = ix0 - ndxy; ndx2 = ix0 + ndxy;
ndy1 = iy0 - ndxy; ndy2 = iy0 + ndxy;

ix = mod(ndx1:ndx2,nglnk);ixt = ix==0;ix(ixt)=nglnk;
iy = mod(ndy1:ndy2,nglnk);iyt = iy==0;iy(iyt)=nglnk;

a = lnk(ix,iy);
b = find(a~=0);
overlap = 0;
for k = 1:length(b)
    j = a(b(k));
    x1 = circles(j,1); y1 = circles(j,2);
    a1 = circles(j,3); b1 = circles(j,4);
    theta1 = circles(j,5);

    if x1-x0 > image_size / 2; x1 = x1 - image_size; end;
    if x0-x1 > image_size / 2; x1 = x1 + image_size; end;
    if y1-y0 > image_size / 2; y1 = y1 - image_size; end;
    if y0-y1 > image_size / 2; y1 = y1 + image_size; end;

    overlap = overlap_ellipses(x0,y0,a0,b0,theta0,x1,y1,a1,b1,theta1);
    if overlap == 1; overlap = 1; break; end;
end

author: Sable

repo: mcbench-benchmarks


text:
function [coef]=comp_dgt_fb(f,g,a,M)
%COMP_DGT_FB  Filter bank DGT
%   Usage:  c=comp_dgt_fb(f,g,a,M);
%
%   This is a computational routine. Do not call it directly.
%
%   See help on DGT.

%   AUTHOR : Peter L. Søndergaard.

% Calculate the parameters that was not specified.
L=size(f,1);
N=L/a;
gl=length(g);
W=size(f,2);      % Number of columns to apply the transform to.
glh=floor(gl/2);  % gl-half

% Conjugate the window here.
g=conj(fftshift(g));

coef=zeros(M,N,W,assert_classname(f,g));

% ----- Handle the first boundary using periodic boundary conditions. ---
for n=0:ceil(glh/a)-1

    % Periodic boundary condition.
    fpart=[f(L-(glh-n*a)+1:L,:);...
           f(1:gl-(glh-n*a),:)];

    fg=bsxfun(@times,fpart,g);

    % Do the sum (decimation in frequency, Poisson summation)
    coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2);

end;

% ----- Handle the middle case. ---------------------
for n=ceil(glh/a):floor((L-ceil(gl/2))/a)

  fg=bsxfun(@times,f(n*a-glh+1:n*a-glh+gl,:),g);

  % Do the sum (decimation in frequency, Poisson summation)
  coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2);
end;

% ----- Handle the last boundary using periodic boundary conditions. ---
for n=floor((L-ceil(gl/2))/a)+1:N-1

    % Periodic boundary condition.
    fpart=[f((n*a-glh)+1:L,:);... %   L-n*a+glh elements
           f(1:n*a-glh+gl-L,:)];  %  gl-L+n*a-glh elements

    fg=bsxfun(@times,fpart,g);

    % Do the sum (decimation in frequency, Poisson summation)
    coef(:,n+1,:)=sum(reshape(fg,M,gl/M,W),2);
end;

% --- Shift back again to make it a frequency-invariant system. ---
for n=0:N-1
  coef(:,n+1,:)=circshift(coef(:,n+1,:),n*a-glh);
end;

coef=fft(coef);

% Simple code using a lot of circshifts.
% Move f initially so it lines up with the initial fftshift of the
% window
%f=circshift(f,glh);
%for n=0:N-1
  % Do the inner product.
  %fg=circshift(f,-n*a)(1:gl,:).*gw;

  % Periodize it.
  %fpp=zeros(M,W);
  %for ii=0:gl/M-1
    %  fpp=fpp+fg(ii*M+1:(ii+1)*M,:);
    %end;
%  fpp=sum(reshape(fg,M,gl/M,W),2);

  % Shift back again.
%  coef(:,n+1,:)=circshift(fpp,n*a-glh); %),M,1,W);

%end;

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function b = r8pbu_ml ( n, mu, a_lu, x )

%*****************************************************************************80
%
%% R8PBU_ML multiplies a vector times a matrix that was factored by R8PBU_FA.
%
%  Discussion:
%
%    The R8PBU storage format is for a symmetric positive definite band matrix.
%
%    To save storage, only the diagonal and upper triangle of A is stored,
%    in a compact diagonal format that preserves columns.
%
%    The diagonal is stored in row MU+1 of the array.
%    The first superdiagonal in row MU, columns 2 through N.
%    The second superdiagonal in row MU-1, columns 3 through N.
%    The MU-th superdiagonal in row 1, columns MU+1 through N.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 February 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%    N must be positive.
%
%    Input, integer MU, the number of superdiagonals of the matrix.
%    MU must be at least 0 and no more than N-1.
%
%    Input, real A_LU(MU+1,N), the matrix, as factored by R8PBU_FA.
%
%    Input, real X(N), the vector to be multiplied by A.
%
%    Output, real B(N), the product A * x.
%
  b(1:n) = x(1:n);
%
%  Multiply U * X = Y.
%
  for k = 1 : n

    ilo = max ( 1, k - mu );
    for i = ilo : k - 1
      b(i) = b(i) + a_lu(mu+1+i-k,k) * b(k);
    end

    b(k) = a_lu(mu+1,k) * b(k);

  end
%
%  Multiply L * Y = B.
%
  for k = n : -1 : 1

    jhi = min ( k + mu, n );
    for j = k + 1 : jhi
      b(j) = b(j) + a_lu(mu+1+k-j,j) * b(k);
    end

    b(k) = a_lu(mu+1,k) * b(k);

  end

  return
end


text:
clear;
clc
close all;

%% INTPUS
p = [0; 0];
v = [0;  0];
yaw = deg2rad(45);

%% Epoch 1 Measurements
omgea = [0.5; 0.2; 0.1; -0.1];
t = 0.5;
a = [2  0.1; 5 0.1; 2 -0.05; 0 0];

for i = 1:4
% update heading
lyaw = yaw;
yaw = yaw + omgea(i)*t;

% transform acceration to p frame, get a average value
Cpb_before = [cos(lyaw) -sin(lyaw); sin(lyaw) cos(lyaw)];
Cpb = [cos(yaw) -sin(yaw); sin(yaw) cos(yaw)];
Cpb = (Cpb_before + Cpb) / 2;

% get acceralation in N frame
a_n_frame = Cpb*a(i,:)';

% update velocity
lv = v;
v = v + a_n_frame.*t;
% update position
p = p + (lv +v)*0.5*t;

end

p

author: yandld


text:
function [node,elem] = interfaceUniformrefine(node,elem,interfaceEdge,phi)

%% Construct data structure
totalEdge = uint32(sort([elem(:,[2,3]); elem(:,[3,1]); elem(:,[1,2])],2));
[edge, ~, j] = unique(totalEdge,'rows');
N = size(node,1); NT = size(elem,1); NE = size(edge,1);
elem2edge = uint32(reshape(j,NT,3));

isInterfaceNode = false(N,1);
isInterfaceNode(interfaceEdge(:)) = true;

%% Add new nodes: middle points of all edges
tmpNode = (node(edge(:,1),:)+node(edge(:,2),:))/2;
isNewInterfaceNode = isInterfaceNode(edge(:,1)) & isInterfaceNode(edge(:,2));
a = node(edge(isNewInterfaceNode,1),:) - tmpNode(isNewInterfaceNode,:);
b = node(edge(isNewInterfaceNode,2),:) - tmpNode(isNewInterfaceNode,:);
a = tmpNode(isNewInterfaceNode,:) + [-a(:,2), a(:,1)];
b = tmpNode(isNewInterfaceNode,:) + [-b(:,2), b(:,1)];
tmpNode(isNewInterfaceNode,:) = findintersectbisect(phi,a,b);
node(N+1:N+NE,:) = tmpNode;

edge2newNode = uint32((N+1:N+NE)');

%% Refine each triangle into four triangles as follows
%     3
%    / \
%   5 - 4
%  / \ / \
% 1 - 6 - 2
t = 1:NT;
p(t,1:3) = elem(t,1:3);
p(t,4:6) = edge2newNode(elem2edge(t,1:3));
elem(t,:) = [p(t,1), p(t,6), p(t,5)];
elem(NT+1:2*NT,:) = [p(t,6), p(t,2), p(t,4)];
elem(2*NT+1:3*NT,:) = [p(t,5), p(t,4), p(t,3)];
elem(3*NT+1:4*NT,:) = [p(t,4), p(t,5), p(t,6)];

repo: ifem


text:
function YESNO = isinterval(F)
%ISINTERVAL (overloaded)

F = flatten(F);
if isempty(F.clauses)
    YESNO = 1;
else
    YESNO = 1;
    i = 1;
    while (i<=length(F.clauses)) & YESNO
        Fi = F.clauses{i};
        YESNO =  YESNO & is(Fi.data,'interval');
        i = i+1;
    end
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function g
%here is how one creates a function ("callback") which does something
%(prints the node label) when you click on the node's text in Matlab figure.
%
% Leon Peshkin  http://www.ai.mit.edu/~pesha
%
%draw_graph(...)

     % "gca" is the current "axes" object, parent of all objects in figure
     % "gcbo" is the handle of the object whose callback is being executed
     % "findall" gives handles to all elements of a given type in the figure
text_elms = findall(gca,'Type','text');
for ndx = 1:length(text_elms)
  callbk = 'my_call(str2num(get(gcbo,''String'')))';
  set(text_elms(ndx), 'ButtonDownFcn', callbk);  % assume the node label is a number
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function [C,phi,S12,f,confC,phistd,Cerr]=cohmatrixc(data,params)
% Multi-taper coherency,cross-spectral matrix - continuous process
%
% Usage:
%
% [C,phi,S12,f,confC,phistd,Cerr]=cohmatrixc(data,params)
% Input:
% Note units have to be consistent. See chronux.m for more information.
%       data (in form samples x channels) -- required
%       params: structure with fields tapers, pad, Fs, fpass, err
%       - optional
%           tapers : precalculated tapers from dpss or in the one of the following
%                    forms:
%                    (1) A numeric vector [TW K] where TW is the
%                        time-bandwidth product and K is the number of
%                        tapers to be used (less than or equal to
%                        2TW-1).
%                    (2) A numeric vector [W T p] where W is the
%                        bandwidth, T is the duration of the data and p
%                        is an integer such that 2TW-p tapers are used. In
%                        this form there is no default i.e. to specify
%                        the bandwidth, you have to specify T and p as
%                        well. Note that the units of W and T have to be
%                        consistent: if W is in Hz, T must be in seconds
%                        and vice versa. Note that these units must also
%                        be consistent with the units of params.Fs: W can
%                        be in Hz if and only if params.Fs is in Hz.
%                        The default is to use form 1 with TW=3 and K=5
%
%	        pad		    (padding factor for the FFT) - optional (can take values -1,0,1,2...).
%                    -1 corresponds to no padding, 0 corresponds to padding
%                    to the next highest power of 2 etc.
%			      	 e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT
%			      	 to 512 points, if pad=1, we pad to 1024 points etc.
%			      	 Defaults to 0.
%           Fs   (sampling frequency) - optional. Default 1.
%           fpass    (frequency band to be used in the calculation in the form
%                                   [fmin fmax])- optional.
%                                   Default all frequencies between 0 and Fs/2
%           err  (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars
%                                   [0 p] or 0 - no error bars) - optional. Default 0.
% Output:
%       C (magnitude of coherency frequency x channels x channels)
%       phi (phase of coherency frequency x channels x channels)
%       S12 (cross-spectral matrix frequency x channels x channels)
%       f (frequencies)
%       confC (confidence level for C at 1-p %) - only for err(1)>=1
%       phistd - theoretical/jackknife (depending on err(1)=1/err(1)=2) standard deviation for phi
%                Note that phi + 2 phistd and phi - 2 phistd will give 95% confidence
%                bands for phi - only for err(1)>=1
%       Cerr  (Jackknife error bars for C - use only for Jackknife - err(1)=2)

if nargin < 1; error('need data'); end;
if nargin < 2; params=[]; end;
[N,Ch]=size(data);
if Ch==1; error('Need at least two channels of data'); end;
[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);
clear trialave params
if nargout > 6 && err(1)~=2;
    error('Cerr computed only for Jackknife. Correct inputs and run again');
end;
if nargout >= 4 && err(1)==0;
%   Errors computed only if err(1) is nonzero. Need to change params and run again.
    error('When errors are desired, err(1) has to be non-zero.');
end;
nfft=max(2^(nextpow2(N)+pad),N);
[f,findx]=getfgrid(Fs,nfft,fpass);
tapers=dpsschk(tapers,N,Fs); % check tapers
J=mtfftc(data,tapers,nfft,Fs);
J=J(findx,:,:);
if err(1)==0;
     [C,phi,S12]=cohmathelper(J,err);
elseif err(1)==1;
     [C,phi,S12,confC,phistd]=cohmathelper(J,err);
elseif err(1)==2;
     [C,phi,S12,confC,phistd,Cerr]=cohmathelper(J,err);
end

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function square_domain
%square_domain   square domain Q2 grid generator
%   square_domain;
%
% grid defining data is saved to the file: square_grid.mat
%   IFISS function: DJS; 7 May 2006.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
fprintf('\n\nGrid generation for unit square  domain.\n')
nc=default('grid parameter: 3 for underlying 8x8 grid (default is 16x16)',4);
if nc<2, error('illegal parameter choice, try again.'), end
grid_type=default('uniform/stretched grid (1/2) (default is uniform)',1);
n=2^nc; np=n/2; nq=n/4;
%
%% compute (x,y) coordinates of vertices
% y-direction
if grid_type==2
   hmax=nc/(2^(nc+1));
   x1=-1;x2=-2*hmax;x3=2*hmax;x4=1;nx1=2^(nc-1)-1;nx2=2;nx3=2^(nc-1)-1;
   y1=-1;y2=-2*hmax;y3=2*hmax;y4=1;ny1=2^(nc-1)-1;ny2=2;ny3=2^(nc-1)-1;
   y=subint(y1,y2,y3,y4,ny1,ny2,ny3);
   stretch=(y(3)-y(2))/(y(2)-y(1));
   left=-1;
   x=y;
else
   square_type=default('[0,1] or [-1,1] square (enter 1/2) (default is [-1,1])',2);
   yy=[1/np:1/np:1];
   ypos=[0,yy];
   yneg=-yy(length(yy):-1:1);
   y=[yneg,ypos]';
   left=-1;
   if square_type==1
      y=[0:1/(2*np):1]'; left=0;
   end
   x=y;
   end
%
%% compute biquadratic element coordinates
nvtx=(n+1)*(n+1);
[X,Y]=meshgrid(x,y);
xx=reshape(X',nvtx,1);
yy=reshape(Y',nvtx,1);
xy=[xx(:),yy(:)];
%
kx = 1;
ky = 1;
mel=0;
for j=1:np
   for i=1:np
      mref=(n+1)*(ky-1)+kx;
      mel=mel+1;
      nvv(1) = mref;
      nvv(2) = mref+2;
      nvv(3) = mref+2*n+4;
      nvv(4) = mref+2*n+2;
      nvv(5) = mref+1;
      nvv(6) = mref+n+3;
      nvv(7) = mref+2*n+3;
      nvv(8)=  mref+n+1;
      nvv(9)=  mref+n+2;
      mv(mel,1:9)=nvv(1:9);
      kx = kx + 2;
   end
   ky = ky + 2;
   kx = 1;
end
%
%% compute boundary vertices and edges
% four boundary edges
k1=find( xy(:,2)==left );
e1=[]; for k=1:mel, if any(mv(k,5)==k1), e1=[e1,k]; end, end
ef1=ones(size(e1));
%
k2=find( xy(:,1)==1  & xy(:,2)<=1   & xy(:,2) >left);
e2=[]; for k=1:mel, if any(mv(k,6)==k2), e2=[e2,k]; end, end
ef2=2*ones(size(e2));
%
k3=find( xy(:,2)==1  & xy(:,1)<1   & xy(:,1) >left);
e3=[]; for k=1:mel, if any(mv(k,7)==k3), e3=[e3,k]; end, end
ef3=3*ones(size(e3));
%
k4=find( xy(:,1)==left & xy(:,2)<=1   & xy(:,2) >left );
e4=[]; for k=1:mel, if any(mv(k,8)==k4), e4=[e4,k]; end, end
ef4=4*ones(size(e4));
%
bound=sort([k1;k2;k3;k4]);
mbound=[e1',ef1';e2',ef2';e3',ef3';e4',ef4'];
%
%
outbc=1;
gohome
cd datafiles
save square_grid.mat mv xy bound mbound grid_type outbc x y
clear
return


text:
function varargout=lpcpp2pz(varargin)
%
% For calling details please see v_lpcpp2pz.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_lpcpp2pz.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: lpcpp2pz.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_lpcpp2pz(varargin{:});
else
    v_lpcpp2pz(varargin{:});
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function [RNew, phi, psi, alphaNew, gammaOld, gammaNew] = ...
        computeGammaMultipleSinus(...
        ROld, iOrder, crossCorrelationVectors, a, phi, psi, gammaOld, ...
        gammaNew, alphaOld, hankelMatrixIsAdded, dcIsIncluded)

    nPitches = length(a);
    RNew = computeRowsOfToeplitzHankelMatrix(iOrder, iOrder, ...
        crossCorrelationVectors, hankelMatrixIsAdded, dcIsIncluded);
    lambda = a-sum(ROld.*phi,1);
    mu = -sum(ROld.*psi,1);
    phi = [phi;zeros(1,nPitches)]+(ones(iOrder-1,1)*lambda).*gammaNew;
    psi = [psi;zeros(1,nPitches)]+(ones(iOrder-1,1)*mu).*gammaNew;
    alphaNew = sum(RNew(1:end-1,:).*gammaNew,1);
    b = (ones(iOrder-1,1)*(alphaOld-alphaNew)).*gammaNew+...
        [zeros(1,nPitches);gammaNew(1:iOrder-2,:)]+...
        [gammaNew(2:end,:);zeros(1,nPitches)]-...
        [gammaOld(1:iOrder-2,:);zeros(1,nPitches)]+...
        (ones(iOrder-1,1)*psi(end,:)).*phi-...
        (ones(iOrder-1,1)*phi(end,:)).*psi;
    nu = sum(RNew(1:end-1,:).*b)./gammaNew(end,:);
    gammaOld = gammaNew;
    gammaNew = nan(iOrder,nPitches);
    gammaNew(iOrder,:) = 1./(nu+RNew(iOrder,:));
    gammaNew(1:iOrder-1,:) = (ones(iOrder-1,1)*...
        (gammaNew(iOrder,:)./gammaOld(end,:))).*b;

end

author: LimingShi


text:
function [map] = addColourNode(map, rxnList, colour)
% Add colour to all metabolites linked to a list of reaction names.
% If no colour is specified as input, 'RED' will be used by default.
% Complementary function of changeRxnColorAndWidth.m
%
% USAGE:
%
%   [map] = addColourNode(map, rxnList, color)
%
% INPUTS:
%    map:           A parsed model structure generated by
%                   'transformXML2Map' function
%    rxnlist:       List of reactions which nodes have to be coloured
%
% OPTIONAL INPUT:
%    color:         Color string. Default color being 'RED'
%
% OUTPUT:
%    map:           New parsed file with the colored entities linked
%                   to reactions list given as input
%
% .. Authors:
%       - J.modamio 18/07/2017. LCSB, Belval, Luxembourg.
%       - N.Sompairac - Institut Curie, Paris, 11/10/2017.

    if nargin < 3
        colour = 'RED';
    end

    colors = createColorsMap();
    index = find(ismember(map.rxnName, rxnList));  % find index of reactions

    % Change colour base reactants
    baseR = map.rxnBaseReactantAlias(index, 1);
    for i = 1:length(baseR)
        a = baseR{i};
        id = ismember(map.molAlias, a);
        map.molColor(id) = {colors(colour)};
    end

    % Change colour of base products
    baseP = map.rxnBaseProductAlias(index, 1);
    for i = 1:length(baseP)
        a = baseP{i};
        id = ismember(map.molAlias, a);
        map.molColor(id) = {colors(colour)};
    end

    % Change color of secondary reactants
    react = map.rxnReactantAlias(index, 1);
    for i = 1:length(react)
        a = react{i};
        id = ismember(map.molAlias, a);
        map.molColor(id) = {colors(colour)};
    end

    % Change color of secondary products
    product = map.rxnProductAlias(index, 1);
    for i = 1:length(product)
        a = product{i};
        id = ismember(map.molAlias, a);
        map.molColor(id) = {colors(colour)};
    end

    % Change color of modificators
    modif = map.rxnModAlias(index, 1);
    for i = 1:length(modif)
        a = modif{i};
        id = ismember(map.molAlias, a);
        map.molColor(id) = {colors(colour)};
    end

end

author: opencobra

repo: cobratoolbox


text:
classdef pbNotify
    %pbNotify sends a push notification to users.
    %   To use this class you will need to signup for a Push Bullet account. See: https://www.pushbullet.com/
    %
    %   pbO = pbNotify(<accessToken>)
    %   Once you signed up for an account, you will need your access token to create a pbNotifier object. https://www.pushbullet.com/account
    %
    %   ret = pbO.notify(<Message>)
    %   This shall push the message to the devices registered in your account and return a json string.

    properties
        accessToken='';
        computer='';
    end

    methods
        function o=pbNotify(token)
            o.accessToken=token;
            if ispc
                o.computer = getenv('COMPUTERNAME');
            else
                o.computer = getenv('HOSTNAME');
            end
        end
        function r=notify(o,message)
            r=urlread('https://api.pushbullet.com/v2/pushes','Authentication','Basic','username',o.accessToken, ...
                      'password','','timeout',35,'post',{'type','note','title',['MATLAB:',o.computer],'body',message});
        end
    end

end

author: thomas-koehler

repo: SupER


text:
function CM = yaron_colormap(n)
  CM = hex2rgb([
  'ce517e'
  'd16486'
  'd47890'
  'd88a95'
  'dd9c9e'
  'e0ada7'
  'e5beaf'
  'ead1ba'
  'efe2c3'
  'e6e6c4'
  'cfd7bc'
  'b9ccb5'
  'a4c2af'
  '8db7a8'
  '77aca1'
  '54a49e'
  '309c96'
  '159592'
  ]);
  if nargin>=1
    CM = interp1(linspace(0,1,size(CM,1))',CM,linspace(0,1,n)','spline');
  end
end

author: alecjacobson

repo: gptoolbox


text:
function pass = test_uplus( pref )
% This tests the basic arithmetic operations on chebfun2 objects.

if ( nargin < 1 )
    pref = chebfunpref;
end
tol = 1e5 * pref.cheb2Prefs.chebfun2eps;
j = 1;

D = [-1 1 -1 1; -2 2 -2 2; -1 pi 0 2*pi];

for r = 1 : size(D,1)
    f = chebfun2(@(x,y) cos(x.*y), D(r,:));

    uplusF = f;
    tolr = norm(D(r,:),inf)*tol;

    pass(j) = ( norm( f - uplusF ) < tolr ); j = j + 1;
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
clear;
clc
close all;
addpath('../../library/nav_lib');

%% 用户真实坐标及接受机钟差(m)
true_user_states = [4245849, -2451342, 4113840, 1000000]';

%% 卫星位置
sat = zeros(3,5);
sat(:,1) = [21630742.37 -7872946.37 13290000]';
sat(:,2) = [9799722.428 -11678854.4 21773061.34]';
sat(:,3) = [15014045.82 2647381.37 21773061.34]';
sat(:,4) = [17020279.96 -20283979.8 2316599.642]';
sat(:,5) = [26076581.77 4598004.93 2316599.642]';
pos = zeros(4,1);
dp = 0;

%% presduo range
pr = vecnorm(sat - true_user_states(1:3)) + true_user_states(4) ;
[pos, dp, G] = ch_gpsls(pos, sat,  pr);

pos
dp


text:
function file_name_new = file_name_ext_swap ( file_name, ext )

%*****************************************************************************80
%
%% FILE_NAME_EXT_SWAP replaces the current "extension" of a file name.
%
%  Discussion:
%
%    The "extension" of a filename is the string of characters
%    that appears after the LAST period in the name.  A file
%    with no period, or with a period as the last character
%    in the name, has a "null" extension.
%
%  Example:
%
%          Input           Output
%    ================     =============
%    FILE_NAME    EXT     FILE_NAME_NEW
%
%    bob.for      obj     bob.obj
%    bob.bob.bob  txt     bob.bob.txt
%    bob          yak     bob.yak
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 August 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, character FILE_NAME(*), a file name.
%    On output, the extension of the file has been changed.
%
%    Input, character EXT(*), the extension to be used on the output
%    copy of FILE_NAME, replacing the current extension if any.
%
%    Output, character FILE_NAME_NEW(*), a copy of the input file name,
%    with the new extension.
%
  file_name_len = length ( file_name );

  ext_len = length ( ext );

  period = file_name_len + 1;

  for i = file_name_len : -1 : 1
    if ( file_name(i:i) == '.' )
      period = i;
      break
    end
  end

  file_name_new(1:period-1) = file_name(1:period-1);
  file_name_new(period) = '.';
  file_name_new(period+1:period+ext_len) = ext(1:ext_len);

  return
end


text:
function [Q, R] = gs_c(A)
%GS_C    Classical Gram-Schmidt QR factorization.
%        [Q, R] = GS_C(A) uses the classical Gram-Schmidt method to compute the
%        factorization A = Q*R for m-by-n A of full rank,
%        where Q is m-by-n with orthonormal columns and R is n-by-n.

%        Reference:
%        N. J. Higham, Accuracy and Stability of Numerical Algorithms,
%        Second edition, Society for Industrial and Applied Mathematics,
%        Philadelphia, PA, 2002; sec 19.8.

[m, n] = size(A);
Q = zeros(m,n);
R = zeros(n);

for j=1:n
    R(1:j-1,j) = Q(:,1:j-1)'*A(:,j);
    temp = A(:,j) - Q(:,1:j-1)*R(1:j-1,j);
    R(j,j) = norm(temp);
    Q(:,j) = temp/R(j,j);
end


text:
%% TriScatteredInterp_ND
% Below is a demonstration of the features of the |TriScatteredInterp_ND| function

%%
clear; close all; clc;

%% Syntax
% |[DI]=TriScatteredInterp_ND(DT,D,XI,InterpMethod);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function [sys,prn]=satsys(sat)

global glc
sys=0;

if sat<=0||sat>glc.MAXSAT
    sat=0;
elseif sat<=glc.NSATGPS
    sys=glc.SYS_GPS; sat=sat+glc.MINPRNGPS-1;
elseif (sat-glc.NSATGPS)<=glc.NSATGLO
    sys=glc.SYS_GLO; sat=(sat-glc.NSATGPS)+glc.MINPRNGLO-1;
elseif (sat-glc.NSATGPS-glc.NSATGLO)<=glc.NSATGAL
    sys=glc.SYS_GAL; sat=(sat-glc.NSATGPS-glc.NSATGLO)+glc.MINPRNGAL-1;
elseif (sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL)<=glc.NSATBDS
    sys=glc.SYS_BDS; sat=(sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL)+glc.MINPRNBDS-1;
elseif (sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL-glc.NSATBDS)<=glc.NSATQZS
    sys=glc.SYS_QZS; sat=(sat-glc.NSATGPS-glc.NSATGLO-glc.NSATGAL-glc.NSATBDS)+glc.MINPRNQZS-1;
else
    sat=0;
end

prn=sat;

return

repo: GINav


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

    enumeration
        UseParallel('Compute Gradients in Parallel',true)
        DoNotUseParallel('Compute Gradients in Serial',false);
    end

    properties
        name char = '';
        optionVal(1,1) logical = true
    end

    methods
        function obj = FminconUseParallelEnum(name, optionVal)
            obj.name = name;
            obj.optionVal = optionVal;
        end
    end

    methods(Static)
        function listBoxStr = getListBoxStr()
            m = enumeration('FminconUseParallelEnum');
            [~,I] = sort({m.name});
            listBoxStr = {m(I).name};
        end

        function [ind, enum] = getIndForName(name)
            m = enumeration('FminconUseParallelEnum');
            [~,I] = sort({m.name});
            m = m(I);
            ind = find(ismember({m.name},name),1,'first');
            enum = m(ind);
        end

        function [enum, ind] = getEnumForListboxStr(nameStr)
            m = enumeration('FminconUseParallelEnum');
            ind = find(ismember({m.name},nameStr),1,'first');
            enum = m(ind);
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
filename='ImprovedBridge_hexahedra';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = [1];
constraint = {'volume'};
optimizer = 'AlternatingPrimalDual';
optimizerUnconstrained = 'SLERP';
designVariable = 'LevelSet';
incrementFactor = 1;
filterType = 'P1';
constraint_case = 'INEQUALITY';
line_search_initiator = 'STANDARD';
showBC = true;

nsteps = 10;
Vfrac_final = 0.1;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

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

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function test_suite = test_createDurerPolyheron
%TEST_CREATEDURERPOLYHERON  Test case for the file createDurerPolyheron
%
%   Test case for the file createDurerPolyheron

%   Example
%   test_createDurerPolyheron
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2012-07-31,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2012 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function test_Simple(testCase) %#ok<*DEFNU>
% Test call of function without argument
[v, f] = createDurerPolyhedron;
testCase.assertEqual([12 3], size(v));
testCase.assertEqual(8, length(f));

function test_VEF(testCase)
% Test call of function without argument
[v, e, f] = createDurerPolyhedron;
testCase.assertEqual([12 3], size(v));
testCase.assertEqual([18 2], size(e));
testCase.assertEqual(8, length(f));

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function [boxes, scores, num_candidates] = read_candidates_mat(dirname, img_id, subdirlen, coco)
  if nargin < 3
    subdirlen = 4;
  end
  if nargin < 4
    coco = false;
  end

  if coco
    subdirlen1 = 14;
    subdir1 = img_id(1:subdirlen1);
    subdirlen2 = 22;
    subdir2 = img_id(1:subdirlen2);
    subdir = fullfile(subdir1, subdir2);
  else
    subdir = img_id(1:subdirlen);
  end
  matfile = fullfile(dirname, subdir, sprintf('%s.mat', img_id));

  % default value
  num_candidates = 10000;

  load(matfile);
end

author: hosang

repo: detection-proposals


text:
function [err,testShift] = CMFfitOneMeridianFun( testShift, uDistTemplate, mnPhTemplate, uDist, mnPh)
%
% AUTHOR:  Wandell, Brewer
% PURPOSE:
%
%   The CMF data have an observed relative uDist and complex phase (mnPh).
% The absolute value of the distance, however, is not meaningful.
% We can add or subtract a constant from each of the meridia because
% they don't start in exactly the same place.
%
%   This routine slides the distance of the data to be in
% register with a template function.  Usually one of the
% the data sets themselves is used as the template.
%
% We search for a distance shift (testShift) that
% brings the data into register with the template data.
%
% DEBUG:
% template = meridia(1);
% testShift = 3; uDist = meridia(2).uDist; mnPh = meridia(2).mnPh;
% CMFfitOneMeridianFun( testShift, template, uDist,mnPh)

warning('Not used, we think.');

% Interpolate the test data set using the testShift parameter
% This uses the existing data to predict the values at the template
% The mnPh data are complex.
%
predicted = interp1(uDist + testShift, mnPh, uDistTemplate, 'linear');
% try adding 'extrap' option to interp1?

% A few of the data may be out of range.  These produce NaNs in the
% interpolation.  Count these;  if there are too many send a big error
% back.  Otherwise, send back the norm difference, but accounting for
% the number of points used to do the fit.
% I wish I had a reason for using 0.65.
%
l = ~isnan(predicted);
if sum(l) > 0.65*length(uDistTemplate)
   err = norm(predicted(l) - mnPhTemplate(l))/sqrt(length(l));
else
   err = 1000;  % A large number
end

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function R = apprRot(Ra)
%R = apprRot(Ra)

% should not change due to introduction of c

i1 = 0.5; i2 = 0.5;
U = Ra(1,:);
V = Ra(2,:);
un = norm(U);
vn = norm(V);
Un = U/un;
Vn = V/vn;

vp = Un*Vn';
up = Vn*Un';

Vc = Vn-vp*Un;  Vc = Vc/norm(Vc);
Uc = Un-up*Vn;  Uc = Uc/norm(Uc);

Ua = i1*Un+i2*Uc; Ua = Ua/norm(Ua);
Va = i1*Vn+i2*Vc; Va = Va/norm(Va);

R = [Ua;Va;cross(Ua,Va)];
if det(R)<0, R(3,:) = -R(3,:); end;

end

repo: CategoryShapes


text:
function y=pulse(t,f,w,Ein)
% unit pulse; starts at f ends at w; pulsewidth = w - f
% amplitude when on = Ein
if t < f | t > w
   y=0;
else
   y=Ein;
end

author: Sable

repo: mcbench-benchmarks


text:
% Loads the true SST fields from the HadGem1 runs, the input
% is the name of the file name with the training data
%
function [ true_sst, Itest, Itrain, time, train_sst ] = ...
    load_testdata( dataset )

switch dataset
case 'hadsst2d1'
    datafile = 'run1_ts_A1_5x5';
case 'hadsst2d2'
    datafile = 'run2_ts_A1_5x5';
end

% Load training data
datapath = metoffice_get_path();
train = load( [ datapath, dataset ], 'time', 'sst' );
%train = load( [ datapath '/RecTest/DATASETS/' dataset ], 'time', 'sst' );
Itrain = ~isnan( train.sst );

% Load test data
testpath = metoffice_get_testpath();
hadgem = load( [ testpath, datafile ], 'sst', 'time' );
% $$$ hadgem = load( [ datapath '/HadGem1/' datafile ], 'sst', 'time' );

[ time, Ihadsst, Ihadgem ] = intersect( train.time, hadgem.time );

% Take the time period included in the test data
true_sst = hadgem.sst(:,Ihadgem);

% Load mask
[ mask, lat, lon ] = metoffice_get_mask( dataset );

Itest = logical( ones(size(true_sst)) );
Itest( ~mask(:), : ) = 0;
Itest( Itrain ) = 0;
% Possible missing data in model runs
Itest( isnan(true_sst) ) = 0;
% Remove ice from test data
Iice = true_sst < -1.8;
Itest(Iice) = 0;

% Remove Caspian sea (detached area with no observations)
mask_Caspian = zeros(length(lat),length(lon));
%          lat  lon
ilat = find(lat==47.5);
ilon = find(lon==52.5);
mask_Caspian( ilat, ilon ) = 1;
mask_Caspian( ilat+1, ilon ) = 1;
mask_Caspian( ilat+2, ilon ) = 1;
mask_Caspian( ilat, ilon-1 ) = 1;
mask_Caspian = reshape( mask_Caspian, length(lat)*length(lon), 1 );
%lmap( mask_Caspian, lat, lon );

Itest( logical(mask_Caspian), : ) = 0;

%true_sst(~(Itest | Itrain)) = NaN;

if nargout >= 5
    train_sst = train.sst(:,Ihadsst);
end

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab