text:
% complete pipeline for calcium imaging data pre-processing
clear;
addpath(genpath('../NoRMCorre'));               % add the NoRMCorre motion correction package to MATLAB path
gcp;                                            % start a parallel engine
foldername = '';
         % folder where all the files are located.
filetype = 'tif'; % type of files to be processed
        % Types currently supported .tif/.tiff, .h5/.hdf5, .raw, .avi, and .mat files
files = subdir(fullfile(foldername,['*.',filetype]));   % list of filenames (will search all subdirectories)
FOV = size(read_file(files(1).name,1,1));
numFiles = length(files);

%% motion correct (and save registered h5 files as 2d matrices (to be used in the end)..)
% register files one by one. use template obtained from file n to
% initialize template of file n + 1;

motion_correct = true;                            % perform motion correction
non_rigid = true;                                 % flag for non-rigid motion correction
output_type = 'h5';                               % format to save registered files

if non_rigid; append = '_nr'; else; append = '_rig'; end        % use this to save motion corrected files

options_mc = NoRMCorreSetParms('d1',FOV(1),'d2',FOV(2),'grid_size',[128,128],'init_batch',200,...
                'overlap_pre',32,'mot_uf',4,'bin_width',200,'max_shift',24,'max_dev',8,'us_fac',50,...
                'output_type',output_type);

template = [];
col_shift = [];
for i = 1:numFiles
    fullname = files(i).name;
    [folder_name,file_name,ext] = fileparts(fullname);
    output_filename = fullfile(folder_name,[file_name,append,'.',output_type]);
    options_mc = NoRMCorreSetParms(options_mc,'output_filename',output_filename,'h5_filename','','tiff_filename',''); % update output file name
    if motion_correct
        [M,shifts,template,options_mc,col_shift] = normcorre_batch_even(fullname,options_mc,template);
        save(fullfile(folder_name,[file_name,'_shifts',append,'.mat']),'shifts','-v7.3');           % save shifts of each file at the respective folder
    else    % if files are already motion corrected convert them to h5
        convert_file(fullname,'h5',fullfile(folder_name,[file_name,'_mc.h5']));
    end
end

%% downsample h5 files and save into a single memory mapped matlab file

if motion_correct
    registered_files = subdir(fullfile(foldername,['*',append,'.',output_type]));  % list of registered files (modify this to list all the motion corrected files you need to process)
else
    registered_files = subdir(fullfile(foldername,'*_mc.h5'));
end

fr = 30;                                         % frame rate
tsub = 5;                                        % degree of downsampling (for 30Hz imaging rate you can try also larger, e.g. 8-10)
ds_filename = [foldername,'/ds_data.mat'];
data_type = class(read_file(registered_files(1).name,1,1));
data = matfile(ds_filename,'Writable',true);
data.Y  = zeros([FOV,0],data_type);
data.Yr = zeros([prod(FOV),0],data_type);
data.sizY = [FOV,0];
F_dark = Inf;                                    % dark fluorescence (min of all data)
batch_size = 2000;                               % read chunks of that size
batch_size = round(batch_size/tsub)*tsub;        % make sure batch_size is divisble by tsub
Ts = zeros(numFiles,1);                          % store length of each file
cnt = 0;                                         % number of frames processed so far
tt1 = tic;
for i = 1:numFiles
    name = registered_files(i).name;
    info = h5info(name);
    dims = info.Datasets.Dataspace.Size;
    ndimsY = length(dims);                       % number of dimensions (data array might be already reshaped)
    Ts(i) = dims(end);
    Ysub = zeros(FOV(1),FOV(2),floor(Ts(i)/tsub),data_type);
    data.Y(FOV(1),FOV(2),sum(floor(Ts/tsub))) = zeros(1,data_type);
    data.Yr(prod(FOV),sum(floor(Ts/tsub))) = zeros(1,data_type);
    cnt_sub = 0;
    for t = 1:batch_size:Ts(i)
        Y = read_file(name,t,min(batch_size,Ts(i)-t+1));
        F_dark = min(nanmin(Y(:)),F_dark);
        ln = size(Y,ndimsY);
        Y = reshape(Y,[FOV,ln]);
        Y = cast(downsample_data(Y,'time',tsub),data_type);
        ln = size(Y,3);
        Ysub(:,:,cnt_sub+1:cnt_sub+ln) = Y;
        cnt_sub = cnt_sub + ln;
    end
    data.Y(:,:,cnt+1:cnt+cnt_sub) = Ysub;
    data.Yr(:,cnt+1:cnt+cnt_sub) = reshape(Ysub,[],cnt_sub);
    toc(tt1);
    cnt = cnt + cnt_sub;
    data.sizY(1,3) = cnt;
end
data.F_dark = F_dark;
%% now run CNMF on patches on the downsampled file, set parameters first

sizY = data.sizY;                       % size of data matrix
patch_size = [40,40];                   % size of each patch along each dimension (optional, default: [32,32])
overlap = [8,8];                        % amount of overlap in each dimension (optional, default: [4,4])

patches = construct_patches(sizY(1:end-1),patch_size,overlap);
K = 7;                                            % number of components to be found
tau = 8;                                          % std of gaussian kernel (half size of neuron)
p = 2;                                            % order of autoregressive system (p = 0 no dynamics, p=1 just decay, p = 2, both rise and decay)
merge_thr = 0.8;                                  % merging threshold
sizY = data.sizY;

options = CNMFSetParms(...
    'd1',sizY(1),'d2',sizY(2),...
    'deconv_method','constrained_foopsi',...    % neural activity deconvolution method
    'p',p,...                                   % order of calcium dynamics
    'ssub',2,...                                % spatial downsampling when processing
    'tsub',2,...                                % further temporal downsampling when processing
    'merge_thr',merge_thr,...                   % merging threshold
    'gSig',tau,...
    'max_size_thr',300,'min_size_thr',10,...    % max/min acceptable size for each component
    'spatial_method','regularized',...          % method for updating spatial components
    'df_prctile',50,...                         % take the median of background fluorescence to compute baseline fluorescence
    'fr',fr/tsub,...                            % downsamples
    'space_thresh',0.35,...                     % space correlation acceptance threshold
    'min_SNR',2.0,...                           % trace SNR acceptance threshold
    'cnn_thr',0.2,...                           % cnn classifier acceptance threshold
    'nb',1,...                                  % number of background components per patch
    'gnb',3,...                                 % number of global background components
    'decay_time',0.5...                         % length of typical transient for the indicator used
    );

%% Run on patches (the main work is done here)

[A,b,C,f,S,P,RESULTS,YrA] = run_CNMF_patches(data.Y,K,patches,tau,0,options);  % do not perform deconvolution here since
                                                                               % we are operating on downsampled data
%% compute correlation image on a small sample of the data (optional - for visualization purposes)
Cn = correlation_image_max(data,8);

%% classify components

rval_space = classify_comp_corr(data,A,C,b,f,options);
ind_corr = rval_space > options.space_thresh;           % components that pass the correlation test
                                                        % this test will keep processes

%% further classification with cnn_classifier
try  % matlab 2017b or later is needed
    [ind_cnn,value] = cnn_classifier(A,FOV,'cnn_model',options.cnn_thr);
catch
    ind_cnn = true(size(A,2),1);                        % components that pass the CNN classifier
end

%% event exceptionality

fitness = compute_event_exceptionality(C+YrA,options.N_samples_exc,options.robust_std);
ind_exc = (fitness < options.min_fitness);

%% select components

keep = (ind_corr | ind_cnn) & ind_exc;

%% run GUI for modifying component selection (optional, close twice to save values)
% run_GUI = false;
% if run_GUI
%     Coor = plot_contours(A,Cn,options,1); close;
%     GUIout = ROI_GUI(A,options,Cn,Coor,keep,ROIvars);
%     options = GUIout{2};
%     keep = GUIout{3};
% end

%% view contour plots of selected and rejected components (optional)
throw = ~keep;
Coor_k = [];
Coor_t = [];
figure;
    ax1 = subplot(121); plot_contours(A(:,keep),Cn,options,0,[],Coor_k,[],1,find(keep)); title('Selected components','fontweight','bold','fontsize',14);
    ax2 = subplot(122); plot_contours(A(:,throw),Cn,options,0,[],Coor_t,[],1,find(throw));title('Rejected components','fontweight','bold','fontsize',14);
    linkaxes([ax1,ax2],'xy')

%% keep only the active components

A_keep = A(:,keep);
C_keep = C(keep,:);

%% extract residual signals for each trace

if exist('YrA','var')
    R_keep = YrA(keep,:);
else
    R_keep = compute_residuals(data,A_keep,b,C_keep,f);
end

%% extract fluorescence on native temporal resolution

options.fr = options.fr*tsub;                   % revert to origingal frame rate
N = size(C_keep,1);                             % total number of components
T = sum(Ts);                                    % total number of timesteps
C_full = imresize(C_keep,[N,T]);                % upsample to original frame rate
R_full = imresize(R_keep,[N,T]);                % upsample to original frame rate
F_full = C_full + R_full;                       % full fluorescence
f_full = imresize(f,[size(f,1),T]);             % upsample temporal background

S_full = zeros(N,T);

P.p = 0;
ind_T = [0;cumsum(Ts(:))];
options.nb = options.gnb;
for i = 1:numFiles
    inds = ind_T(i)+1:ind_T(i+1);   % indeces of file i to be updated
    [C_full(:,inds),f_full(:,inds),~,~,R_full(:,inds)] = update_temporal_components_fast(registered_files(i).name,A_keep,b,C_full(:,inds),f_full(:,inds),P,options);
    disp(['Extracting raw fluorescence at native frame rate. File ',num2str(i),' out of ',num2str(numFiles),' finished processing.'])
end

%% extract DF/F and deconvolve DF/F traces

[F_dff,F0] = detrend_df_f(A_keep,[b,ones(prod(FOV),1)],C_full,[f_full;-double(F_dark)*ones(1,T)],R_full,options);

C_dec = zeros(N,T);         % deconvolved DF/F traces
S_dec = zeros(N,T);         % deconvolved neural activity
bl = zeros(N,1);            % baseline for each trace (should be close to zero since traces are DF/F)
neuron_sn = zeros(N,1);     % noise level at each trace
g = cell(N,1);              % discrete time constants for each trace
if p == 1; model_ar = 'ar1'; elseif p == 2; model_ar = 'ar2'; else; error('This order of dynamics is not supported'); end

for i = 1:N
    spkmin = options.spk_SNR*GetSn(F_dff(i,:));
    lam = choose_lambda(exp(-1/(options.fr*options.decay_time)),GetSn(F_dff(i,:)),options.lam_pr);
    [cc,spk,opts_oasis] = deconvolveCa(F_dff(i,:),model_ar,'method','thresholded','optimize_pars',true,'maxIter',20,...
                                'window',150,'lambda',lam,'smin',spkmin);
    bl(i) = opts_oasis.b;
    C_dec(i,:) = cc(:)' + bl(i);
    S_dec(i,:) = spk(:);
    neuron_sn(i) = opts_oasis.sn;
    g{i} = opts_oasis.pars(:)';
    disp(['Performing deconvolution. Trace ',num2str(i),' out of ',num2str(N),' finished processing.'])
end

author: flatironinstitute

repo: CaImAn-MATLAB


text:
function y=dbp(x)
% dbp(x) = 10*log10(x): the dB equivalent of the power x
y = -Inf*ones(size(x));
nonzero = x~=0;
y(nonzero) = 10*log10(abs(x(nonzero)));

author: Sable

repo: mcbench-benchmarks


text:
% clear; close all; clc;

function ani_slider
fs = 200;
t = 0:1/fs:5-1/fs;
f = 1;
x = sin(2*pi*1*t);

figure;
set(gcf,'position',[500 500 640 480]);
figsize = get(gcf,'position');
h = plot(t,x);

SliderH = uicontrol('style','slider','position',[70 6 512 20],'min',1,'max',5,'value',1,'callback',@cbfcn);

    function cbfcn(src, event)
       f = SliderH.Value ;
       x = sin(2*pi*f*t);
       h = plot(t,x);
    end
end

author: angeloyeo

repo: gongdols

save_path: github-repos/MATLAB/angeloyeo-gongdols


text:
function m = p02_m ( )

%*****************************************************************************80
%
%% P02_M returns the number of equations M for problem 2.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 April 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer M, the number of equations.
%
  m = 6;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function diagnostic = callstrul(F,h,options)

F_new = [];

for i = 1:length(F)
    if ~is(F(i),'lmi')
        F_new = F_new + F(i);
    else
        X = sdpvar(F(i));
        [l,m,r]=factors(X);
        if isempty(m)
            F_new = F_new + F(i);
        else
            [L1,R1,A1,M1,negated_cont1,negated_disc1,epsilon1,delta1,numpos1,xindicies,Pindicies] = preprocess_constraint(X);
            F_new = F_new + assignschur(F(i),'HKM_schur_LR_structure',L1,R1,A1,M1,negated_cont1,negated_disc1,epsilon1,delta1,numpos1,xindicies,Pindicies);
        end
    end
end

if nargin < 2
    % Equalities are converted internally in SDPT3 to double-sided
    % inequalities. This messes up our Schur compiler, hence we do it
    % already outside SDPT3
    options = sdpsettings('solver','sdpt3','removeequalities',-1);
else
    options.solver = 'sdpt3';
    options.removeequalities = -1;
end
diagnostic = solvesdp(F_new,h,options);

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
function varargout = lbpfliplr(varargin)
% VL_LBPFLIPLR  Flip LBP features left-right
%   F = VL_LBPFLIPLR(F) flips the LBP features F from left to
%   right.
%
%   Example::
%     The following instructions return results almost identical
%     assuming that the width of I is exactly divisible by the cell
%     size:
%       F = VL_LBP(FLIPLR(I), 8)
%       F_ = VL_LBPFLIPLR(VL_LBP(I), 8)
%
%   See also: VL_LBP(), VL_HELP().
[varargout{1:nargout}] = vl_lbpfliplr(varargin{:});

author: yihui-he

repo: panorama

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


text:
%GOBJ_POLYHEDRON Create polyhedron geometry object.
%
%   [ GOBJ ] = GOBJ_POLYHEDRON( P, TAG ) Creates a polyhedron geometry
%   object by finding the convex hull of the points P. Accepts the
%   following input parameters.
%
%       Parameter   Value/{Default}           Description
%       -----------------------------------------------------------------------------------
%       p           array [n_p,3]             Polyhedron points (default unit tetrahedron)
%       tag         string  {P1}              Geometry object tag/name
%
%   See also CONVHULL

% Copyright 2013-2022 Precise Simulation, Ltd.

author: precise-simulation

repo: featool-multiphysics


text:
function y = stdignorenan(x,varargin)

y = std(x(~isnan(x)),varargin{:});

author: kristinbranson

repo: JAABA


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Descritpion: Script to Price European options under Regime Switching Diffusion Models using Monte Carlo simulation
% Author:      Justin Kirkby
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[folder, name, ext] = fileparts(which( mfilename('fullpath')));
cd(folder);

addpath('../')

% ---------------------
%  Contract/Market Params
% ---------------------
call = 1;    %For call use 1 (else, its a put)
S_0  = 100;  %Initial price
r    = .05;  %Interest rate
q    = .00;  %dividend yield
T    = 1;    %Time (in years)
Kvec = S_0*[.85 .90 .95 1 1.05 1.10 1.15 1.20 1.25 1.30 1.35 1.5 1.6];   % strikes to price

% ---------------------
% Regime Switching Diffusion Params
% ---------------------
% Transition Matrix (dictates how the regimes transition)
Q = [-1 0.5 0.5;
    0.5 -1 0.5;
    0.5 0.5 -1];

drift_vec = [r-q  r-q  r-q];  % Drift in each state
sigma_vec = [0.15  0.25  0.35]; % Volatility in each state

initial_state = 1;

% ---------------------
% Sim Params
% ---------------------
N_sim = 5*10^5;
M = 500;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

method = 2;   %  1 = Euler, biased;   2 = Unbiased

tic
if method == 1
    Spath = Simulate_RegimeSwitching_Diffusion_func( N_sim, M, T, S_0, drift_vec, sigma_vec, Q, initial_state);

else
   Spath = Simulate_RegimeSwitching_Diffusion_Unbiased( N_sim, T, S_0, drift_vec, sigma_vec, Q, initial_state);
end
time = toc

histogram(Spath)

disc = exp(-r*T);
[prices, stdErrs] = Price_MC_European_Strikes_func(Spath, disc, call, Kvec )

plot(Kvec, prices)
ylabel('price')
xlabel('strike')
grid on;


text:
function d = cohens_d_2sample(input_values,binary_outcome)
% d = cohens_d_2sample(input_values,binary_outcome)
%
% This is for the two-sample case
% By Phil Kragel
%
% input_values: Continuous input values to test
% binary_outcome: Logical vector of 1/0 values for group A/B assignment

n1 = sum(~isnan(input_values(binary_outcome)) & ~isinf(input_values(binary_outcome)));
n0 = sum(~isnan(input_values(~binary_outcome)) & ~isinf(input_values(~binary_outcome)));

meanpres = mean(input_values(binary_outcome));
meanabs = mean(input_values(~binary_outcome));

v1 = var(input_values(binary_outcome));
v0 = var(input_values(~binary_outcome));

pooledsd = sqrt((v1.*(n1-1) + v0.*(n0-1)) ./ (n1 + n0 - 2));

d = (meanpres - meanabs) ./ pooledsd;

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
% LORENZ system
% System identification: DelayDMDc

clear all, close all, clc
figpath = '../FIGURES/LORENZ/';
datapath = '../DATA/LORENZ/';
addpath('../utils');

SystemModel = 'LORENZ';

%% Generate Data
InputSignalType = 'sphs';%prbs; chirp; noise; sine2; sphs; mixed
Ndelay = 1;
ONLY_TRAINING_LENGTH = 1;
getTrainingData

Nt = length(tspan)-1;

%% DMDc: B = unknown  and with time delay coordinates
ModelNumber = 2; % or 2
xrefs = [xref1,xref2];

if Ndelay == 1
    ModelName = 'DMDc';
elseif Ndelay>1
    ModelName = 'DelayDMDc';
end

Hu = getHankelMatrix_MV(u',1);
for i = 1:ModelNumber
    xmean{i} = xrefs(:,i)'; %mean(x);
    X   = x - repmat(xmean{i},[T 1]);
    Hx  = getHankelMatrix_MV(X,1);
    numOutputs = size(Hx,1); numInputs = size(Hu,1); numVar = 3;
    r1 = size(Hx,1); r2 = size(Hx,1);
    [sysmodel_DMDc{i},U,Up] = DelayDMDc_MV(Hx,Hu,size(Hx,1),size(Hx,1),dt,size(Hx,1),size(Hu,1),2);
end
%% Prediction over training phase
for i = 1:ModelNumber
    [xDMDc{i},~] = lsim(sysmodel_DMDc{i},Hu',tspan(1:end),x(1,:)'-xmean{i}');
    xDMDc{i} = xDMDc{i} + repmat(xmean{i},[length(tspan) 1]);
end

%% Show validation
for i = 1:ModelNumber
    clear ph
    figure,box on,
    ccolors = get(gca,'colororder');
    ph(1) = plot(tspan,x(:,1),'-','Color',ccolors(1,:),'LineWidth',1); hold on
    ph(2) = plot(tspan,x(:,2),'-','Color',ccolors(2,:),'LineWidth',1);
    ph(3) = plot(tspan(Ndelay:Nt+Ndelay),xDMDc{i}(:,1),'--','Color',ccolors(1,:)-[0 0.2 0.2],'LineWidth',2);
    ph(4) = plot(tspan(Ndelay:Nt+Ndelay),xDMDc{i}(:,2),'--','Color',ccolors(2,:)-[0.1 0.2 0.09],'LineWidth',2);
    xlim([0 (length(tspan)-1)*dt]), ylim([-25 50])
    xlabel('Time')
    ylabel('Population size')
    % legend('Prey (True)','Predator (True)', 'Prey (DMDc)','Predator (DMDc)')
    legend(ph([1,3]),'True',ModelName)
    set(gca,'LineWidth',1, 'FontSize',14)
    set(gcf,'Position',[100 100 300 200])
    set(gcf,'PaperPositionMode','auto')
    print('-depsc2', '-loose', '-cmyk', [figpath,'EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'_M',i,'.eps']);
end
%% Prediction
% Reference
tspanV   = [10:dt:20];
xA      = xv;
tA      = tv;

% Model
for i = 1:ModelNumber
    if Ndelay == 1
        x0      = [x(end,1:3)];
        Hunew   = [u(end),uv(1:end)];
        [xBm{i},tB] = lsim(sysmodel_DMDc{i},Hunew,tspanV,[x0-[xmean{i}]]');
    elseif Ndelay > 1
        x0      = [x(end-Ndelay+1,1:3),x(end,1:3)];
        Hunew   = [ u(end-Ndelay+1:end),uv(1:end-Ndelay);
            u(end),uv(1:end-1)];
        [xBm,tB] = lsim(sysmodel_DMDc,Hunew,tspanV,[x0-[xmean]]');
        xBm = xBm(:,4:6); xBm = xBm + repmat(xmean,[size(xBm,1) 1]);
    end

    xBm{i} = xBm{i} + repmat(xmean{i},[length(tB) 1]);
end
%% Show training and prediction
xB = xBm{1};
VIZ_SI_Validation

xB = xBm{2};
VIZ_SI_Validation

%% Save Data
Model.name = 'DelayDMDc';
Model.sys = sysmodel_DMDc;
Model.Ndelay = Ndelay;
Model.xmean = xmean;
Model.xrefs = xrefs;
Model.dt = dt;
save(fullfile(datapath,['EX_',SystemModel,'_SI_',ModelName,'_',InputSignalType,'.mat']),'Model')

author: eurika-kaiser

repo: SINDY-MPC


text:
function yval = basis_matrix_tmp ( left, n, mbasis, ndata, tdata, ydata, tval )

%*****************************************************************************80
%
%% BASIS_MATRIX_TMP computes Q = T * MBASIS * P
%
%  Discussion:
%
%    YDATA is a vector of data values, most frequently the values of some
%    function sampled at uniformly spaced points.  MBASIS is the basis
%    matrix for a particular kind of spline.  T is a vector of the
%    powers of the normalized difference between TVAL and the left
%    endpoint of the interval.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer LEFT, indicats that TVAL is in the interval
%    [ TDATA(LEFT), TDATA(LEFT+1) ], or that this is the "nearest"
%    interval to TVAL.
%    For TVAL < TDATA(1), use LEFT = 1.
%    For TDATA(NDATA) < TVAL, use LEFT = NDATA - 1.
%
%    Input, integer N, the order of the basis matrix.
%
%    Input, real MBASIS(N,N), the basis matrix.
%
%    Input, integer NDATA, the dimension of the vectors TDATA and YDATA.
%
%    Input, real TDATA(NDATA), the abscissa values.  This routine
%    assumes that the TDATA values are uniformly spaced, with an
%    increment of 1.0.
%
%    Input, real YDATA(NDATA), the data values to be interpolated or
%    approximated.
%
%    Input, real TVAL, the value of T at which the spline is to be
%    evaluated.
%
%    Output, real YVAL, the value of the spline at TVAL.
%
  if ( left == 1 )
    arg = 0.5E+00 * ( tval - tdata(left) );
    first = left;
  elseif ( left < ndata - 1 )
    arg = tval - tdata(left);
    first = left - 1;
  elseif ( left == ndata - 1 )
    arg = 0.5E+00 * ( 1.0E+00 + tval - tdata(left) );
    first = left - 1;
  end
%
%  TVEC(I) = ARG**(N-I).
%
  tvec(n,1) = 1.0E+00;
  for i = n-1 : -1 : 1
    tvec(i,1) = arg * tvec(i+1,1);
  end

  yval = 0.0E+00;
  for j = 1 : n
    yval = yval + ( tvec(1:n,1)' * mbasis(1:n,j) ) * ydata(first - 1 + j);
  end

  return
end


text:
function G = divgrad(M,options)

% divgrad - compute either gradient or divergence.
%
%   G = divgrad(M);
%
%   if M is a 2D array, compute gradient,
%   if M is a 3D array, compute divergence.
%   Use centered finite differences.
%
%   Copyright (c) 2007 Gabriel Peyre

options.null = 0;
if size(M,3)==2
    G = mydiv(M,options);
else
    G = mygrad(M,options);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d = mydiv(g,options)

bound = getoptions(options, 'bound', 'sym');

n = size(g,1);
d = zeros(n);

if strcmp(bound,'sym')
    d(2:end-1,:) = d(2:end-1,:) + ( g(3:end,:,1)-g(1:end-2,:,1) )/2;
    d(1,:) = d(1,:) + g(2,:,1)-g(1,:,1);
    d(end,:) = d(end,:) + g(end,:,1)-g(end-1,:,1);

    d(:,2:end-1) = d(:,2:end-1) + ( g(:,3:end,2)-g(:,1:end-2,2) )/2;
    d(:,1) = d(:,1) + g(:,2,2)-g(:,1,2);
    d(:,end) = d(:,end) + g(:,end,2)-g(:,end-1,2);
else
    sel1 = [2:n 1];
    sel2 = [n 1:n-1];
    d = g(sel1,:,1)-g(sel2,:,1) + g(:,sel1,2)-g(:,sel2,2);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function g = mygrad(M,options)

bound = getoptions(options, 'bound', 'sym');

n = size(M,1);
g = zeros(n,n,2);

if strcmp(bound,'sym')
    % on x
    g(2:end-1,:,1) = ( M(3:end,:)-M(1:end-2,:) )/2;
    g(1,:,1) = M(2,:)-M(1,:);
    g(end,:,1) = M(end,:)-M(end-1,:);
    % on y
    g(:,2:end-1,2) = ( M(:,3:end)-M(:,1:end-2,:) )/2;
    g(:,1,1) = M(2,:)-M(1,:);
    g(:,end,1) = M(:,end)-M(:,end-1);
else
    sel1 = [2:n 1];
    sel2 = [n 1:n-1];
    g = cat( 3, M(sel1,:)-M(sel2,:), M(:,sel1)-M(:,sel2) )/2;
end

author: alecjacobson

repo: gptoolbox


text:
function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
%   J = SIGMOID(z) computes the sigmoid of z.

% You need to return the following variables correctly
g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).

f=@(h) 1 ./ (1 + exp(-h)); % 1 / (1 + exp(-h));

g = f(z);

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

end

author: vugsus

repo: coursera-machine-learning


text:
classdef prtClassPerTurbo < prtClass
    % See: "Perturbo: a new classi?cation algorithm based on the spectrum
    % perturbations of the laplace-beltrami operator."
    %
    % Notes:
    % 1) Very very sensitive to the kernel sigma parameter; should/must
    % optimize over \sigma
    %
    % 2) Very memory intensive.  Consider bootstrapping data and/or bagging
    % this classifier to reduce computational load (memory ~ O(nObs^2) )
    %
    % % try this:
    % ds = prtDataGenMarysSimpleSixClass;
    % pt = prtClassPerTurbo;
    % pt.kernel = prtKernelRbf('sigma',.7);
    % pt = pt.train(ds);
    % plot(pt)
    %
    %
    % ds = prtDataGenMarySimple;
    % pt = prtClassPerTurbo;
    % pt.kernel = prtKernelRbf('sigma',.7);
    % pt = pt.train(ds);
    % plot(pt)
    %

    properties (SetAccess=private)
        name = 'PerTurbo'  % Bumping
        nameAbbreviation = 'PerTurbo'  %
        isNativeMary = true;         %
    end

    properties
        kernel = prtKernelRbfNdimensionScale;
    end
    properties (SetAccess=protected)
        trainedKernels
        K
        Kinv
        uClasses
    end

    methods

        function self = set.kernel(self,val)
            assert(numel(val)==1 &&  isa(val,'prtKernel'),'prt:prtClassRvm:kernel','kernel must be a prtKernel');
            self.kernel = val;
        end

        function self = prtClassPerTurbo(varargin)
            self = prtUtilAssignStringValuePairs(self,varargin{:});
        end

    end

    methods (Access=protected, Hidden = true)

        function self = trainAction(self,dataSet)
            self.uClasses = dataSet.uniqueClasses;
            y = dataSet.getTargets;
            x = dataSet.getObservations;
            for i = 1:length(self.uClasses)
                cInd = y == self.uClasses(i);
                cx = x(cInd,:);

                tempDs = prtDataSetClass(cx);
                self.trainedKernels{i} = self.kernel.train(tempDs);
                self.K{i} =  self.trainedKernels{i}.run_OutputDoubleArray(tempDs);
                self.Kinv{i} = inv(self.K{i});
            end
        end

        function yOut = runAction(self,dataSet)

            x = nan(dataSet.nObservations,length(self.uClasses));
            for samples = 1:1000:dataSet.nObservations
                retainObs = samples:min([samples+999,dataSet.nObservations]);
                currSet = dataSet.retainObservations(retainObs);
                for i = 1:length(self.uClasses)

                    k = self.trainedKernels{i}.run_OutputDoubleArray(currSet);
                    x(retainObs,i) = 1-diag(k*self.Kinv{i}*k');
                end
            end

            yOut = dataSet;
            yOut.X = -x;
            %binary; note - output mixture for binary classification
            if length(self.uClasses) == 2
                yOut.X = -x(:,2)+x(:,1);
            end
        end

    end
end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
clear all; close all;
bw=imread('cameraman.tif');
se=strel('ball', 5, 5);
bw2=imdilate(bw, se);
figure;
subplot(121);  imshow(bw);
subplot(122);  imshow(bw2);

author: HuangCongQing


text:
function c_jac = cheb2jac( c_cheb, alpha, beta )
%CHEB2JAC   Convert Chebyshev coefficients to Jacobi coefficients.
%   C_JAC = CHEB2LEG(C_CHEB, A, B) converts the vector C_CHEB of Chebyshev
%   coefficients to a vector C_JAC of Jacobi coefficients such that
%    C_CHEB(1)*T_0(x) + ... + C_CHEB(N)*T{N-1}(x) = ...
%           C_LEG(1)*P_0^{(A,B)}(x) + ... + C_LEG(N)*P{N-1}^{(A,B)}(x),
%   where P_k^{(A,B)} is the degree k Jacobi polynomial corresponding to the
%   weight function w(x) = (1-X)^A * (1+X)^B.
%
% See also JAC2CHEB, JAC2JAC.

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

%%%%%%%%% For developers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% For more information on the algorithm for N>512, see Section 5.3 of
%
% A. Townsend, M. Webb, and S. Olver, "Fast polynomial transforms based on
% Toeplitz and Hankel matrices", submitted, 2016.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

N = size(c_cheb, 1);    % Length of coefficients.

if ( alpha == 0 && beta == 0 )
   % Use cheb2leg for alpha = beta = 0:

    c_jac = cheb2leg( c_cheb );

elseif ( alpha == -.5 && beta == -.5 )
    % Undo scaling:

    % Convert T_n -> P_n^(-1/2,1/2):
    scl = [1 cumprod((1/2:1/2+N-2)./(1:N-1))]';   % P_n^(-1/2,-1/2)(1)
    c_jac = spdiags( scl, 0, N, N) \ c_cheb;

elseif ( N <= 512 )

    c_jac = cheb2jac_direct(c_cheb, alpha, beta);

else
    % Convert Chebyshev to Jacobi (-1/2,-1/2) and then call jac2jac:

    % Convert T_n -> P_n^(-1/2,1/2):
    scl = [1 cumprod((1/2:1/2+N-2)./(1:N-1))]';   % P_n^(-1/2,-1/2)(1)
    c_jac = spdiags( scl, 0, N, N) \ c_cheb;
    % Now convert P_n^(-1/2,-1/2) -> P_n^(alpha,beta):
    c_jac = jac2jac( c_jac, -1/2, -1/2, alpha, beta );

end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% DIRECT METHOD %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function c_jac = cheb2jac_direct(c_cheb, a, b)
%CHEB2JAC_DIRECT   Convert Cheb to Jacobi (A,B) coeffs using direct method.

[N, m] = size(c_cheb);              % Number of columns.
N = N - 1;                          % Degree of polynomial.
% Don't let N be too big:

if ( N <= 0 ), c_jac = c_cheb; return, end % Trivial case.
f = chebtech2.coeffs2vals([c_cheb ; zeros(N, m)]); % Values on 2*N+1 Cheb grid.
% 2*N+1 Chebyshev grid (reversed order) and Clenshaw-Curtis-Jacobi weights:
[w, x] = ccjQuadwts(2*N+1, a, b);

% Make the Jacobi-Chebyshev Vandemonde matrix:
apb = a + b; aa  = a * a; bb  = b * b;
P = zeros(2*N+1, N+1); P(:,1) = 1;
P(:,2) = 0.5*(2*(a + 1) + (apb + 2)*(x - 1));
for k = 2:N
    k2 = 2*k;
    k2apb = k2 + apb;
    q1 =  k2*(k + apb)*(k2apb - 2);
    q2 = (k2apb - 1)*(aa - bb);
    q3 = (k2apb - 2)*(k2apb - 1)*k2apb;
    q4 =  2*(k + a - 1)*(k + b - 1)*k2apb;
    P(:,k+1) = ((q2 + q3*x).*P(:,k) - q4*P(:,k-1)) / q1;
end

% Scaling:
% NN = (0:N)';
% scale = 2^(a+b+1)*gamma(NN+a+1).*gamma(NN+b+1) ./ ...
%     ((2*NN+a+b+1).*gamma(NN+a+b+1).*factorial(NN))
scale = zeros(N+1, 1);
scale(1) = beta(a+1, b+1);
for n = 0:N-1
    scale(n+2) = (2*n+a+b+1)*(n+a+1)*(n+b+1) / ...
        ((n+1)*(2*n+a+b+3)*(n+a+b+1))*scale(n+1);
end
scale = 2^(a+b+1)*scale;

% Jacobi coefficients:
c_jac = bsxfun(@times, P.'*(bsxfun(@times, f , w.')), 1./scale);

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% DCT METHODS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [w, x] = ccjQuadwts(n, a, b)
%CCJQUADWTS   Clenshaw-Curtis-Jacobi quadrature weights.
%   [W, X] = CCJQUADWTS(N, A, B) returns the N-point Clenshaw-Curtis-Jacobi
%   quadrature nodes, X = CHEBPTS(N), and weights, W, corresponding to the
%   weight function w(t) = (1-t)^A * (1+t)^B on the interval [-1,1].

% TODO: Move this to somewhere more sensible / accessible.

if ( a == b && a == 0 ) % Clenshaw-Curtis

    c = 2./[1, 1-(2:2:(n-1)).^2];          % Standard Chebyshev moments
    c = [c, c(floor(n/2):-1:2)];           % Mirror for DCT via FFT
    w = ifft(c);                           % Interior weights
    w([1, n]) = w(1)/2;                    % Boundary weights

elseif ( a == b )       % Gegenbauer

    l = a + .5;                            % Gegenbauer parameter
    g0 = gamma(l+.5)*sqrt(pi)/gamma(l+1);
    k = 1:floor((n-1)/2);
    c = g0*[1, cumprod((k-l-1)./(k+l))];   % Chebyshev moments for (1-x)^a(1+x)^b
    c = [c, c(floor(n/2):-1:2)];           % Mirror for DCT via FFT
    w = ifft(c);                           % Interior weights
    w([1, n]) = w(1)/2;                    % Boundary weights

else                    % Jacobi

    c = [1, (a-b)/(a+b+2), zeros(1, n-2)]; % Initialise moments
    for r = 1:n % Recurrence relation for 3F2([r, -r, b +1 ; .5, a+b+2] ; 1 ):
        c(r+2) = - (2*(b-a)*c(r+1) + (a+b+2-r)*c(r)) / (a+b+2+r);
    end
    c = 2^(a+b+1)*gamma(a+1)*gamma(b+1)/gamma(a+b+2) * c; % Moments (with const)
    v = ifft([c(1:n), c(n-1:-1:2)]);       % Mirror for DCT via FFT
    w = [v(1), 2*v(2:n-1), v(n)];          % Rescale interior weights

end

if ( nargout > 1 )
    x = chebtech2.chebpts(n);              % 2nd-kind Chebyshev points.
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function Ahat = nearestSPD(A)
% nearestSPD - the nearest (in Frobenius norm) Symmetric Positive Definite matrix to A
% usage: Ahat = nearestSPD(A)
%
% From Higham: "The nearest symmetric positive semidefinite matrix in the
% Frobenius norm to an arbitrary real matrix A is shown to be (B + H)/2,
% where H is the symmetric polar factor of B=(A + A')/2."
%
% http://www.sciencedirect.com/science/article/pii/0024379588902236
%
% arguments: (input)
%  A - square matrix, which will be converted to the nearest Symmetric
%    Positive Definite Matrix.
%
% Arguments: (output)
%  Ahat - The matrix chosen as the nearest SPD matrix to A.

if nargin ~= 1
  error('Exactly one argument must be provided.')
end

% test for a square matrix A
[r,c] = size(A);
if r ~= c
  error('A must be a square matrix.')
elseif (r == 1) && (A <= 0)
  % A was scalar and non-positive, so just return eps
  Ahat = eps;
  return
end

% symmetrize A into B
B = (A + A')/2;

% Compute the symmetric polar factor of B. Call it H.
% Clearly H is itself SPD.
[U,Sigma,V] = svd(B);
H = V*Sigma*V';

% get Ahat in the above formula
Ahat = (B+H)/2;

% ensure symmetry
Ahat = (Ahat + Ahat')/2;

% test that Ahat is in fact PD. if it is not so, then tweak it just a bit.
p = 1;
k = 0;
while p ~= 0
  [R,p] = chol(Ahat);
  k = k + 1;
  if p ~= 0
    % Ahat failed the chol test. It must have been just a hair off,
    % due to floating point trash, so it is simplest now just to
    % tweak by adding a tiny multiple of an identity matrix.
    mineig = min(eig(Ahat));
    Ahat = Ahat + (-mineig*k.^2 + eps(mineig))*eye(size(A));
  end
end

author: opencobra

repo: cobratoolbox


text:
function start_num = p01_start_num ( )

%*****************************************************************************80
%
%% P01_START_NUM returns the number of starting points for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 May 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer START_NUM, the number of starting points.
%
  start_num = 2;

  return
end


text:
  function y = fatrix2_maskit(mask, x)
%|function y = fatrix2_maskit(mask, x)
%|
%| Apply mask to x (replicating if needed via bsxfun).
%| If mask is empty, then y := x.
%|
%| Used as part of many "back" (adjoint) methods to comply with fatrix2
%| requirement that "back" method apply the mask.

if nargin < 2, ir_usage, end

if isempty(mask)
	y = x;
elseif isequal(size(mask), size(x))
	y = mask .* x;
else
	siz = size(x);
	size_mask = size(mask);
	if numel(size_mask) == 2 && size_mask(2) == 1
		size_mask = size_mask(1);
		ndim_mask = 1;
	else
		ndim_mask = ndims(mask);
	end
	if ~isequal(size_mask, siz(1:ndim_mask))
		pr size(mask)
		pr size(x)
		fail 'size mismatch'
	end
	y = bsxfun(@times, mask, x);
end

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function [ output_maps ] = max_pooling( input_maps)
%POOLING Summary of this function goes here
%   Detailed explanation goes here

    orig_rows = size(input_maps,1);
    orig_cols = size(input_maps,2);

    pooled_rows = ceil(orig_rows / 2);
    pooled_cols = ceil(orig_cols / 2);

    up_to_rows_out = floor(orig_rows / 2);
    up_to_cols_out = floor(orig_cols / 2);

    if(mod(orig_cols,2) == 0)
        up_to_cols = orig_cols;
    else
        up_to_cols = orig_cols - 1;
    end

    if(mod(orig_rows,2) == 0)
        up_to_rows = orig_rows;
    else
        up_to_rows = orig_rows - 1;
    end

    output_maps = zeros(pooled_rows, pooled_cols, size(input_maps,3));
    for i=1:size(input_maps,3)
        temp = im2col(input_maps(1:up_to_rows,1:up_to_cols,i), [2,2], 'distinct');
        max_val = max(temp);
        output_maps(1:up_to_rows_out,1:up_to_cols_out,i) = reshape(max_val, up_to_rows_out, up_to_cols_out);
    end

    % A bit of a hack for non-even number of rows or columns
    if(mod(orig_cols,2) ~= 0)
        for i=1:size(input_maps,3)
            temp = im2col(input_maps(1:up_to_rows,end,i), [2,1], 'distinct');
            max_val = max(temp);
            output_maps(1:up_to_rows_out,end,i) = max_val;
        end
    end

    if(mod(orig_rows,2) ~= 0)
        for i=1:size(input_maps,3)
            temp = im2col(input_maps(end, 1:up_to_cols,i), [1,2], 'distinct');
            max_val = max(temp);
            output_maps(end, 1:up_to_cols_out,i) = max_val;
        end
    end

    if(mod(orig_cols,2) ~= 0 && mod(orig_rows,2) ~= 0)
        output_maps(end,end,:) = input_maps(end,end,:);
    end

end

author: TadasBaltrusaitis

repo: OpenFace


text:
classdef ProcResultClass < handle

    properties
        dod;
        dc;
        dodAvg;
        dcAvg;
        dodAvgStd;
        dcAvgStd;
        dodSum2;
        dcSum2;
        tHRF;
        nTrials;
        ch;
        grpAvgPass;
        misc;
    end

    properties (Access=private)
        filename
        logger
    end

    methods

        % ---------------------------------------------------------------------------
        function obj = ProcResultClass()
            global logger

            obj.logger = InitLogger(logger);

            obj.Initialize();
            obj.filename = '';
        end

        % ---------------------------------------------------------------------------
        function Initialize(obj)
            obj.dod = [];
            obj.dc = [];
            obj.dodAvg = [];
            obj.dcAvg = [];
            obj.dodAvgStd = [];
            obj.dcAvgStd = [];
            obj.dodSum2 = [];
            obj.dcSum2 = [];
            obj.tHRF = [];
            obj.nTrials = {};
            obj.grpAvgPass = [];
            obj.misc = [];
        end

        % ---------------------------------------------------------------------------
        function tHRF_common = GeneratetHRFCommon(obj, tHRF_common)
            nDataBlks = obj.GetDataBlocksNum();
            if isempty(tHRF_common)
                tHRF_common = cell(nDataBlks,1);
            end

            % Find smallest tHRF among the runs. We should make this the common one.
            for iBlk = 1:nDataBlks
                if isempty(tHRF_common{iBlk})
                    tHRF_common{iBlk} = obj.GetTHRF(iBlk);
                elseif length(obj.GetTHRF(iBlk)) < length(tHRF_common{iBlk})
                    tHRF_common{iBlk} = obj.GetTHRF(iBlk);
                end
            end
        end

        % ---------------------------------------------------------------------------
        function SettHRFCommon(obj, tHRF_common, name, type)
            for iBlk = 1:length(tHRF_common)
                if size(tHRF_common{iBlk},2)<size(tHRF_common{iBlk},1)
                    tHRF_common{iBlk} = tHRF_common{iBlk}';
                end
                t = obj.GetTHRF(iBlk);
                if isempty(t)
                    return;
                end
                n = length(tHRF_common{iBlk});
                m = length(t);
                d = n-m;
                if d<0
                    fprintf('WARNING: tHRF for %s %s is larger than the common tHRF.\n',type, name);
                    if ~isempty(obj.dodAvg)
                        if isa(obj.dodAvg, 'DataClass')
                            obj.dodAvg(iBlk).TruncateTpts(abs(d));
                        else
                            obj.dodAvg(n+1:m,:,:) = [];
                        end
                    end
                    if ~isempty(obj.dodAvgStd)
                        if isa(obj.dodAvgStd, 'DataClass')
                            obj.dodAvgStd(iBlk).TruncateTpts(abs(d));
                        else
                            obj.dodAvgStd(n+1:m,:,:) = [];
                        end
                    end
                    if ~isempty(obj.dodSum2)
                        if isa(obj.dodSum2, 'DataClass')
                            obj.dodSum2(iBlk).TruncateTpts(abs(d));
                        else
                            obj.dodSum2(n+1:m,:,:) = [];
                        end
                    end
                    if ~isempty(obj.dcAvg)
                        if isa(obj.dcAvg, 'DataClass')
                            obj.dcAvg(iBlk).TruncateTpts(abs(d));
                        else
                            obj.dcAvg(n+1:m,:,:,:) = [];
                        end
                    end
                    if ~isempty(obj.dcAvgStd)
                        if isa(obj.dcAvgStd, 'DataClass')
                            obj.dcAvgStd(iBlk).TruncateTpts(abs(d));
                        else
                            obj.dcAvgStd(n+1:m,:,:,:) = [];
                        end
                    end
                    if ~isempty(obj.dcSum2)
                        if isa(obj.dcSum2, 'DataClass')
                            obj.dcSum2(iBlk).TruncateTpts(abs(d));
                        else
                            obj.dcSum2(n+1:m,:,:,:) = [];
                        end
                    end
                end
                obj.tHRF = tHRF_common{iBlk};
            end
        end

        % ----------------------------------------------------------------------------------
        function var = GetVar(obj, varname, iBlk)
            var = [];
            if exist('iBlk','var') && isempty(iBlk)
                iBlk=1;
            end
            if isproperty(obj, varname)
                eval(sprintf('var = obj.%s;', varname));
            elseif isproperty(obj.misc, varname)
                eval(sprintf('var = obj.misc.%s;', varname));
            end
            if ~isempty(var) && exist('iBlk','var')
                if iscell(var)
                    var = var{iBlk};
                else
                    var = var(iBlk);
                end
            end
        end

    end

    methods

        % ----------------------------------------------------------------------------------
        function filename = SetFilename(obj, filename)
            if nargin==1
                filename = '';
                return;
            end
            if isempty(filename)
                return;
            end

            % It is important that this function can assume that the
            % filename path + '.mat' exists
            [pname, fname] = fileparts(filename);
            pname = filesepStandard(pname);
            if ispathvalid([pname, fname, '.mat'])
                obj.filename = [pname, fname, '.mat'];
            elseif ispathvalid([pname, fname, '/', fname, '.mat'])
                obj.filename = [pname, fname, '/', fname, '.mat'];
            else
                obj.filename = '';
            end
            filename = obj.filename;
        end

        % ----------------------------------------------------------------------------------
        function SetInactiveChannelData(obj)
            if isa(obj.dc, 'DataClass')
                obj.dc.SetInactiveChannelData();
            end
            if isa(obj.dod, 'DataClass')
                obj.dod.SetInactiveChannelData();
            end
            if isa(obj.dcAvg, 'DataClass')
                obj.dcAvg.SetInactiveChannelData();
            end
            if isa(obj.dodAvg, 'DataClass')
                obj.dodAvg.SetInactiveChannelData();
            end
            if isa(obj.dcAvgStd, 'DataClass')
                obj.dcAvgStd.SetInactiveChannelData();
            end
            if isa(obj.dodAvgStd, 'DataClass')
                obj.dodAvgStd.SetInactiveChannelData();
            end
        end

        % ----------------------------------------------------------------------------------
        function Save(obj, vars, filename, options)
            % options possible values:
            %    freememory
            %    keepinmemory

            if ~exist('options', 'var') || isempty(options)
                options = 'keepinmemory';
            end

            obj.SetFilename(filename);

            output = obj; %#ok<NASGU>
            props = propnames(vars);
            for ii=1:length(props)
                if eval( sprintf('isproperty(output, ''%s'');', props{ii}) )
                    eval( sprintf('output.%s = vars.%s;', props{ii}, props{ii}) );
                else
                    eval( sprintf('output.misc.%s = vars.%s;', props{ii}, props{ii}) );
                end
            end

            obj.SetInactiveChannelData();

            % If file name is not an empty string, save results to file and  ree memory
            % to save memory space
            if isempty(obj.filename)
                return;
            end

            % If saving this data for the first time folder might have to be created under
            % the processd data output folder, depending on the group folder folder structure
            pname = fileparts(obj.filename);
            if ~isempty(pname)
                if ~ispathvalid(pname)
                    mkdir(pname)
                end
            end

            try
                obj.logger.Write(sprintf('Saving derived data output: %s', obj.filename));
            	save(obj.filename, '-mat', 'output');
            catch
                if ~ispathvalid(obj.filename)
                    msg = sprintf('ERROR: Was not able to save processed data - %s not found.', obj.filename);
                    MessageBox(msg);
                    obj.logger.Write(msg);
                    return;
                end
            end

            % Free memory for this object
            if ~isempty(findstr('freememory', options)) %#ok<FSTR>
                obj.FreeMemory();
            end
        end

        % ----------------------------------------------------------------------------------
        function SaveInit(obj, pathname, filename)
            if isempty(filename)
                return
            end
            if ispathvalid([filesepStandard(pathname), filename, '.mat'])
                return
            end
            if ~ispathvalid(pathname)
                mkdir(pathname)
            end
            output = ProcResultClass();

            obj.logger.Write(sprintf('Initializing empty derived data output file:   %s', [filesepStandard(pathname), filename, '.mat']));
            save([filesepStandard(pathname), filename, '.mat'], '-mat', 'output');
        end

        % ----------------------------------------------------------------------------------
        function err = Load(obj, filename)
            err = 0;
            obj.SetFilename(filename);
            if isempty(obj.filename)
                return;
            end

            % If object is not empty it means we already have loaded data. No
            % need to waste time loading it from file.
%             if ~obj.IsEmpty()
%                 return;
%             end

            % Error check file
            if ~ispathvalid(obj.filename,'file')
                return
            end

            % If file name is not an empty string, load proc stream output from file
            load(obj.filename, '-mat');

            % Error check output
            if ~exist('output','var')
                return
            end
            if ~isa(output,'ProcResultClass')
                return
            end
            obj.Copy(output);
        end

        % ----------------------------------------------------------------------------------
        function FreeMemory(obj, filename)
            if ~exist('filename','var')
                filename = '';
            end

            % If file name is not passed and is not already set within this
            % object it means we are not saving output to seperate files
            % and therefore not freeing memory for the processed output.
            % Therefore we simply return to avoid re-initialzing the object
            if isempty(obj.filename) && isempty(filename)
                return;
            end

            if ~ispathvalid([filename, '.mat'], 'file')
                return
            end

            % Free memory for this object
            obj.Initialize();
        end

        % ----------------------------------------------------------------------------------
        function Reset(obj, filename)
            obj.Initialize();

            obj.SetFilename(filename);
            if isempty(obj.filename)
                return;
            end

            % Check that data file associated with this processing element exists
            if ispathvalid(obj.filename, 'file')
                % Delete file containing the actual datas
                delete(obj.filename);
            end

            % Check that exported data file associated with this processing element exists
            [pname, fname] = fileparts(obj.filename);
            if ispathvalid([pname, '/', fname, '_HRF.txt'], 'file')
                delete([pname, '/', fname, '_HRF.txt']);
            end
        end

        % ----------------------------------------------------------------------------------
        function Flush(obj)
            obj.Initialize();
        end

        % ----------------------------------------------------------------------------------
        function Print(obj, indent)
            if ~exist('indent', 'var')
                indent = 6;
            end
            fprintf('%sOutput:\n', blanks(indent));
        end

    end

    methods

        % ----------------------------------------------------------------------------------
        function [keys, values] = GetAllData(obj)
            % Returns names and references to all non-empty DataClass objects available as
            % properties of the ProcResultClass instance or of the misc list
            props = properties(obj);
            keys = {};
            values = {};
            for i = 1:length(props)
                val = eval(sprintf('obj.%s', props{i}));
                if isa(val, 'DataClass')
                    if ~isempty(val.dataTimeSeries) && ~isempty(val.time) && ~isempty(val.measurementList)
                        keys{end + 1} = props{i}; %#ok<AGROW>
                        values{end + 1} = val; %#ok<AGROW>
                    end
                end
            end
            try
                miscnames = fields(obj.misc);
            catch
                return
            end
            for i = 1:length(miscnames)
                val = eval(sprintf('obj.misc.%s', miscnames{i}));
                if isa(val, 'DataClass')
                    if ~isempty(val.dataTimeSeries) && ~isempty(val.time) && ~isempty(val.measurementList)
                        keys{end + 1} = miscnames{i}; %#ok<AGROW>
                        values{end + 1} = val; %#ok<AGROW>
                    end
                end
            end
        end

        % ----------------------------------------------------------------------------------
        function SetTHRF(obj, t)
            obj.tHRF = t;
        end

        % ----------------------------------------------------------------------------------
        function t = GetTHRF(obj, iBlk)
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1;
            end

            if ~isempty(obj.dcAvg) && isa(obj.dcAvg, 'DataClass')
                t = obj.dcAvg(iBlk).GetT;
            elseif ~isempty(obj.dodAvg) && isa(obj.dodAvg, 'DataClass')
                t = obj.dodAvg(iBlk).GetT;
            else
                t = obj.tHRF;
            end
        end

        % ----------------------------------------------------------------------------------
        function SetDodAvg(obj, val)
            obj.dodAvg = val;
        end

        % ----------------------------------------------------------------------------------
        function SetDcAvg(obj, val)
            obj.dcAvg = val;
        end

        % ----------------------------------------------------------------------------------
        function SetDodAvgStd(obj, val)
            obj.dodAvgStd = val;
        end

        % ----------------------------------------------------------------------------------
        function SetDcAvgStd(obj, val)
            obj.dcAvgStd = val;
        end

        % ----------------------------------------------------------------------------------
        function SetDodSum2(obj, val)
            obj.dodSum2 = val;
        end

        % ----------------------------------------------------------------------------------
        function SetDcSum2(obj, val)
            obj.dcSum2 = val;
        end

        % ----------------------------------------------------------------------------------
        function SetDod(obj, val)
            obj.dod = val;
        end

        % ----------------------------------------------------------------------------------
        function SetDc(obj, val)
            obj.dc = val;
        end

        % ----------------------------------------------------------------------------------
        function yavg = GetDodAvg(obj, type, condition, iBlk) %#ok<*INUSL>
            yavg = [];

            % Check type argument
            if ~exist('type','var') || isempty(type)
                type = 'dodAvg';
            end
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1; %#ok<NASGU>
            end

            if ~ischar(type)
                return;
            end

            % Get data matrix
            if isa(eval(sprintf('obj.%s', type)), 'DataClass')
                if isempty(eval(sprintf('obj.%s', type)))
                    return;
                end
                yavg = eval(sprintf('obj.%s(iBlk).GetDataTimeSeries(''reshape'')', type));
            else
                yavg = eval(sprintf('obj.%s', type));
            end

            % Get condition
            if ~exist('condition','var')
                condition = 1:size(yavg,3);
            end
            if isempty(condition)
                yavg = [];
            end
            if isempty(yavg)
                return;
            end
            if max(condition)>size(yavg,3)
                yavg = [];
                return;
            end
            if all(isnan(yavg(:,:,condition)))
                yavg = [];
                return;
            end
            yavg = yavg(:,:,condition);
        end

        % ----------------------------------------------------------------------------------
        function yavg = GetDcAvg(obj, type, condition, iBlk)
            yavg = [];

            % Check type argument
            if ~exist('type','var') || isempty(type)
                type = 'dcAvg';
            end
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1; %#ok<NASGU>
            end

            if ~ischar(type)
                return;
            end

            % Get data matrix
            if isa(eval(sprintf('obj.%s', type)), 'DataClass')
                if isempty(eval(sprintf('obj.%s', type)))
                    return;
                end
                yavg = eval(sprintf('obj.%s(iBlk).GetDataTimeSeries(''reshape'')', type));
            else
                yavg = eval(sprintf('obj.%s', type));
            end

            % Get condition
            if ~exist('condition','var')
                condition = 1:size(yavg,4);
            end
            if isempty(condition)
                yavg = [];
            end
            if isempty(yavg)
                return;
            end
            if max(condition)>size(yavg,4)
                yavg = [];
                return;
            end
            if all(isnan(yavg(:,:,:,condition)))
                yavg = [];
                return;
            end
            yavg = yavg(:,:,:,condition);
        end

        % ----------------------------------------------------------------------------------
        function y = GetDataTimeCourse(obj, type, iBlk)
            y = [];
            options = ''; %#ok<NASGU>

            % Check type argument
            if ~exist('type','var') || isempty(type)
                type = 'dcAvg';
            end
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1; %#ok<NASGU>
            end

            if ~ischar(type)
                return;
            end

            if isa(eval(sprintf('obj.%s', type)), 'DataClass')
                if isempty(eval(sprintf('obj.%s', type)))
                    return;
                end
                if strcmp(type, 'dc') || strcmp(type, 'dcAvg') || strcmp(type, 'dodAvg')
                    options = 'reshape'; %#ok<NASGU>
                end
                y = eval(sprintf('obj.%s(iBlk).GetDataTimeSeries(options)', type));
            else
                y = eval(sprintf('obj.%s', type));
            end
        end

        % ----------------------------------------------------------------------------------
        function SetNtrials(obj, val)
            obj.nTrials = val;
        end

        % ----------------------------------------------------------------------------------
        function nTrials = GetNtrials(obj, iBlk)
            nTrials = {};
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1;
            end
            if isempty(obj.nTrials)
                return;
            end
            if iscell(obj.nTrials)
                nTrials = obj.nTrials{iBlk};
            else
                nTrials = obj.nTrials;
            end
        end

        % ----------------------------------------------------------------------------------
        function s = GetStims(obj, t)
            if nargin==1
                t = [];
            end
            s = obj.GetVar('s');
            if isempty(s)
                if isempty(obj.dod) || ~isa(obj.dod, 'DataClass')
                    return;
                end
                stim = obj.GetVar('stim');
                if isempty(stim)
                    return;
                end
                snirf = SnirfClass(obj.dod, stim);
                s = snirf.GetStims(t);
            end
        end

        % ----------------------------------------------------------------------------------
        function val = GetTincAuto(obj, iBlk)
            val = {};
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk=1;
            end
            if isproperty(obj.misc, 'tIncAuto')
                if iscell(obj.misc.tIncAuto)
                    val = obj.misc.tIncAuto{iBlk};
                else
                    val = obj.misc.tIncAuto;
                end
            end
        end

        % ----------------------------------------------------------------------------------
        function val = GetTincAutoCh(obj, iBlk)
            val = {};
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk=1;
            end
            if isproperty(obj.misc, 'tIncAutoCh')
                if iscell(obj.misc.tIncAutoCh)
                    val = obj.misc.tIncAutoCh{iBlk};
                else
                    val = obj.misc.tIncAutoCh;
                end
            end
        end

        % ----------------------------------------------------------------------------------
        function mlActAuto = GetMeasListActAuto(obj, iBlk)
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk=1;
            end
            mlActAutoAll = obj.GetVar('mlActAuto');
            mlActAuto = mlActAutoAll{iBlk};
        end

        % ----------------------------------------------------------------------------------
        function n = GetDataBlocksNum(obj)
            n = 0;

            if ~isempty(obj.dcAvg)
                if isnumeric(obj.dcAvg)
                    n = 1;
                else
                    n = length(obj.dcAvg);
                end
            elseif ~isempty(obj.dodAvg)
                if isnumeric(obj.dodAvg)
                    n = 1;
                else
                    n = length(obj.dodAvg);
                end
            elseif ~isempty(obj.dc)
                if isnumeric(obj.dc)
                    n = 1;
                else
                    n = length(obj.dc);
                end
            elseif ~isempty(obj.dod)
                if isnumeric(obj.dod)
                    n = 1;
                else
                    n = length(obj.dod);
                end
            end
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods

        % ----------------------------------------------------------------------------------
        function Copy(obj, obj2, filename)

            if ~isa(obj, 'ProcResultClass')
                return;
            end
            if ~exist('filename', 'var')
                filename = '';
            end
            obj.SetFilename(filename);

            % If file name is set and exists then free memory for output
            % as a place holder for loading data from file when needed
            if ~isempty(filename) && exist(obj.filename, 'file')

                obj.FreeMemory(filename);

            % Else copy obj2 to obj
            elseif isempty(filename)

	            obj.dod = obj2.dod;
	            obj.dc = obj2.dc;
	            obj.dodAvg = obj2.dodAvg;
	            obj.dcAvg = obj2.dcAvg;
	            obj.dodAvgStd = obj2.dodAvgStd;
	            obj.dcAvgStd = obj2.dcAvgStd;
	            obj.dodSum2 = obj2.dodSum2;
	            obj.dcSum2 = obj2.dcSum2;
	            obj.tHRF = obj2.tHRF;
	            if iscell(obj2.nTrials)
	                obj.nTrials = obj2.nTrials;
	            else
	                obj.nTrials = {obj2.nTrials};
	            end
	            obj.ch = obj2.ch;
	            obj.misc = obj2.misc;
            end
        end

        % ----------------------------------------------------------------------------------
        function b = IsEmpty(obj)
            b = false;
            if isempty(obj)
                b = true;
                return
            end
            if ~isempty(obj.dod)
                return
            end
            if ~isempty(obj.dc)
                return
            end
            if ~isempty(obj.dodAvg)
                return
            end
            if ~isempty(obj.dcAvg)
                return
            end
            if ~isempty(obj.dodAvgStd)
                return
            end
            if ~isempty(obj.dcAvgStd)
                return
            end
            if ~isempty(obj.dodSum2)
                return
            end
            if ~isempty(obj.dcSum2)
                return
            end
            if ~isempty(obj.tHRF)
                return
            end
            if ~isempty(obj.nTrials)
                return
            end
            if ~isempty(obj.grpAvgPass)
                return
            end
            if ~isempty(obj.misc)
                return
            end
            b = true;
        end

        % ----------------------------------------------------------------------------------
        function n = GetNumChForOneCondition(obj, iBlk)
            n = 0;
            if nargin<2
                iBlk = 1;
            end
            if isa(obj.dcAvg, 'DataClass')
                n = length(obj.dcAvg(iBlk).GetMeasurementListIdxs(1));
            end
        end

        % ----------------------------------------------------------------------------------
        function nbytes = MemoryRequired(obj)
            fields = properties(obj);
            nbytes = zeros(length(fields),1);
            for ii = 1:length(fields)
                fieldstr = sprintf('obj.%s', fields{ii});
                if ~isempty(fieldstr)
                    if isa(eval(fieldstr), 'DataClass')
                        nbytes(ii) =  eval(sprintf('%s.MemoryRequired();', fieldstr));
                    else
                        nbytes(ii) =  eval(sprintf('sizeof(%s);', fieldstr));
                    end
                end
            end
            nbytes = sum(nbytes);
        end

    end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Export related methods
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    methods

        % ----------------------------------------------------------------------------------
        function [tblcells, maxwidth] = GenerateTableCellsHeader_MeanHRF(obj, iBlk)
            if nargin<5
                iBlk = 1;
            end
            tblcells = TableCell.empty();
            maxwidth = length('HRF HbX,999,999');
            if isa(obj.dcAvg, 'DataClass')
                measList = obj.dcAvg(iBlk).measurementList;
                measListIdxs = obj.dcAvg(iBlk).GetMeasurementListIdxs(1);
                for iCh = measListIdxs
                    tblcells(1,iCh) = TableCell(sprintf('%s,%d,%d', measList(iCh).dataTypeLabel, measList(iCh).sourceIndex, measList(iCh).detectorIndex), maxwidth);
                end
            end
        end

        % ----------------------------------------------------------------------------------
        function tblcells = GenerateTableCells_MeanHRF_Alt(obj, name, CondNames, trange, width, iBlk)
            if ~exist('trange','var') || isempty(trange) || all(trange==0)
                trange = [obj.tHRF(1), obj.tHRF(end)];
            end
            if ~exist('width','var') || isempty(width)
                width = 12;
            end
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1;
            end
            tblcells = TableCell.empty();
            if isa(obj.dcAvg, 'DataClass')
                dataTimeSeries = obj.dcAvg(iBlk).GetDataTimeSeries('');
                h = waitbar_improved(0, sprintf('Generating table cells for export ... 0%% complete.'));
                % Data rows
                for iCond = 1:length(CondNames)
                    waitbar_improved(iCond/length(CondNames), h, sprintf('Generating table cells for export ... %d%% complete.', uint32(100 * iCond/length(CondNames))));
                    measListIdxs = obj.dcAvg(iBlk).GetMeasurementListIdxs(iCond);
                    for iCh = measListIdxs
                        iT = (obj.dcAvg.time >= trange(1)) & (obj.dcAvg.time <= trange(2));
                        meanData = mean(dataTimeSeries(iT,iCh));
                        if isnan(meanData)
                            cname  = 'N/A';
                        else
                            cname = sprintf('%s%0.5e', blanks(meanData>=0), meanData);
                        end
                        tblcells(iCond, mod(iCh-1, length(measListIdxs))+1) = TableCell(cname, width);
                    end
                end
                close(h);
            end
        end

        % ----------------------------------------------------------------------------------
        function tblcells = GenerateTableCells_HRF(obj, CondNames, iBlk)
            tblcells = [];

            if ~isa(obj.dcAvg, 'DataClass')
                return
            end
            if isempty(obj.dcAvg)
                return
            end
            if obj.dcAvg.IsEmpty()
                return
            end

            if nargin<3
                iBlk = 1;
            end

            tblcells = TableCell.empty();

            dataTimeSeries  = obj.dcAvg(iBlk).GetDataTimeSeries();
            time            = obj.dcAvg(iBlk).GetTime();
            measList        = obj.dcAvg(iBlk).measurementList;

            %%%% Row 1: Header row containing stim condition names
            tblcells(2,1) = TableCell('', 12);      % Make space for time column
            for iCh = 1:length(measList)
                tblcells(1,iCh+1) = TableCell(sprintf('%s', CondNames{measList(iCh).dataTypeIndex}), 12);
            end

            %%%% Row 2: Header row containing time label followed by Hb types with source,detector indices
            tblcells(2,1) = TableCell('time', 12);
            for iCh = 1:length(measList)
                tblcells(2,iCh+1) = TableCell(sprintf('%s,%d,%d', measList(iCh).dataTypeLabel, measList(iCh).sourceIndex, measList(iCh).detectorIndex), 12);
            end

            %%%% Rows 3 and greater are time points and data for all channels
            h = waitbar_improved(0, sprintf('Generating table cells for export ... 0%% complete.'));
            for t = 1:size(dataTimeSeries,1)
                if mod(t,100)==0
                    waitbar_improved(t/size(dataTimeSeries,1), h, sprintf('Generating table cells for export ... %d%% complete.', uint32(100 * t/size(dataTimeSeries,1))));
                end

                % time
                cname = sprintf('%s%0.3f', blanks(time(t)>=0), time(t));
                tblcells(t+2,1) = TableCell(cname, 12);

                % data
                for iCh = 1:length(measList)
                    if isnan(dataTimeSeries(t,iCh))
                        cname  = 'NaN';
                    else
                        cname = sprintf('%s%0.5e', blanks(dataTimeSeries(t,iCh)>=0), dataTimeSeries(t,iCh));
                    end
                    tblcells(t+2,iCh+1) = TableCell(cname, 12);
                end
            end
            close(h);
        end

        % ----------------------------------------------------------------------------------
        function tblcells = GenerateTableCells_MeanHRF(obj, name, CondNames, trange, iBlk)
            tblcells = [];

            if ~isa(obj.dcAvg, 'DataClass')
                return
            end
            if isempty(obj.dcAvg)
                return
            end
            if obj.dcAvg.IsEmpty()
                return
            end

            if nargin<3
                iBlk = 1;
            end

            tblcells = TableCell.empty();

            dataTimeSeries  = obj.dcAvg(iBlk).GetDataTimeSeries();
            time            = obj.dcAvg(iBlk).GetTime();
            measList        = obj.dcAvg(iBlk).measurementList;

            %%%% Row 1: Header row containing stim condition names
            tblcells(2,1) = TableCell('', 12);      % Make space for time column
            for iCh = 1:length(measList)
                tblcells(1,iCh+1) = TableCell(sprintf('%s', CondNames{measList(iCh).dataTypeIndex}), 12);
            end

            %%%% Row 2: Header row containing processing element label followed by Hb types with source,detector indices
            tblcells(2,1) = TableCell(sprintf('Name'), 12);
            for iCh = 1:length(measList)
                tblcells(2,iCh+1) = TableCell(sprintf('%s,%d,%d', measList(iCh).dataTypeLabel, measList(iCh).sourceIndex, measList(iCh).detectorIndex), 12);
            end

            %%%% Row 3: processing element name followed by mean HRF data for all channels
            h = waitbar_improved(0, sprintf('Generating table cells for export ... 0%% complete.'));

            % Name of processing element
            tblcells(3,1) = TableCell(name, 12);

            % Mean HRF data
            for iCh = 1:length(measList)
                iT = (time >= trange(1)) & (time <= trange(2));
                if isnan(dataTimeSeries(iT,iCh))
                    cname  = 'NaN';
                else
                    cname = sprintf('%s%0.5e', blanks(mean(dataTimeSeries(iT,iCh)) >= 0), mean(dataTimeSeries(iT,iCh)));
                end
                tblcells(3,iCh+1) = TableCell(cname, 12);
            end
            close(h);
        end

        % ----------------------------------------------------------------------------------
        function tbl = ExportHRF(obj, filename, CondNames, iBlk)
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1;
            end

            % Generate table cells
            tblcells = obj.GenerateTableCells_HRF(CondNames, iBlk);

            [p, f] = fileparts(obj.SetFilename(filename));
            filename = [filesepStandard(p, 'nameonly:dir'), f];

            % Create table export data to file
            tbl = ExportTable(filename, 'HRF', tblcells);
        end

        % ----------------------------------------------------------------------------------
        function filename = ExportHRF_GetFilename(obj, filename)
            [p, f] = fileparts(obj.SetFilename(filename));
            filename = [filesepStandard(p, 'nameonly:dir'), f];

            % Create table export data to file
            tbl = ExportTable(filename, 'HRF');
            filename = tbl.GetFilenameFull();
        end

        % ----------------------------------------------------------------------------------
        function tbl = ExportMeanHRF(obj, filename, CondNames, trange, iBlk)
            if ~exist('iBlk','var') || isempty(iBlk)
                iBlk = 1;
            end

            [p, f] = fileparts(obj.SetFilename(filename));
            filename = [filesepStandard(p, 'nameonly:dir'), f];

            % Generate table cells
            tblcells = obj.GenerateTableCells_MeanHRF(f, CondNames, trange, iBlk);

            % Create table export data to file
            tbl = ExportTable(filename, 'HRF Mean', tblcells);
        end

        % ----------------------------------------------------------------------------------
        function tbl = ExportMeanHRF_Alt(obj, filename, tblcells)
            [p, f] = fileparts(obj.SetFilename(filename));
            filename = [filesepStandard(p, 'nameonly:dir'), f];

            % Create table export data to file
            tbl = ExportTable(filename, 'HRF mean', tblcells);
        end

    end

end

author: BUNPC


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Precompute all w_{ij}
% Xp is the likelihood of the optimal assignments given
% the current output set
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [W, Xp] = getW(B, S, param)

P = zeros(size(B,2));
for i = 1:size(B,2)
    P(i,:) = getIOUFloat(B',B(:,i)');
end
P = bsxfun(@times, P, S(:));
P = [P param.lambda*ones(size(B,2),1)];
P = bsxfun(@times, P, 1./sum(P,2));
W = log(P);
Xp = W(:,end);
W = W(:,1:end-1);

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D
% shape modeling and analysis toolkit.
% It is a software package developed at Shenlab in Center for Neuroimaging,
% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)
% It is available to the scientific community as copyright freeware
% under the terms of the GNU General Public Licence.
%
% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University
%
% This file is part of SPHARM-MAT.
%
% SPHARM-MAT 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.
%
% SPHARM-MAT 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 SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function patch_overlay(vertices, faces, signal, threshold, type, vtnorm, cmap,windowHandle, fname)

figure(windowHandle);
set(gcf,'PaperPositionMode','auto');
colormap(cmap);

patch_lighta(vertices, faces);
maxSG = max(signal);
minSG = min(signal);

FValpha = ones(size(vertices,1),1);
switch type
    case 'p-value'
        idx = find(abs(signal)>(threshold));
        FValpha(idx) = 0;

        hold on;
        patch('faces', faces,'vertices',vertices, 'FaceVertexCData',signal, 'EdgeColor', 'none', ...
            'VertexNormals',vtnorm,'FaceVertexAlpha',FValpha,'FaceColor','interp', 'FaceAlpha','interp');
        hold off;
        colorbar;

    case 't-map'
        idx = find(abs(signal)<threshold);
        FValpha(idx) = 0;

        hold on;
        patch('faces', faces,'vertices',vertices, 'FaceVertexCData',signal, 'EdgeColor', 'none', ...
            'VertexNormals',vtnorm,'FaceVertexAlpha',FValpha,'FaceColor','interp', 'FaceAlpha','interp');
        hold off;
        colorbar('location', 'EastOutside');
end

title(sprintf('%s.mat\n%s',strrep(fname,'_','-'),type));

return;

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
function [xEst,PEst]=batchLSNonlinMeasLinDyn(xInit,z,h,F,R,kD,HJacob,numIter)
%%BATCHLSNONLINMEASLINDYN Perform batch least squares state estimation
%                      refinement under a nonlinear measurement model and a
%                      linear dynamic model without process noise. The
%                      iterative nonlinear least squares algorithm is used.
%
%INPUTS: xInit The initial estimate of the target state at the time of the
%              kDth measurement that is to be refined through iteration.
%            z The zDim X N matrix of measurements for the whole batch. It
%              is assumed that the measurements have the same
%              dimensionality over the batch.
%            h A NX1 cell array of function handles for the measurement
%              function that transform the state into the measurement
%              domain at each step. If the same measurement function is
%              used for all steps in the batch, then h can just be the
%              single function handle used.
%            F An xDim X xDim X (N-1) hypermatrix of matrices. The state at
%              discrete-time k+1 is modeled as F(:,:,k) times the state at
%              time k with no process noise. Alternatively, if all of the
%              state transition matrices are the same, one can just pass a
%              single xDim X xDim matrix. Note that all of the F matrices
%              must be invertible if kD is not equal to one.
%            R The zDim X zDim X N hypermatrix of measurement covariance
%              matrices. Alternatively, if all of the measurement
%              covariance matrices are the same, one can just pass a
%              single zDim X zDim matrix.
%           kD The discrete time-step at which the smoothed state estimate
%              is desired, where z(:,1) is at discrete time-step 1 (not 0).
%       HJacob A NX1 cell array of function handles for the measurement
%              Jacobian matrix that each takes the target state as a
%              parameter. If a single measurement Jacobian matrix is used
%              for all steps of the batch, then HJacob can just be the
%              single function handle used. If an empty matrix is passed or
%              HJacob is not provided, then HJacob will be found using
%              numerical differentiation via the numDiff function with
%              default parameters.
%      numIter The numer of iterations to perform in the nonlinear least
%              squares algorithm. If this parameter is omitted, the
%              default is 10.
%
%OUTPUTS: xEst The refined batch state estimate at step kD.
%         PEst A covariance matrix estimate that goes with the state
%              estimate.
%
%The algorithm is an implementation of the nonlinear iterative least
%squares algorithm of Chapter 3.4 of [1]. The covariance provided is the
%covariance associated with the algorithm. The measurement matrices for the
%propagated state as well as the transition matrices for the propagated
%state are taken as derived in Section 3.3.2 of [2].
%
%The algorithm is likely to diverge if xEst is particularly bad. A more
%robust albeit slower estimation algorithm is
%batchLSNonlinMeasLinDynProcNoise, which also supports the inclusion of
%process noise.
%
%REFERENCES:
%[1] Y. Bar-Shalom, X. R. Li, and T. Kirubarajan, Estimation with
%    Applications to Tracking and Navigation. New York: John Wiley and
%    Sons, Inc, 2001.
%[2] A. B. Poore, B. J. Slocumb, B. J. Suchomel, F. H. Obermeyer, S. M.
%    Herman, and S. M. Gadaleta, "Batch maximum likelihood (ML) and maximum
%    a posteriori (MAP) estimation with process noise for tracking
%    applications," in Proceedings of SPIE: Signal and Data Processing of
%    Small Targets, vol. 5204, San Diego, CA, 3 Aug. 2003, pp. 188-199.
%
%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

if(nargin<8)
    numIter=10;
end
if(nargin<7)
    HJacob=[];
end

xEst=xInit;

zDim=size(z,1);
xDim=size(xEst,1);
numSteps=size(z,2);

if(isa(h,'function_handle'))
    h=repmat({h},[numSteps,1]);
end

if(isa(HJacob,'function_handle'))
    HJacob=repmat({HJacob},[numSteps,1]);
end

if(isempty(HJacob))
    HJacob=cell(numSteps,1);
    for curStep=1:numSteps
        HJacob{curStep}=@(x)numDiff(x,h{curStep},zDim);
    end
end

if(size(R,3)==1)
    R=repmat(R,[1,1,numSteps]);
end

J=zeros(zDim*numSteps,xDim);
zPredStacked=zeros(zDim*numSteps,1);

RStackedInv=inv(blkDiagRep(R));

if(size(F,3)==1)
    F=repmat(F,[1,1,numSteps-1]);
end

transMats=getTransMats(F,kD);

for curIter=1:numIter
    minIdx=1;
    for curStep=1:numSteps
        maxIdx=minIdx+zDim-1;

        xCur=transMats(:,:,curStep)*xEst;
        J(minIdx:maxIdx,:)=HJacob{curStep}(xCur)*transMats(:,:,curStep);

        zPredStacked(minIdx:maxIdx)=h{curStep}(xCur);
        minIdx=maxIdx+1;
    end

    xEst=xEst+lsqminnorm(J'*RStackedInv*J,J'*RStackedInv*(z(:)-zPredStacked));
end

%If a covariance matrix estimate is desired.
if(nargout==2)
    minIdx=1;
    for curStep=1:numSteps
        maxIdx=minIdx+zDim-1;

        xCur=transMats(:,:,curStep)*xEst;
        J(minIdx:maxIdx,:)=HJacob{curStep}(xCur)*transMats(:,:,curStep);

        minIdx=maxIdx+1;
    end

    PEst=pinv(J'*RStackedInv*J);
end

end

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

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function [itrfin] = multisvm( T,C,test )
%MULTISVM(3.0) classifies the class of given training vector according to the
% given group and gives us result that which class it belongs.
% We have also to input the testing matrix

%Inputs: T=Training Matrix, C=Group, test=Testing matrix
%Outputs: itrfin=Resultant class(Group,USE ROW VECTOR MATRIX) to which tst set belongs

%----------------------------------------------------------------------%
% IMPORTANT: DON'T USE THIS PROGRAM FOR CLASS LESS THAN 3,             %
%            OTHERWISE USE svmtrain,svmclassify DIRECTLY or            %
%            add an else condition also for that case in this program. %
%            Modify required data to use Kernel Functions and Plot also%
%----------------------------------------------------------------------%
%                       Date:11-08-2011(DD-MM-YYYY)                    %
% This function for multiclass Support Vector Machine is written by
% ANAND MISHRA (Machine Vision Lab. CEERI, Pilani, India)
% and this is free to use. email: anand.mishra2k88@gmail.com

% Updated version 2.0 Date:14-10-2011(DD-MM-YYYY)
% Updated version 3.0 Date:04-04-2012(DD-MM-YYYY)

itrind=size(test,1);
itrfin=[];
Cb=C;
Tb=T;
for tempind=1:itrind
    tst=test(tempind,:);
    C=Cb;
    T=Tb;
    u=unique(C);
    N=length(u);
    c4=[];
    c3=[];
    j=1;
    k=1;
    if(N>2)
        itr=1;
        classes=0;
        cond=max(C)-min(C);
        while((classes~=1)&&(itr<=length(u))&& size(C,2)>1 && cond>0)
        %This while loop is the multiclass SVM Trick
            c1=(C==u(itr));
            newClass=c1;
            svmStruct = svmtrain(T,newClass,'kernel_function','rbf');   % I am using rbf kernel function, you must change it also
            classes = svmclassify(svmStruct,tst);

            % This is the loop for Reduction of Training Set
            for i=1:size(newClass,2)
                if newClass(1,i)==0;
                    c3(k,:)=T(i,:);
                    k=k+1;
                end
            end
        T=c3;
        c3=[];
        k=1;

            % This is the loop for reduction of group
            for i=1:size(newClass,2)
                if newClass(1,i)==0;
                    c4(1,j)=C(1,i);
                    j=j+1;
                end
            end
        C=c4;
        c4=[];
        j=1;

        cond=max(C)-min(C); % Condition for avoiding group
                            %to contain similar type of values
                            %and the reduce them to process

            % This condition can select the particular value of iteration
            % base on classes
            if classes~=1
                itr=itr+1;
            end
        end
    end

valt=Cb==u(itr);		% This logic is used to allow classification
val=Cb(valt==1);		% of multiple rows testing matrix
val=unique(val);
itrfin(tempind,:)=val;
end

end

% Give more suggestions for improving the program.

author: Sable

repo: mcbench-benchmarks


text:
function setup_paths()

% Add the neccesary paths

[pathstr, name, ext] = fileparts(mfilename('fullpath'));

% Tracker implementation
addpath(genpath([pathstr '/implementation/']));

% Runfiles
addpath([pathstr '/runfiles/']);

% Utilities
addpath([pathstr '/utils/']);

% The feature extraction
addpath(genpath([pathstr '/feature_extraction/']));

% Matconvnet
addpath([pathstr '/external_libs/matconvnet/matlab/mex/']);
addpath([pathstr '/external_libs/matconvnet/matlab']);
addpath([pathstr '/external_libs/matconvnet/matlab/simplenn']);

% PDollar toolbox
addpath(genpath([pathstr '/external_libs/pdollar_toolbox/channels']));

% Mtimesx
addpath([pathstr '/external_libs/mtimesx/']);

% mexResize
addpath([pathstr '/external_libs/mexResize/']);

repo: UDT


text:
function v = roiToggleFilledPerimeter(v);
%
%  v = roiToggleFilledPerimeter(v);
%
%Author: Wandell
%Purpose:
%   Toggle the fill perimeter drawing state.  When on, the perimeters are
%   always continuous.  When off, some perimeters appear as a set of open
%   loops.
%
% v = FLAT{1};

t = viewGet(v,'filledperimeterstate');
if isempty(t), t = 0; end
v = viewSet(v,'filledperimeterstate',1 - t);

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [filtered_outpt] = coax_simulator(Samples,rate,t,f,inpt,Zr, ...
    L,b,a,Ur,Er,cond,var_coax,T0,cutoff,ord_but,considerBeta)

format long;

%% ########################### Input Signal ############################
INPT=fftshift(fft(inpt));

%% ########################## Coaxial Cable ############################
H  = coaxTF(f,Zr,L,b,a,Ur,Er,cond,considerBeta);
FRESH_OUTPT = INPT.*H;
fresh_outpt = real(ifft(ifftshift(FRESH_OUTPT)));

%% #################### Noise from Coaxial Cable #######################
AWGNoise = sqrt(var_coax)*randn(size(t));
noisy_out = fresh_outpt + AWGNoise;

%% ########################### Low Pass Filter #########################
    filtrTF = buttLPF(f,cutoff,ord_but);                %Butterworth LPF

%% ##################### Thermal Noise of receiver #####################
k = 1.38e-23;   % Boltzmann's Const. (W/K-Hz)
noise_SD = sqrt(k*T0*cutoff*Zr);
noise_variance = noise_SD^2;
thermal_noise = noise_SD*randn(size(t));
outpt = noisy_out + thermal_noise;

%% ##################### Output Calculation ############################
OUTPT = fftshift(fft(outpt));
FILTERED_OUTPT = OUTPT.*filtrTF;
filtered_outpt = real(ifft(ifftshift(FILTERED_OUTPT)));


text:
% Author: Ricardo Baptista and Matthias Poloczek
% Date:   June 2018
%
% See LICENSE.md for copyright information
%

function output = SA_spears(objective, inputs)
% SIMULATED_ANNEALING_SPEARS: Function runs simulated annealing algorithm using the
% SPEARS algorithm for optimizing binary functions (MAX-SAT). The reference with
% the description of the algorithm and the parameters can be found in:
%
% An Experimental Evaluation of Fast Approximation Algorithms for the Maximum
% Satisfiability Problem by: MATTHIAS POLOCZEK and DAVID P. WILLIAMSON

% Extract n_vars
n_vars = inputs.n_vars;

% Set temperature limits
max_temp = 10;
min_temp = 0.01;

% Set counter and T
counter  = 0;
T = max_temp;

% Set initial condition and evaluate objective function
new_x   = sample_models(1,n_vars);
new_obj = objective(new_x);

% Set best variables
best_x   = new_x;
best_obj = new_obj;

% Declare vectors to save solutions
model_iter = zeros(0,n_vars);
obj_iter   = zeros(0,1);
time_iter  = zeros(0,1);

% Run simulated annealing
while(T >= min_temp)

    % Increment counter
    counter = counter + 1;
    sa_iter = tic;

    % Decrease T according to cooling schedule
    T = T*exp(-1/n_vars);

    %% Compute change from flipping each variable
    for i=1:n_vars

        % compute change in objective from flipping bit
        temp_x  = new_x; temp_x(i) = 1 - temp_x(i);
        temp_df = objective(temp_x) - new_obj;

        % Compute probability of flipping variable
        p = 1/(1 + exp(-temp_df/T));
        if rand < p
            new_x = temp_x;
        end

    end

    % Evaluate objective function at current solution
    new_obj = objective(new_x);

    % Update best solution
    if new_obj < best_obj
        best_x = new_x;
        best_obj = new_obj;
    end

    % save solution
    model_iter = [model_iter; best_x];
    obj_iter   = [obj_iter; best_obj];
    time_iter  = [time_iter; toc(sa_iter)];

end

% save outputs
output = struct;
output.objVals  = obj_iter;
output.optModel = model_iter;
output.runTime  = time_iter;

end

author: baptistar

repo: BOCS

save_path: github-repos/MATLAB/baptistar-BOCS


text:
function [imo,rois] = wsddn_get_batch(images, imdb, batch, opts)
% cnn_wsddn_get_batch  Load, preprocess, and pack images for CNN evaluation

if isempty(images)
  imo = [] ;
  rois = [] ;
  return ;
end

% fetch is true if images is a list of filenames (instead of
% a cell array of images)
fetch = ischar(images{1}) ;

% prefetch is used to load images in a separate thread
prefetch = fetch & opts.prefetch ;

% pick size
imSize = imdb.images.size(batch(1),:);
factor = min(opts.scale(1)/imSize(1),opts.scale(1)/imSize(2));
height = floor(factor*imSize(1));

if prefetch
  vl_imreadjpeg(images, 'numThreads',opts.numThreads,'Resize',height,'prefetch') ;
  imo = [] ;
  rois = [] ;
  return ;
end

if fetch
  ims = vl_imreadjpeg(images,'numThreads',opts.numThreads,'Resize',height) ;
else
  ims = images ;
end

for i=1:numel(images)
  % acquire image
  if isempty(ims{i})
    imt = imread(images{i}) ;
    if size(imt,3) == 1
      imt = cat(3, imt, imt, imt) ;
    end

    ims{i} = imresize(imt,factor,'Method',opts.interpolation);
    ims{i} = single(ims{i}) ; % faster than im2single (and multiplies by 255)
  end
end

bboxes = cell(1,numel(batch));
nBoxes = 0;
for b=1:numel(batch)
  bboxes{b} = double(imdb.images.boxes{batch(b)});
  nBoxes = nBoxes + size(bboxes{b},1);
end

rois = zeros(nBoxes,5);
countr = 0;

maxW = 0;
maxH = 0;

for b=1:numel(batch)

  hw = imdb.images.size(batch(b),:);
  h = hw(1);
  w = hw(2);

  imsz = size(ims{b});

  if opts.flip(b)
    im = ims{b};
    ims{b} = im(:,end:-1:1,:);

    bbox = bboxes{b};
    bbox(:,[2,4]) = w + 1 - bbox(:,[4,2]);
    bboxes{b} = bbox;
  end

  maxH = max(imsz(1),maxH);
  maxW = max(imsz(2),maxW);

  % adapt bounding boxes into new coord
  bbox = bboxes{b};
  if any(bbox(:)<=0)
    error('bbox error');
  end
  nB = size(bbox,1);
  tbbox = scale_box(bbox,[h,w],imsz);
  if any(tbbox(:)<=0)
    error('tbbox error');
  end

  rois(countr+1:countr+nB,:) = [b*ones(nB,1),tbbox];
  countr = countr + nB;
end

% rois = single(rois);
depth = size(ims{1},3);
imo = zeros(maxH,maxW,depth,numel(batch),'single');

if isempty(opts.averageImage)
  avgIm = [];
elseif numel(opts.averageImage)==depth
  avgIm = opts.averageImage;
end

for b=1:numel(batch)
  sz = size(ims{b});

  imo(1:sz(1),1:sz(2),:,b) = single(ims{b});

  if ~isempty(avgIm)
    imo(1:sz(1),1:sz(2),:,b) = single(bsxfun(@minus,imo(1:sz(1),1:sz(2),:,b),opts.averageImage));
  end
  if ~isempty(opts.rgbVariance)
    imo(1:sz(1),1:sz(2),:,b) = bsxfun(@plus, imo(1:sz(1),1:sz(2),:,b), ...
        reshape(opts.rgbVariance * randn(3,1), 1,1,3)) ;
  end
end

function boxOut = scale_box(boxIn,szIn,szOut)

  h = szIn(1);
  w = szIn(2);

  bxr = 0.5 * (boxIn(:,2)+boxIn(:,4)) / w;
  byr = 0.5 * (boxIn(:,1)+boxIn(:,3)) / h;

  bwr = (boxIn(:,4)-boxIn(:,2)+1) / w;
  bhr = (boxIn(:,3)-boxIn(:,1)+1) / h;

  % boxIn center in new coord
  byhat = (szOut(1) * byr);
  bxhat = (szOut(2) * bxr);

  % relative width, height
  bhhat = szOut(1) * bhr;
  bwhat = szOut(2) * bwr;

  % transformed boxIn
  boxOut = [max(1,round(byhat - 0.5 * bhhat)),...
    max(1,round(bxhat - 0.5 * bwhat)), ...
    min(szOut(1),round(byhat + 0.5 * bhhat)),...
    min(szOut(2),round(bxhat + 0.5 * bwhat))];

author: hbilen

repo: WSDDN

save_path: github-repos/MATLAB/hbilen-WSDDN


text:
function display(sVF,varargin)
% standard output

displayClass(sVF,inputname(1),varargin{:});

if length(sVF) > 1, disp([' size: ' size2str(sVF)]); end

end

author: mtex-toolbox

repo: mtex

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


text:
function ye = exact_solution(t,x,c)

	% Function called: profile

yyy = x;
for j = 1:length(x),   yyy(j) = profile(x(j) - c*t); end
ye = yyy;

repo: Aero-matlab


text:
%Voice Based Biometric System
%By Ambavi K. Patel.

function op1=cmpr(cb,cd,n,k,r,c)
op1(1:n)=0;
for j=1:n      % finding euclidian distance

  x(j)=sqrt(sum((cb(1,1:r)-cd((n*(k-1))+j,1:r)).^2));
    y(j)=sqrt(sum((cb(1,r+1:r+c)-cd((n*(k-1))+j,r+1:r+c)).^2));

    if x(j)<0.05 && y(j)<3     % comparing with threshold values
        op1(j)=1;
    else op1(j)=0;
    end;
end;
% display(x);
% display(y);
%


text:
function linplus_test151 ( )

%*****************************************************************************80
%
%% TEST151 tests R8BB_INDICATOR.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 March 2009
%
%  Author:
%
%    John Burkardt
%
  n1 = 6;
  n2 = 2;
  n = n1 + n2;
  ml = 1;
  mu = 1;
  na = ( 2 * ml + mu + 1 ) * n1 + 2 * n1 * n2 + n2 * n2;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST151\n' );
  fprintf ( 1, '  R8BB_INDICATOR sets up an indicator matrix.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Matrix order N     = %d\n', n );
  fprintf ( 1, '  Matrix suborder N1 = %d\n', n1 );
  fprintf ( 1, '  Matrix suborder N2 = %d\n', n2 );
  fprintf ( 1, '  Lower bandwidth ML = %d\n', ml );
  fprintf ( 1, '  Upper bandwidth MU = %d\n', mu );
%
%  Set the matrix.
%
  a = r8bb_indicator ( n1, n2, ml, mu );

  r8bb_print ( n1, n2, ml, mu, a, '  The indicator matrix:' );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
classdef (Abstract) Base < matlabshared.libiio.base & ...
        matlab.system.mixin.CustomIcon
    %AD9680 Base Class

    properties (Nontunable)
        %SamplesPerFrame Samples Per Frame
        %   Number of samples per frame, specified as an even positive
        %   integer from 2 to 16,777,216. Using values less than 3660 can
        %   yield poor performance.
        SamplesPerFrame = 2^15;
    end

    properties(Nontunable, Hidden)
        Timeout = Inf;
        kernelBuffersCount = 2;
        dataTypeStr = 'int16';
    end

    properties (Abstract, Hidden, Constant)
       Type
    end

    properties (Hidden, Constant)
        ComplexData = false;
    end

    methods
        %% Constructor
        function obj = Base(varargin)
            % Returns the matlabshared.libiio.base object
            coder.allowpcode('plain');
            obj = obj@matlabshared.libiio.base(varargin{:});
        end
        % Check SamplesPerFrame
        function set.SamplesPerFrame(obj, value)
            validateattributes( value, { 'double','single' }, ...
                { 'real', 'positive','scalar', 'finite', 'nonnan', 'nonempty','integer','>',0,'<',2^20+1}, ...
                '', 'SamplesPerFrame');
            obj.SamplesPerFrame = value;
        end
    end

    %% API Functions
    methods (Hidden, Access = protected)

        function icon = getIconImpl(obj)
            icon = sprintf(['AD9680 ',obj.Type]);
        end

        function setupInit(~)
            % Unused
        end

    end

    %% External Dependency Methods
    methods (Hidden, Static)

        function tf = isSupportedContext(bldCfg)
            tf = matlabshared.libiio.ExternalDependency.isSupportedContext(bldCfg);
        end

        function updateBuildInfo(buildInfo, bldCfg)
            % Call the matlabshared.libiio.method first
            matlabshared.libiio.ExternalDependency.updateBuildInfo(buildInfo, bldCfg);
        end

        function bName = getDescriptiveName(~)
            bName = 'AD9680';
        end

    end
end

author: analogdevicesinc