text:
function declare_properties(varargin)
% Declare properties of a function.
% declare_properties('Property',value,'Property',value, ...)
%
% declare_properties must be a top-level statement in the function (like persistent) that must come
% before arg_define. The function must use varargin in its argument list.
%
% This construct can be used to declare any key-value properties for a function which can later be
% retrieved using arg_report('properties',@myfunction). BCILAB looks for certain properties in
% plugin functions (e.g., filters, dataset_editing, machine_learning), to support improved
% integration of these functions into the GUI and the evaluation system.
%
% In:
%   Options...: list of name-value pairs.
%
%               Ordering hints applicable for filters (respected by flt_pipeline) are the following:
%                'depends': expresses that some other filter(s) *must* have been called before running
%                           the filter whose properties are being declared (this is usually due to some
%                           required meta-data that is supplied by that other filter)
%                'cannot_follow': expresses that the filter being declared cannot follow after some
%                                 other filter(s) (this is usually due to destructive
%                                 editing performed by those other filters)
%                'cannot_precede': expresses that the filter being declared cannot precede some
%                                  other filter(s)
%                'follows': expresses that the filter being declared *prefers* to follow some
%                           other filter(s) (this is usually for numeric or efficiency reasons)
%                'precedes': expresses that the filter being declared *prefers* to precede some
%                           other filter(s) (this is usually for numeric or efficiency reasons)
%
%               Optional properties respected by the evaluation system (for improved usability):
%                'independent_channels': specify that this filter does not transfer information
%                                        across channels (e.g. channel selection, FIR filter)
%                                        (allows the online system to auto-infer which data channels
%                                        are actually required by a given BCI model)
%                'independent_trials': specify that this filter does transfer information
%                                      across second-length or larger time scales (on the order of
%                                      the duration of a trial or larger); this determines whether
%                                      the filter will be called repeatedly for each partition of the
%                                      data in a cross-validation and other offline analyses
%
%               Further optional properties include:
%                'name': specify the GUI/human-readable name of this function (auto-determined if
%                        left unspecified)
%                'experimental': whether the function implementation is experimental or otherwise
%                                in "prototype" stage
%                'deprecated': whether the function is deprecated
%
% Examples:
%   function myfunction(...,varargin)
%
%   % declare a property called 'name', and assign the string 'MyFunction' to it, and another
%   % property called 'price', with some value attached
%   declare_properties('name','MyFunction','price',1999)
%
%   % in a signal processing function, declare the name of the function as it should appear in the
%   % GUI panel (default is the name of the file without the flt_ / set_ prefix)
%   declare_properties('name','MyFilter')
%
%   % in a signal processing function, declare that the filter depends on two other (previously applied)
%   % filters (here: flt_ica and set_fit_dipoles)
%   declare_properties('depends',{'flt_ica','set_flt_dipoles'});
%
%   % in a signal processing function, declare a hint that the filter typically follows some other
%   % filter in the pipeline (if that other filter was enabled; here: flt_resample)
%   declare_properties('follows','flt_resample');
%
%   % in a signal processing function, declare a hint that the filter typically precedes some other
%   % filters in the pipeline (if that other filter was enabled; here: flt_iir and flt_fir)
%   declare_properties('precedes',{'flt_iir','flt_fir'});
%
%   % in a signal processing function, declare the constraint that the filter cannot follow some other
%   % filter
%   declare_properties('cannot_follow','set_makepos');
%
%   % in a signal processing function, declare the constraint that the filter cannot follow some other
%   % filter
%   declare_properties('cannot_precede','set_makepos');
%
%   % in a signal processing function, declare that the contents of each output channel produced
%   % by the filter depend only on the contents of the corresponding input channel (i.e. there is not
%   % cross-mixing of channels (default is false)
%   declare_properties('independent_channels',true);
%
%   % in a signal processing function, declare that the contents of each output trial depend not
%   % only on data of the respective input trial, but perhaps on other trials, as well (i.e., there is
%   % cross-mixing over time at trial granularity); the effect of this is that the respective filter
%   % will be executed once per cross-validation fold
%   declare_properties('independent_trials',false);
%
% See also:
%   arg_report
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-11-02

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

caller_args = evalin('caller','varargin');
if length(caller_args)>1 && isequal(caller_args(end-1:end),{'__arg_report__','properties'})
    % properties are being requested via arg_report; return them as a struct
    caller = hlp_getcaller();

    % collect properties as name-value pairs
    if ~iscellstr(varargin(1:2:end))
        error('The given arguments must be name-value pairs.'); end
    nvps = reshape([{'depends',{},'cannot_follow',{},'cannot_precede',{},'follows',{},'precedes',{},'independent_channels',[], ...
        'independent_trials',[],'name',caller,'deprecated',false,'experimental',false} varargin],2,[]);
    % find the indices of the last assignment for each name and convert them to a struct
    [s,inds] = sort(nvps(1,:)); inds(strcmp(s(1:end-1),s(2:end))) = [];
    properties = cell2struct(nvps(2,inds),nvps(1,inds),2);

    if isempty(properties.independent_trials) && (strncmp(caller,'flt_',4) || strncmp(caller,'set_',4))
        properties.independent_trials = false;
        % warn about this omission: in practice, this means that this filter and all that come after it
        % in a pipeline will be recomputed for every partition of the data during (nested) cross-validation
        % (perhaps 10x or 100x as often as necessary)
        disp_once('Note: The function "%s" does not declare the property independent_trials; assuming that it is false. This may be a conservative assumption that can have massive performance cost during offline processing. Consider declaring the property explicitly in the declare_properties() clause.',caller);
    end

    if isempty(properties.independent_channels) && (strncmp(caller,'flt_',4) || strncmp(caller,'set_',4))
        properties.independent_channels = false;
        % warn about this omission: in practice, this often means that BCILAB has to assume that a given
        % model requires all channels that were present in the source data set -- even if it selects
        % only a subset somewhere in its filter pipeline (e.g., excluding peripheral measures). If such
        % channels are not available in an online stream, the model will fail to work, perhaps
        % unneccessarily.
        disp_once('Note: The function "%s" does not declare the property independent_channels; assuming that it is false. This may be a conservative assumption that can make it unnecessariy difficult to set up online processing. Consider declaring the property explicitly in the declare_properties() clause.',caller);
    end

    % report them
    arg_issuereport(properties);
end

repo: REST


text:
%VEX Convert skew-symmetric matrix to vector
%
% V = VEX(S) is the vector (3x1) which has the skew-symmetric matrix S (3x3)
%
%           | 0   -vz  vy|
%           | vz   0  -vx|
%           |-vy   vx  0 |
%
% Notes::
% - This is the inverse of the function SKEW().
% - No checking is done to ensure that the matrix is actually skew-symmetric.
% - The function takes the mean of the two elements that correspond to each unique
%   element of the matrix, ie. vx = 0.5*(S(3,2)-S(2,3))
%
% See also SKEW.

% Copyright (C) 1993-2015, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

function v = vex(S)
    if isrot(S) || ishomog(S)
        v = 0.5*[S(3,2)-S(2,3); S(1,3)-S(3,1); S(2,1)-S(1,2)];
    else
        error('argument must be a 3x3 matrix');
    end

author: Allopart

repo: rbpf-gmapping


text:
%% BEARING FAULT ANALYSIS
% This program demonstrates how you can analyze the operation of a bearing,
% and how faults can be found by means of Signal Processing.
%
% _Created by Roni Peer_, Last Revision: *December 30th, 2011*
%%

%% Why to use this program
% In order to fully leverage this program, I recommend reading some theory,
% as can be found on Wikipedia or other textbooks. This program takes a
% ball-bearing, simulates a fault in its inner or outer ring, and tries to
% show how you can view the fault, by means of finding the resonance
% frequencies.

%% Menus and Options
% There are several key options you can select with this program.
%% Bearing Fault type:
% On the right popup menu select between the *"Inner Ring"* or *"Outer
% Ring"*
% fault. An inner ring fault would generate a sinewave-like signal, an
% Outer ring fault would generate a pulsing signal.
%
%% Rotation Speed
% A slider of the Rotation Speed (in RPM), in which the bearing is
% operating. Input range is between 1 and 2000.
%
%% Analysis Type
% A pop-up menu to choose between 4 types of analysis: *Spectral Analysis,
% Kurtosis, Envelope, and Time/Frequency*.
%
%% Kurtosis Option
% The Kurtosis option on the pop-up menu will generate 3 Kurtosis numbers
% (compatible with the 3 different resonances, of 120, 500, 1500
% [rad/sec]), which will be shown below.
%
%% Filter for Envelope
% The 'Filter For Envelope' button enables a band pass filter over a preset
% bandwidth of the envelope. To set the bandwidth press the *'Filter For
% Envelope'* button.  set the first band limit by dragging the cursor on the
% graph. press "Enter", a 2nd cursor will appear, set it up to the 2nd
% limit of the desired bandwidth.  press "Enter" again to get the filtered signal.
%
%% Run Button
% The 'Run' button is needed to be pressed so that the changes we made will
% effect the calculations and graphs of the program.
%
%% Plots and Axes
% You can view several different aspects of the bearing system at hand.
%
%% Top Left Graph
% This graph shows the input signal - the signal measured at the faulty
% bearing.
%
%% Top Right Graph
% This graph shows the BODE frequency-Magnitude plot of the system.
%
%% Central Graph
% This graph shows the system response.
%
%% Bottom Graph
% This graph shows the output of the selected analysis plot.
%

author: Sable

repo: mcbench-benchmarks


text:
function F = ctranspose( F )
% '   Conjugate transpose of a CHEBFUN2V

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

% Transpose and then conjugate:
F = transpose( F );
F = conj( F );

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function[]=xoffset(i1,i2)
%XOFFSET  Offsets lines in the x-direction after plotting.
%
%   XOFFSET allows data to be manipulated after it has been plotted, by
%   operating on the data stored in the figure itself.  This may be used
%   only with 2-D line plots (not symbol plots, contour plots, etc.).
%
%   XOFFSET offsets all lines in the current axes a specified amount.
%
%   XOFFSET(N) or XOFFSET N, where N is a *real* number, offsets each
%   column of the X-data by an amount N from the previous column.  N must
%   be a number, not a variable whose value is a number.
%
%   XOFFSET(N) or XOFFSET N, where N is an *imaginary* number, offsets
%   each column of the X-data by an amount imag(N)*DX from the previous
%   column, where DX is the X-axis length of the original (unoffset) plot.
%
%   XOFFSET(M,N) or XOFFSET M N, applies the same offsets to each of M
%   groups of lines. For example, for complex-valued data Z use UVPLOT(Z)
%   followed by XOFFSET 2 N.
%
%   XOFFSET with no arguments returns the data to its original (unoffset)
%   orientation [as do XOFFSET(0) and XOFFSET(0i)].
%
%   XOFFSET also allow multiple axes to be manipulated simultaneously.
%
%   XOFFSET LOCK and XOFFSET UNLOCK lock and unlock all Y-data in the
%   current figure. When LOCK is on, calls to XOFFSET are applied to each
%   subplot individually.
%
%   See also YOFFSET, LINESTYLE.
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2000--2015 J.M. Lilly --- type 'help jlab_license' for details

if strcmpi(i1,'--t')
    return
end

if nargin==1;
  N=10000;  %Very large number of lines
end
if nargin==2
  N=i1;
  i1=i2;
  if ischar(N)
    N=str2double(N);
  end
end

bcontinue=1;
if nargin>0
   if ischar(i1)
      if isempty(str2double(i1))
           i1=deblank(i1);
           i1=fliplr(deblank(fliplr(i1)));
           if strcmpi(i1,'lock')
                if isappdata(gca,'lastxoffset')
                    lastoff=getappdata(gca,'lastxoffset');
                    setappdata(gcf,'xoffsetlock',1)
                    xoffsetloop(0,N);
                    xoffsetloop(lastoff,N);
                else
                    setappdata(gcf,'xoffsetlock',1)
                end
                bcontinue=0;
            end
            if strcmpi(i1,'unlock')
                setappdata(gcf,'xoffsetlock',0)
                bcontinue=0;
            end
      end
   end
end

if bcontinue
   if nargin>0
      delta=i1;
   else
      delta=0;
   end

   h=linehandles;
   if plotmodified(h)
   %If the plot has been changed, the old "lastxoffset" may no
   %longer be correct.  If so, we set it to zero
       setappdata(gca,'lastxoffset',0)
   end
   xoffsetloop(delta,N);
end

function[]=xoffsetloop(delta,N)
h=gca;
if isappdata(gcf,'xoffsetlock')
   if getappdata(gcf,'xoffsetlock')
      h=axeshandles(gcf);
   end
end

for i=1:length(h)
    axes(h(i))
    if isappdata(gca,'lastxoffset')
       lastdelta=getappdata(gca,'lastxoffset');
       xoffsetapply(-1*lastdelta,N);
       setappdata(gca,'lastxoffset',0)
    end
    xoffsetapply(delta,N);
end

axes(h(1))

function[]=xoffsetapply(delta,N)
h=linehandles;

if ischar(delta),delta=str2double(delta);end
xx=get(h,{'xdata'});

if length(delta)==1 && ~isreal(delta)
   ax=axis;
   dx=ax(2)-ax(1);
   delta=dx.*imag(delta)/100;
end

if length(delta)==1
   for i=length(xx):-1:1
       xx{i}=xx{i}+delta*(mod(length(xx)-i,round(length(xx)/N)));
   end
elseif length(delta)==length(h)
   for i=length(xx):-1:1
       xx{i}=xx{i}+delta(i);
   end
else
   error('Number of line handles does not equal offset array length.')
end

set(h,{'xdata'},xx);
setappdata(gca,'lastxoffset',delta)
setappdata(gca,'lasthandles',h)

function[b]=plotmodified(h)
b=0;
if isappdata(gca,'lasthandles')
  b=1;
  h2=getappdata(gca,'lasthandles');
  if length(h2)==length(h)
      if all(h2==h)
          b=0;
      end
  end
end

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab


text:
function pixel_scan
%author Imran Akthar imran_akthar@hotmail.com

clc;
clear all;
buffer=pwd;
[file, pathname] = uigetfile('*.jpg','Load Image');

cd(pathname);
a=imread(file);%color image

figure(1)
subplot(2,1,1)
subimage(a)
r=a(:,:,1);
g=a(:,:,2);
b=a(:,:,3);
size_row=size(a,1);
size_col=size(a,2);
for counter_row=1:size_row
    for counter_col=1:size_col
    rr=[r(counter_row,counter_col),g(counter_row,counter_col),b(counter_row,counter_col)];
    subplot(2,1,2);
    u16=double(rr);
    image(colormap(u16./255));
    title(['Row',num2str(counter_row),'Col',num2str(counter_col),'RGB Color',num2str(double(rr))])
    pause(.001)
end
end


text:
function test_pull1456

% MEM 8gb
% WALLTIME 00:20:00
% DEPENDENCY ft_sourceanalysis ft_inverse_eloreta

load(dccnpath('/home/common/matlab/fieldtrip/data/test/pull1456.mat'));

% Compute spectrum
cfg = [];
cfg.output = 'powandcsd';
cfg.channel = 'all';
cfg.method = 'mtmfft';
cfg.taper = 'hanning';%'boxcar';
dataFreq1 = ft_freqanalysis(cfg, dataPre);
cfg.output = 'fourier';
dataFreq2 = ft_freqanalysis(cfg, dataPre);

% source reconstruction
cfg = [];
cfg.method = 'eloreta';
cfg.sourcemodel = sourcemodel;
cfg.headmodel = vol.vol;
source_eloreta1 = ft_sourceanalysis(cfg, dataFreq1); % compute the source model

assert(isequal(size(source_eloreta1.avg.pow),[size(source_eloreta1.pos,1) numel(source_eloreta1.freq)]));

source_eloreta2 = ft_sourceanalysis(cfg, dataFreq2); % compute the source model
i1 = find(source_eloreta2.inside,1,'first');

assert(isequal(size(source_eloreta2.avg.mom{i1}),[3 80 193]));

cfg.mne.snr = 10;
cfg.method = 'mne';
source_mne1 = ft_sourceanalysis(cfg, dataFreq1);
source_mne2 = ft_sourceanalysis(cfg, dataFreq2);

% -> this does not work. AT ALLedit f
%cfg.method = 'harmony';
%source_harmony1 = ft_sourceanalysis(cfg, dataFreq1);
%source_harmony2 = ft_sourceanalysis(cfg, dataFreq2);

% -> this should throw an explicit error
cfg.method = 'music';
try
  source_music1 = ft_sourceanalysis(cfg, dataFreq1);
  ok = true;
catch
  ok = false;
end
assert(~ok);
try
  source_music2 = ft_sourceanalysis(cfg, dataFreq2);
  ok = true;
catch
  ok = false;
end
assert(~ok);

% -> this currently also does note work, but throws a non informative error
%cfg.method = 'rv';
%source_rv1 = ft_sourceanalysis(cfg, dataFreq1);
%source_rv2 = ft_sourceanalysis(cfg, dataFreq2);

% -----------------------------

% Compute an ERP
cfg = [];
cfg.covariance = 'yes';
cfg.covariancewindow = [-1 0]; % calculate the average of the covariance matrices
% for each trial (but using the pre-event baseline data only)
dataAvg = ft_timelockanalysis(cfg, dataPre);

% source reconstruction
cfg = [];
cfg.method = 'eloreta';
cfg.sourcemodel = sourcemodel;
cfg.headmodel = vol.vol;
sourceTime = ft_sourceanalysis(cfg, dataAvg);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [Pro,Res] = transferoperator(HB,NL,isFreeNode)
%% TRANSFEROPERATOR transfer operators between multilevel meshes
%
%  [Pro,Res] = transferoperator(HB,NL) construct matrix representation of
%  transfer operators between levels. All output are cell(level,1).
%
%  In the input, HB is the hierarchical structure of nodes. NL records the
%  starting and ending indices of nodes in each level. see HBstructure or
%  HBstructure3.
%
%  Prolongation (Pro) and restrction (Res) is constructed using standard
%  linear finite element basis and Res = Pro'.
%
%  See also mg, HBstructure, HBstructure3.
%
%  Reference: L. Chen. MultiGrid Methods.

if ~exist('isFreeNode','var'), isFreeNode = []; end
level = length(NL)-1;
Pro = cell(level,1);
Res = cell(level,1);
for j = level:-1:2
    % fine node and coarse node index
    fineNodeRange = NL(j)+1:NL(j+1);
    fineNode = HB(fineNodeRange,1);
    nFineNode = NL(j+1)-NL(j);
    coarseNode = (1:NL(j))';
    isCoarseNode = true(NL(j+1),1);
    isCoarseNode(fineNode) = false;
    coarseNodeFineIdx = find(isCoarseNode);
    ii = [coarseNodeFineIdx; fineNode; fineNode];
    jj = [coarseNode; HB(fineNodeRange,2); HB(fineNodeRange,3)];
    ss = [ones(NL(j),1); 0.5*ones(nFineNode,1); 0.5*ones(nFineNode,1)];
    % remove fix dof from index
    if ~isempty(isFreeNode)
        isFreeNodeC = isFreeNode;
        isFreeNodeC(fineNode) = [];
        Nfree = sum(isFreeNode);
        NfreeC = sum(isFreeNodeC);
        idx = isFreeNode(ii) & isFreeNodeC(jj);
        idxMap(isFreeNode) = (1:Nfree)';
        idxMapC(isFreeNodeC) = (1:NfreeC)';
        ii = idxMap(ii(idx));
        jj = idxMapC(jj(idx));
        ss = ss(idx);
        % generate prolongation matrix
        Pro{j-1} = sparse(ii,jj,ss,Nfree,NfreeC);
        isFreeNode = isFreeNodeC;
    else
        Pro{j-1} = sparse(ii,jj,ss,NL(j+1),NL(j));
    end
    Res{j} = Pro{j-1}';
end

repo: Aero-matlab


text:
%% Plotting Rotations
%
%%
%
% The function <quaternion.scatter.html scatter> allows you to visualize a
% rotation in Rodriguez space.

% define 100 random rotations
rot = rotation.rand(100)

% and plot the Rodriguez space
scatter(rot)

author: mtex-toolbox

repo: mtex

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


text:
function h=demirel(im,thr,T)
%h=demirel(im,thr);
%im is an input image, thr is a threshold between 0-1, T is the thickness
%of the line to indicate the edge.
%h is an uint8 balck and white image with values of 0 and 255.
%This programme has been written by me, G. Anbarjafari (Shahab) months ago
%but finalized today 17-11-2008.
%(c) Demirel and Anbarjafari - 2008

[sx,sy,sz]=size(im);

if sz~=1
    im1=not(im2bw(rgb2gray(im),thr));
else
    im1=not(im2bw(im,thr));
end

SZ=2*T+1;
X=zeros(SZ,SZ);
X((SZ+1)/2,:)=ones(1,SZ);
X(:,(SZ+1)/2)=ones(SZ,1);
X((SZ+1)/2,(SZ+1)/2)=2;
Q = filter2(X,im1);
Q([find(Q<1)])=0;
Q([find(Q>0)])=1;

h=uint8(abs(double(Q)-double(im1))*255);


function [ figformat ] = savefigure_pdf( name,varargin )

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Filippo Ferroni, 6/1/2015
% Revised, 2/15/2017
% Revised, 3/21/2018

% SAVEFIGURE_PDF: this function saves figures in .pdf format
% name: Name of the figure, example: 'figure1'
% type: Format of the figure, example: 'fig','espc'
% If no input is provided, figure saved twice with fig and espc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

set(gcf,'Units','Inches');
pos = get(gcf,'Position');
set(gcf,'PaperPositionMode','Auto','PaperUnits','Inches','PaperSize',[pos(3), pos(4)])
print(gcf,name,'-dpdf','-r0');
figformat=1;
end


text:
function tf = strlexne(a, b)
%STRLEXNE Lexicographic not equal to.
%
%   STRLEXNE(A, B) returns 1 if A is lexicographically not equal to B, and 0
%   otherwise.
%
%   This is a MATLAB version of the Perl `ne' operator.

%   See also NE.

%   Author:      Peter J. Acklam
%   Time-stamp:  2003-10-13 11:15:37 +0200
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   tf = strlexcmp(a, b) ~= 0;

author: CovertLab

repo: WholeCell

save_path: github-repos/MATLAB/CovertLab-WholeCell


text:
function [ClusterID,EventType,AlgoInfo] =  clusterSLIDERmag(ShortCat,MainMag,BackTime,ForeTime,MinRad,MagRadScale,MagRadConst)

	% Example [mCatclus] =  clusterSTEPmag(mCatalog, 1.95, 1.95, 1984, 1, 1);

	% code to cluster catalog with spatial windows according to STEP forecasting model
	% with sliding windows of t1 backwards in time and t2 forward in time
	% starting with the largest earthquake in the catalog

	%
	% Input parameters:
	%   mCatalog        Earthquake catalog
	%   Mainmag         minimum mainmag magnitude
	%   Mc              Completeness magnitude
	%   startyear
	%   t1              time before an earthquake in days
	%   t2              time window following an earthquake in days
	%
	% Output parameters:
	%   fBValue         mCatclus: The clustered catalog for further anaysis
	%
	% Annemarie Christophersen, 31. January 2008

	% Code written for catalogue under zmap, thus the input
	% catalogue is in the variable a, where
	% column 1: longitude
	% column 2: latitude
	% column 3: year (decimal year, including seconds)
	% column 4: month
	% column 5: day
	% column 6: magnitude
	% column 7: depth
	% column 8: hour
	% column 9: minute
	% column 10: seconds
	% column 11-23 not important for clustering and cluster analysis
	% column 24: SCSN flag for event type (l=local, r=regional, q=quarry)

	% variables used
	% mc completeness magnitude
	% twindow duration in time in which to look for related events

	%Converted for MapSeis by DE 21.6.2012

	%may make this switchable if needed
	Rounding=true;

	%init work arrays
	numEvents = length(ShortCat);
	WorkArray=zeros(numEvents,4);
	WorkArray(:,1)= (1:numEvents)'; %introduce column 11 with row number

	%init output
	ClusterID=nan(numEvents,1);
	%EventType=ones(numEvents,1);
	EventType = categorical(ones(numEvents,1),...
		[0 1 2 3],...
        {'unclassified','single event','mainshock','aftershock'});
	InitEvent=false(numEvents,1);
	AlgoInfo=[];

	%InitEvent is currently not directly supported by mapseis, but will be
	%added to AlgoInfo, so it can be used by specialiced algorithms

	clusterno = 1;

	%Dtafter = t2/365; %30 days in decimal years
	%Dtbefore = t1/365; %2 days in decimal years
	clusterno = 1;

	while any(WorkArray(:,2)==0)
		notClustered=WorkArray(:,2)==0;

		[maxmag IDX]=max(ShortCat(notClustered,5)); %the magnitude of the largest earthquake not yet clustered
		maxmag=maxmag(1); %could have mor than one maximum afterall
		NrInGame=WorkArray(notClustered,1);
		ActualIndex=NrInGame(IDX(1));

	   	lino = ActualIndex;
	   	WorkArray(lino,2)=clusterno; %write cluster number into column 12
	   	searchradius=max(MinRad, 10^(MagRadScale*maxmag-MagRadConst)); %calculate search radius

		%get data of the new event
		tref = ShortCat(lino,4); %set reference time
		latref = ShortCat(lino,2); %set reference latitude
		lonref = ShortCat(lino,1); %set reference longitude

		%search for earthquakes before, extend by sliding time windows of t1
		eventsDtbefore=(ShortCat(:,4) > tref-BackTime & ShortCat(:,4) < tref);
		eventsbefore = sum(eventsDtbefore);
		linobefore = lino-eventsbefore;

		%%That did not work like it was intended
		%%--------------------------------------

		% for i=linobefore:lino
			% if (b(i,12) == 0) % don't bother if event already clustered
			    % edist = deg2km(distance(latref,lonref,ShortCat(i,2),ShortCat(i,1))); %calculate distance to mainshock
			    % if (edist <= searchradius)
				% WorkArray(i,2)=clusterno;
				% %make this event new tref and search for events before
				% tref=ShortCat(i,4);
				% eventsDtbefore=(ShortCat(:,4) > tref-BackTime & ShortCat(:,4) < tref);
				% eventsbefore = length(b(eventsDtbefore,1));
				% linobefore = max(1, i-eventsbefore);
				% i=linobefore; %is this the right way to restart loop at linobefore?
			    % end
			% end
		% end %this could now have an earlier linebefore and will loop up to lino
		% % where lino remains the number of mainshoc
		% % now look for later earthquakes

		%old version whould not work, for "borders" once set, will stay as the are;
		i=linobefore;
		while i<=lino
			if WorkArray(i,2)==0
				edist = deg2km(distance(latref,lonref,ShortCat(i,2),ShortCat(i,1))); %calculate distance to mainshock
				if (edist <= searchradius)
					WorkArray(i,2)=clusterno;
					%make this event new tref and search for events before
					tref=ShortCat(i,4);
					eventsDtbefore=(ShortCat(:,4) > tref-BackTime & ShortCat(:,4) < tref);
					eventsbefore = sum(eventsDtbefore);
					linobefore = max(1, i-eventsbefore);
					i=linobefore; %Now it does restart

				else
					i=i+1;
				end
			else
				i=i+1;
			end

		end

		tref=ShortCat(lino,4); %reset reference time to mainshock

		while (lino < numEvents+1) && ShortCat(lino,4) < (tref+ForeTime)
			if WorkArray(lino,2) == 0
				edist = deg2km(distance(latref,lonref,ShortCat(lino,2),ShortCat(lino,1)));
				if (edist <= searchradius)
					WorkArray(lino,2)=clusterno;

					%Not needed already cutted
					%if (ShortCat(lino,6) > Mc)
					tref=ShortCat(lino,4); %set reference time to new earthquake in cluster

				end
				lino=lino+1;
			end
		end

		clusterno=clusterno+1;

	end

	%Output clustered matrix
	% column 1: longitude
	% column 2: latitude
	% column 3: year (decimal year, including seconds)
	% column 4: month
	% column 5: day
	% column 6: magnitude
	% column 7: depth
	% column 8: hour
	% column 9: minute
	% column 10: seconds
	% column 11: line number
	% column 12: cluster number
	% column 13: mainshock with its cluster number
	% column 14: initiating event cluster number

	if Rounding
		ShortCat(:,5)=round(ShortCat(:,5)*10)/10;%  round magnitudes to 0.1
	end

	%may not be needed anymore -> it is needed
	WorkArray(:,1)= 1:length(ShortCat)'; %introduce column 1 with row number

	%WorkArray(WorkArray(:,2)==0,2)=nan;
	UsedCluster=unique(WorkArray(~isnan(WorkArray(:,2))&WorkArray(:,2)~=0,2));
	clusterno=1;

	disp(numel(UsedCluster));

	for i=UsedCluster'
		inCluster = WorkArray(:,2)==i;

		if sum(inCluster) >1
			%A real cluster

			%First mark all as Events of the cluster and as Aftershocks
			ClusterID(inCluster)=clusterno;
			EventType(inCluster)='aftershock';

			%find the first of the largest events label it as mainshock
			[MaxMag IDX] = max(ShortCat(inCluster,5));
			availIndex=WorkArray(inCluster,1);
			MrMaxMag=availIndex(IDX(1));
			EventType(MrMaxMag)='mainshock';

			%Mark initial event
			[MinTime IDX] = min(ShortCat(inCluster,4));
			availIndex=WorkArray(inCluster,1);
			MrInit=availIndex(IDX(1));
			InitEvent(MrInit)=true;

			clusterno=clusterno+1;

		elseif sum(inCluster)==1
			%only one event
			ClusterID(inCluster)=nan;
			EventType(inCluster)='single event';

			%clusterno=clusterno+1;

		end

	end

	%And set all not assign clusters to NaN and 1
	notInClust=WorkArray(:,2)==0;
	ClusterID(notInClust)=nan;
	EventType(notInClust)='single event'

	%And finally the AlgoInfo
	ParamInput=struct(	'MainMag',MainMag,...
				'BackTime',BackTime,...
				'ForeTime',ForeTime,...
				'MinRad',MinRad,...
				'MagRadScale',MagRadScale,...
				'MagRadConst',MagRadConst);

	AlgoInfo.Type='SLIDER-Magnitude-mapseis-v1';
	AlgoInfo.UsedConfig=ParamInput;
	AlgoInfo.CalculationDate=date;
	AlgoInfo.InitialEvents=InitEvent;
	AlgoInfo.WorkArray=WorkArray;

end

author: CelsoReyes


text:
classdef SyntheticSequenceGenerator < handle
    %SYNTHETICSEQUENCEGENERATOR  Synthetic frame sequence generator for testing background subtraction algorithms
    %
    % It will generate the moving object on top of the background.
    % It will apply some distortion to the background to make the test more
    % complex.
    %
    % See also: cv.BackgroundSubtractorLSBP, cv.BackgroundSubtractorGSOC
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    %% SyntheticSequenceGenerator
    methods
        function this = SyntheticSequenceGenerator(background, object, varargin)
            %SYNTHETICSEQUENCEGENERATOR  Creates an instance of SyntheticSequenceGenerator
            %
            %     obj = cv.SyntheticSequenceGenerator(background, object)
            %     obj = cv.SyntheticSequenceGenerator(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __background__ Background image for object.
            % * __object__ Object image which will move slowly over the
            %   background.
            %
            % ## Options
            % * __Amplitude__ Amplitude of wave distortion applied to
            %   background. default 2.0
            % * __Wavelength__ Length of waves in distortion applied to
            %   background. default 20.0
            % * __Wavespeed__ How fast waves will move. default 0.2
            % * __Objspeed__ How fast object will fly over background.
            %   default 6.0
            %
            % See also: cv.SyntheticSequenceGenerator.getNextFrame
            %
            this.id = SyntheticSequenceGenerator_(0, 'new', background, object, varargin{:});
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     obj.delete()
            %
            % See also: cv.SyntheticSequenceGenerator
            %
            if isempty(this.id), return; end
            SyntheticSequenceGenerator_(this.id, 'delete');
        end

        function [frame, gtMask] = getNextFrame(this)
            %GETNEXTFRAME  Obtain the next frame in the sequence
            %
            %     [frame, gtMask] = obj.getNextFrame()
            %
            % ## Output
            % * __frame__ Output frame.
            % * __gtMask__ Output ground-truth (reference) segmentation mask
            %   object/background.
            %
            [frame, gtMask] = SyntheticSequenceGenerator_(this.id, 'getNextFrame');
        end
    end

    %% Algorithm
    methods (Hidden)
        function clear(this)
            %CLEAR  Clears the algorithm state
            %
            %     obj.clear()
            %
            % See also: cv.SyntheticSequenceGenerator.empty,
            %  cv.SyntheticSequenceGenerator.load
            %
            SyntheticSequenceGenerator_(this.id, 'clear');
        end

        function b = empty(this)
            %EMPTY  Returns true if the algorithm is empty
            %
            %     b = obj.empty()
            %
            % ## Output
            % * __b__ Returns true if the object is empty (e.g in the
            %   very beginning or after unsuccessful read).
            %
            % See also: cv.SyntheticSequenceGenerator.clear,
            %  cv.SyntheticSequenceGenerator.load
            %
            b = SyntheticSequenceGenerator_(this.id, 'empty');
        end

        function name = getDefaultName(this)
            %GETDEFAULTNAME  Returns the algorithm string identifier
            %
            %     name = obj.getDefaultName()
            %
            % ## Output
            % * __name__ This string is used as top level XML/YML node tag
            %   when the object is saved to a file or string.
            %
            % See also: cv.SyntheticSequenceGenerator.save,
            %  cv.SyntheticSequenceGenerator.load
            %
            name = SyntheticSequenceGenerator_(this.id, 'getDefaultName');
        end

        function save(this, filename)
            %SAVE  Saves the algorithm parameters to a file
            %
            %     obj.save(filename)
            %
            % ## Input
            % * __filename__ Name of the file to save to.
            %
            % This method stores the algorithm parameters in the specified
            % XML or YAML file.
            %
            % See also: cv.SyntheticSequenceGenerator.load
            %
            SyntheticSequenceGenerator_(this.id, 'save', filename);
        end

        function load(this, fname_or_str, varargin)
            %LOAD  Loads algorithm from a file or a string
            %
            %     obj.load(fname)
            %     obj.load(str, 'FromString',true)
            %     obj.load(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __fname__ Name of the file to read.
            % * __str__ String containing the serialized model you want to
            %   load.
            %
            % ## Options
            % * __ObjName__ The optional name of the node to read (if empty,
            %   the first top-level node will be used). default empty
            % * __FromString__ Logical flag to indicate whether the input is a
            %   filename or a string containing the serialized model.
            %   default false
            %
            % This method reads algorithm parameters from the specified XML or
            % YAML file (either from disk or serialized string). The previous
            % algorithm state is discarded.
            %
            % See also: cv.SyntheticSequenceGenerator.save
            %
            SyntheticSequenceGenerator_(this.id, 'load', fname_or_str, varargin{:});
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function value = triangulation_area ( node_num, node_xy, element_order, ...
  element_num, element_node )

%*****************************************************************************80
%
%% TRIANGULATION_AREA computes the area of a triangulation.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    26 December 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, real NODE_XY(NODE_NUM,2), the coordinates of the nodes.
%
%    Input, integer ELEMENT_ORDER, the order of the triangles.
%
%    Input, integer ELEMENT_NUM, the number of triangles.
%
%    Input, integer ELEMENT_NODE(ELEMENT_NUM,ELEMENT_ORDER),
%    the nodes making up each triangle.
%
%    Output, real VALUE, the area.
%
  value = 0.0;

  for element = 1 : element_num

    element_xy(1:3,1:2) = node_xy(element_node(element,1:3),1:2);

    element_area = 0.5 * abs ( ...
        element_xy(1,1) * ( element_xy(2,2) - element_xy(3,2) ) ...
      + element_xy(2,1) * ( element_xy(3,2) - element_xy(1,2) ) ...
      + element_xy(3,1) * ( element_xy(1,2) - element_xy(2,2) ) );

    value = value + element_area;

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function res = fiducials(this, newfiducials)
% Method for getting/setting the fiducials field
% FORMAT res = fiducials(this, fiducials)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: fiducials.m 3589 2009-11-20 17:17:41Z guillaume $

switch nargin
    case 1
         res = this.fiducials;
    case 2
         this.fiducials = newfiducials;
         res = this;
end


text:
function [TET,Vtet,C]=hex2tet(varargin)

% function [TET,Vtet,C]=hex2tet(HEX,V,C,tetOpt)

%%

switch nargin
    case 2
        HEX=varargin{1};
        V=varargin{2};
        C=[];
        tetOpt=1;
    case 3
        HEX=varargin{1};
        V=varargin{2};
        C=varargin{3};
        tetOpt=1;
    case 4
        HEX=varargin{1};
        V=varargin{2};
        C=varargin{3};
        tetOpt=varargin{4};
    otherwise
        error('Wrong number of input arguments');
end

%%

C=C(:);
switch tetOpt
    case 1 %Add central node and cross side faces

        [F,~]=element2patch(HEX,C,'hex8');

        numV=size(V,1);
        numE=size(HEX,1);

        %The original vertices
        X=V(:,1); Y=V(:,2); Z=V(:,3);

        %The mid-element points
        if numE==1
            Vm=[mean(X(HEX),1) mean(Y(HEX),1) mean(Z(HEX),1)];
        else
            Vm=[mean(X(HEX),2) mean(Y(HEX),2) mean(Z(HEX),2)];
        end

        %The mid-face points
        Vf=[mean(X(F),2) mean(Y(F),2) mean(Z(F),2)];

        %TET point collection
        Vtet=[V; Vm; Vf];

        %Defining tetrahedral node list per hex element
        numV2=numV+numE+1;
        indAdd=reshape(numV2:(numV2+6*numE)-1,numE,6);
        TET_set=[HEX (numV+1:numV+numE)' indAdd];

        TET_format=[14 13 9 10;...
                    12 14 9 10;...
                    15 12 9 10;...
                    13 15 9 10;...
                    %
                    13 14 9 11;...
                    14 12 9 11;...
                    12 15 9 11;...
                    15 13 9 11;...
                    %
                    1 10 12 15;...
                    2 10 14 12;...
                    3 10 13 14;...
                    4 10 15 13;...
                    %
                    5 11 15 12;...
                    6 11 12 14;...
                    7 11 14 13;...
                    8 11 13 15;...
                    %
                    1 2 12 10;...
                    2 3 14 10;...
                    3 4 13 10;...
                    4 1 15 10;...
                    %
                    5 6 11 12;...
                    6 7 11 14;...
                    7 8 11 13;...
                    8 5 11 15;...
                    %
                    1 5 15 12;...
                    2 6 12 14;...
                    3 7 14 13;...
                    4 8 13 15;...
                    ];

        %Reform TET_set as an nx4
        TET_set_reform1=TET_set(:,TET_format(:))';
        TET_set_reform2=reshape(TET_set_reform1,size(TET_format,1),numel(TET_set_reform1)/size(TET_format,1))';
        TET=reshape(TET_set_reform2,4,numel(TET_set_reform2)/4)';

        %Fix color information
        C=repmat(C,size(TET_format,1),1);

        %Removing double vertices
        [TET,Vtet]=mergeVertices(TET,Vtet);

    case 2 %Delaunay based 6 tetrahedron decomposition of cube applied to all
        HEX=HEX(:,[1 2 4 3 5 6 8 7]);
        tetInd =[5     1     2     3;...
            6     5     2     3;...
            6     7     5     3;...
            6     4     7     3;...
            6     2     4     3;...
            6     8     7     4];
        a=tetInd';
        a=a(:)';
        A=HEX(:,a);
        TET=reshape(A',4,6.*size(HEX,1))';
        if ~isempty(C)
            C=(ones(6,1)*C');
            C=C(:);
        end
        Vtet=V;
    case 3 %Same as 2 but flipped top to bottom

        %Switch top and bottom
        HEX=HEX(:,[8 7 5 6 4 3 1 2]);

        tetInd =[5     1     2     3;...
            6     5     2     3;...
            6     7     5     3;...
            6     4     7     3;...
            6     2     4     3;...
            6     8     7     4];
        a=tetInd';
        a=a(:)';
        A=HEX(:,a);
        TET=reshape(A',4,6.*size(HEX,1))';
        if ~isempty(C)
            C=(ones(6,1)*C');
            C=C(:);
        end
        Vtet=V;
    case 4 % 5 tetrahedron decomposition of cube
        tetInd=[1 8 6 5; 7 8 6 3; 2 1 3 6; 4 8 3 1; 6 3 8 1];
        a=tetInd';
        a=a(:)';
        A=HEX(:,a);
        TET=reshape(A',4,5.*size(HEX,1))';
        if ~isempty(C)
            C=(ones(5,1)*C');
            C=C(:);
        end
        Vtet=V;
    case 5 %Same as 4 but flipped top to bottom
        %Switch top and bottom
        HEX=(HEX(:,[4 3 7 8 1 2 6 5 ]));

        tetInd=[1 8 6 5; 7 8 6 3; 2 1 3 6; 4 8 3 1; 6 3 8 1];
        a=tetInd';
        a=a(:)';
        A=HEX(:,a);
        TET=reshape(A',4,5.*size(HEX,1))';
        if ~isempty(C)
            C=(ones(5,1)*C');
            C=C(:);
        end
        Vtet=V;
    case 6 % tets for octet-truss lattice
         [F,~]=element2patch(HEX,C,'hex8');

        numV=size(V,1);
        numE=size(HEX,1);

        %The original vertices
        X=V(:,1); Y=V(:,2); Z=V(:,3);

        %The mid-element points
        if numE==1
            Vm=[mean(X(HEX),1) mean(Y(HEX),1) mean(Z(HEX),1)];
        else
            Vm=[mean(X(HEX),2) mean(Y(HEX),2) mean(Z(HEX),2)];
        end

        %The mid-face points
        Vf=[mean(X(F),2) mean(Y(F),2) mean(Z(F),2)];

        %TET point collection
        Vtet=[V; Vm; Vf];

        %Defining tetrahedral node list per hex element
        numV2=numV+numE+1;
        indAdd=reshape(numV2:(numV2+6*numE)-1,numE,6);
        TET_set=[HEX (numV+1:numV+numE)' indAdd];

        TET_format=[...
%                     %
%                     14 13 9 10;...
%                     12 14 9 10;...
%                     15 12 9 10;...
%                     13 15 9 10;...
%                     %
%                     13 14 9 11;...
%                     14 12 9 11;...
%                     12 15 9 11;...
%                     15 13 9 11;...
                    %
                    1 10 12 15;...
                    2 10 14 12;...
                    3 10 13 14;...
                    4 10 15 13;...
                    %
                    5 11 15 12;...
                    6 11 12 14;...
                    7 11 14 13;...
                    8 11 13 15;...

                    %
                    1 5 15 12;...
                    2 6 12 14;...
                    3 7 14 13;...
                    4 8 13 15;...
                    ];

        %Reform TET_set as an nx4
        TET_set_reform1=TET_set(:,TET_format(:))';
        TET_set_reform2=reshape(TET_set_reform1,size(TET_format,1),numel(TET_set_reform1)/size(TET_format,1))';
        TET=reshape(TET_set_reform2,4,numel(TET_set_reform2)/4)';

        %Fix color information
        C=repmat(C,size(TET_format,1),1);

        %Removing double vertices
        [TET,Vtet]=mergeVertices(TET,Vtet);
end

TET=TET(:,[1 2 4 3]); %Invert

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2019  Kevin Mattheus Moerman
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: brainstorm-tools


text:
function ans = calc_Dx(doseBinsV, volsHistV, x, volType)
% Returns the lowest dose in x% of structure'
% given the DVH data and the parameter percent.
%
%  MODIFICATION ALERT:  THIS FUNCTION IS UTILIZED BY THE DREXLER CODEBASE
%
%  Last modified: AJH 11/05
%
%  Usage: calc_Dx(doseBinsV, volsHistV, percent)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

if isstruct(x)  %for use with ROE
    volType = x.volType.val;
    x = x.x.val;
end

if ~exist('volType','var')
    %warning('Input volume assumed to be in percentage. Set volType=0 for absolute values.');
else
    if ~volType
    x = x/sum(volsHistV)*100;
    end
end

cumVolsV = cumsum(volsHistV);
	cumVols2V = cumVolsV(end) - cumVolsV;
	ind = min(find([ cumVols2V/cumVolsV(end) < x/100 ])); %CHANGED
	if isempty(ind)
        ans = 0;
	else
    	ans = doseBinsV(ind);
	end
return;

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function varargout = cgal_fixed_alpha_shape3(varargin)
% CGAL_FIXED_ALPHA_SHAPE3  Individual alpha-shapes of a 3D set of points
%
% TRI = cgal_fixed_alpha_shape3(X, ALPHA)
%
%   X is a 3-column matrix. X(i, :) contains the xyz-coordinates of a 3D
%   point.
%
%   ALPHA is a vector of scalar alpha values, alpha=R^2, where R is the
%   probe radius.
%
%   TRI is a cell array of the same length as ALPHA. Cell TRI{i} contains
%   the alpha shape triangulation for ALPHA{i}. Each row contains the 3
%   nodes that form one triangular facet in the mesh. The i-th mesh can be
%   visualised running:
%
%     >> trisurf(tri{i}, x)
%
%
% This function uses CGAL's implementation of fixed alpha shapes [1]. Fixed
% alpha shapes are more efficient when only the shape for one or a few
% alpha values is required. When many alpha values are required, it may be
% faster to use cgal_alpha_shape3().
%
% However, note that Matlab function alphavol() implemented by Jonas
% Lundgren and provided as a third-party function in Gerardus seems to be
% faster than either of the CGAL MEX functions, at least for a single alpha
% value.
%
% [1] http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Alpha_shapes_3/Chapter_main.html
%
% See also: alphavol, cgal_alpha_shape3, scimat_lconvhull_smoothing

% Author: Ramon Casero <rcasero@gmail.com>
% Copyright © 2013 University of Oxford
% Version: 0.1.0
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see
% <http://www.gnu.org/licenses/>.

error('MEX file not found')

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
% Test suite for run_CNMF_patches
% Use 'run(TestRunCNMFPatches)' to run the whole suite.
classdef TestRunCNMFPatches < matlab.unittest.TestCase

    properties
        dataset   % generate dataset to test with
        datasize  % dataset size
        patches   % patches coordinates
    end

    properties (ClassSetupParameter)
        sizY = struct('data2d', [128, 128, 500], ...
                      'data2d_small', [25, 25, 500], ...
                      'data3d', [128, 128, 7, 100]);
        memory_mapped = struct('memmapped', true, 'inRAM', false);
    end

    properties (MethodSetupParameter)
        patch_size = struct('default', {[]}, 'small', 25);
    end

    properties (TestParameter)
        cluster_pixels = struct('cluster_on', true, 'cluster_off', false);
    end

    methods (TestClassSetup)
        function createDataset(testCase, sizY, memory_mapped)
            rng(1)  % fix random generator seed for reproducibility
            Y = randn(sizY);
            if memory_mapped
                Yr = reshape(Y, [], sizY(end));
                F_dark = min(Yr(:));
                filename = [tempname, '.mat'];
                save(filename, 'Yr', 'Y', 'F_dark', 'sizY', '-v7.3');
                Y = matfile(filename, 'Writable', false);
            end
            testCase.datasize = sizY;
            testCase.dataset = Y;
        end
    end

    methods (TestClassTeardown)
        function cleanDataset(testCase)
            % clear create file, if any
            if isa(testCase.dataset, 'matlab.io.MatFile')
                delete(testCase.dataset.Properties.Source);
            end
        end
    end

    methods (TestMethodSetup)
        function createPatches(testCase, patch_size)
            if isempty(patch_size)
                testCase.patches = [];
            else
                data_ndims = length(testCase.datasize(1:end-1));
                psize = [patch_size, patch_size, 5];
                psize = psize(1:data_ndims);
                testCase.patches = construct_patches( ...
                    testCase.datasize(1:end-1), psize);
            end
        end
    end

    methods (Test)
        function testRunning(testCase, cluster_pixels)
            % simply test that nothing crashes
            options = struct('cluster_pixels', cluster_pixels);
            run_CNMF_patches( ...
                testCase.dataset, 7, testCase.patches, [], [], options);
        end
    end
end

author: flatironinstitute

repo: CaImAn-MATLAB


text:
% fir_filterdcpadded() - Pad data with DC constant and filter
%
% Usage:
%   >> data = fir_filterdcpadded(b, a, data, causal);
%
% Inputs:
%   b             - vector of filter coefficients
%   a             - 1
%   data          - raw data (times x chans)
%   causal        - boolean perform causal filtering {default 0}
%   usefftfilt    - boolean use fftfilt instead of filter
%
% Outputs:
%   data      - smoothed data
%
% Note:
%   firfiltdcpadded always operates (pads, filters) along first dimension.
%   Not memory optimized.
%
% Author: Andreas Widmann, University of Leipzig, 2014

%123456789012345678901234567890123456789012345678901234567890123456789012

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

function [ data ] = fir_filterdcpadded(b, a, data, causal, usefftfilt)

% Defaults
if nargin < 4 || isempty(usefftfilt)
    usefftfilt = 0;
end
if nargin < 3 || isempty(causal)
    causal = 0;
end

% Check arguments
if nargin < 2
    ft_error('Not enough input arguments.');
end

% Is FIR?
if ~isscalar(a) || a ~= 1
    ft_error('Not a FIR filter. onepass-zerophase and onepass-minphase filtering is available for FIR filters only.')
end

% Group delay
if mod(length(b), 2) ~= 1
    ft_error('Filter order is not even.');
end
groupDelay = (length(b) - 1) / 2;

% Filter symmetry
isSym = all(b(1:groupDelay) == b(end:-1:groupDelay + 2));
isAntisym = all([b(1:groupDelay) == -b(end:-1:groupDelay + 2) b(groupDelay + 1) == 0]);
if causal == 0 && ~(isSym || isAntisym)
    ft_error('Filter is not anti-/symmetric. For onepass-zerophase filtering the filter must be anti-/symmetric.')
end

% Padding
if causal
    startPad = repmat(data(1, :), [2 * groupDelay 1]);
    endPad = [];
else
    startPad = repmat(data(1, :), [groupDelay 1]);
    endPad = repmat(data(end, :), [groupDelay 1]);
end

% Filter data (with double precision)
isSingle = isa(data, 'single');

if usefftfilt
    data = fftfilt(double(b), double([startPad; data; endPad]));
else
    data = filter(double(b), 1, double([startPad; data; endPad])); % Pad and filter with double precision
end

% Convert to single
if isSingle
    data = single(data);
end

% Remove padded data
data = data(2 * groupDelay + 1:end, :);

end

author: spm


text:
function PlotFieldonMesh(coordinates,nodes,component)
%--------------------------------------------------------------------------
% Code written by : Siva Srinivas Kolukula                                |
%                   Senior Research Fellow                                |
%                   Structural Mechanics Laboratory                       |
%                   Indira Gandhi Center for Atomic Research              |
%                   India                                                 |
% E-mail : allwayzitzme@gmail.com                                         |
%          http://sites.google.com/site/kolukulasivasrinivas/             |
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% Purpose:
%         To plot the profile of a component on mesh
% Synopsis :
%           ProfileonMesh(coordinates,nodes,component)
% Variable Description:
%           coordinates - The nodal coordinates of the mesh
%           -----> coordinates = [X Y ]
%           nodes - The nodal connectivity of the elements
%           -----> nodes = [node1 node2......]
%           component - The components whose profile to be plotted
%           -----> components = a column vector in the order of node
%                               numbers
%--------------------------------------------------------------------------

nel = length(nodes) ;                  % number of elements
nnode = length(coordinates) ;          % total number of nodes in system
nnel = size(nodes,2);                % number of nodes per element
%
% Initialization of the required matrices
X = zeros(nnel,nel) ;
Y = zeros(nnel,nel) ;
Z = zeros(nnel,nel) ;
profile = zeros(nnel,nel) ;
%
for iel=1:nel
     for i=1:nnel
     nd(i)=nodes(iel,i);         % extract connected node for (iel)-th element
     X(i,iel)=coordinates(nd(i),1);    % extract x value of the node
     Y(i,iel)=coordinates(nd(i),2);    % extract y value of the node
     end
     profile(:,iel) = component(nd') ;         % extract component value of the node
end

% Plotting the FEM mesh and profile of the given component
     fh = figure ;
     set(fh,'name','Postprocessing','numbertitle','off') ;
     fill(X,Y,profile)
     axis off ;
     % Colorbar Setting
     SetColorbar
 end


text:
function new()
%NEW Wrapper for GenerateFunctionMFile.
%
% NEW() Wrapper for GenerateFunctionMFile.
%
% See also: GenerateFunctionMFile

% $Author: rcotton $  $Date: 2010/04/09 15:41:27 $ $Revision: 0.1 $
% Copyright: Health and Safety Laboratory 2010

GenerateFunctionMFile(true);

end


text:
function res = spm_eeg_artefact_saccade(S)
% Detects eyeblinks in SPM continuous data file
% S              - input structure
% fields of S:
%    S.D         - M/EEG object
%    S.chanind   - vector of indices of channels that this plugin will look at
%    S.threshold - threshold parameter (in stdev)
%
%    Additional parameters can be defined specific for each plugin.
%
% Output:
% res -
%    If no input is provided the plugin returns a cfg branch for itself.
%
%    If input is provided the plugin returns a matrix of size D.nchannels x D.ntrials
%    with zeros for clean channel/trials and ones for artefacts.
%
% A simplified version of a method described by:
% Engbert, R., & Mergenthaler, K. (2006) Microsaccades are triggered by low
% retinal image slip. Proceedings of the National Academy of Sciences of
% the United States of America, 103: 7192-7197.
%__________________________________________________________________________
% Copyright (C) 2008-2017 Wellcome Trust Centre for Neuroimaging

% Markus Bauer, Laurence Hunt
% $Id: spm_eeg_artefact_saccade.m 7132 2017-07-10 16:22:58Z guillaume $

%-This part if for creating a config branch that plugs into spm_cfg_eeg_artefact
% Any parameters can be specified and they are then passed to the plugin
% when it's called.
%--------------------------------------------------------------------------
if nargin == 0
    threshold         = cfg_entry;
    threshold.tag     = 'threshold';
    threshold.name    = 'Threshold';
    threshold.strtype = 'r';
    threshold.val     = {3};
    threshold.num     = [1 1];
    threshold.help    = {'Threshold to reject things that look like saccades but probably aren''t.'};

    excwin         = cfg_entry;
    excwin.tag     = 'excwin';
    excwin.name    = 'Excision window';
    excwin.strtype = 'r';
    excwin.num     = [1 1];
    excwin.val     = {0};
    excwin.help    = {'Window (in ms) to mark as bad around each saccade, 0 to not mark data as bad.'};

    saccade      = cfg_branch;
    saccade.tag  = 'saccade';
    saccade.name = 'Saccades';
    saccade.val  = {threshold, excwin};
    saccade.help = {''};

    res = saccade;

    return
end

SVNrev = '$Rev: 7132 $';

%-Startup
%--------------------------------------------------------------------------
spm('sFnBanner', mfilename, SVNrev);
spm('FigName','M/EEG saccade detection');

if isequal(S.mode, 'reject')
     error('Only mark mode is supported by this plug-in, use event-based rejection to reject.');
end

D = spm_eeg_load(S.D);

chanind = S.chanind;
threshold = S.threshold;

if length(chanind)~=1
    error('More than one channel - not currently supported.')
end

eog_data = reshape(squeeze(D(chanind,:,:)), 1, []);

%-Saccade detection:
% 1) filter the data, saccade duration ~40 ms, filtering at 30 Hz is fine
% even if it may weaken signal a tiny bit, it takes out quite some noise
% 2) calculate the velocity values
%--------------------------------------------------------------------------
eog_data = ft_preproc_lowpassfilter(eog_data, D.fsample, 30);
eog_filt = [eog_data(:,1),diff(eog_data,1,2)];
% eog_filt = ft_preproc_lowpassfilter(eog_filt, D.fsample, 20);

%-Find saccades by thresholding
%--------------------------------------------------------------------------
% robust estimate of standard deviation, suggested by Mark Woolrich
sd_eeg = (spm_percentile(eog_filt,85)-spm_percentile(eog_filt,15))/2;
em_thresh = S.threshold*sd_eeg;

%-Find 'spikes' (putative saccades)
%--------------------------------------------------------------------------
eblength = round(D.fsample/5); %length of saccade(200 ms) in samples;
spikes = [];
for i = eblength:length(eog_filt)-eblength;
    if abs(eog_filt(i))>em_thresh && ... %bigger than threshold
       all(abs(eog_filt(i))>=abs(eog_filt(i-eblength+1:i+eblength))); %biggest in surrounding 400ms
        spikes = [spikes i];
    end
end

if isempty(spikes)
    error('No saccades detected by algorithm. Try a lower threshold.')
end

spikemat = zeros(eblength*2,length(spikes));
for i = 1:length(spikes)
    spikemat(:,i) = eog_filt(spikes(i)-eblength+1:spikes(i)+eblength);
end

% reject spikes whose peak is not within 1 s.d. of the mean
% (gets rid of most artefacts etc. not removed by filtering):
%--------------------------------------------------------------------------
mn_spike = mean(spikemat(eblength,:));
sd_spike = std(spikemat(eblength,:));
spikes(spikemat(eblength,:)>mn_spike+sd_spike | ...
       spikemat(eblength,:)<mn_spike-sd_spike) = [];
spikemat(:,find(spikemat(eblength,:)>mn_spike+sd_spike | ...
       spikemat(eblength,:)<mn_spike-sd_spike)) = [];

disp(['Number of putative saccades detected: ' num2str(length(spikes))]);

num_eb_per_min=(60*D.fsample*length(spikes))/length(eog_data);
disp([num2str(num_eb_per_min) ' saccades per minute '])
if (num_eb_per_min<0.5)
    error(['Only ' num2str(num_eb_per_min) ' saccades per minute detected by algorithm. Try a lower threshold.'])
end
if (num_eb_per_min>60)
    error(['As many as ' num2str(num_eb_per_min) ' saccades per minute detected by algorithm. Try a higher threshold.'])
end

% plot
%--------------------------------------------------------------------------
if ~spm('CmdLine')
    Fgraph = spm_figure('GetWin','Graphics');
    colormap(gray)
    figure(Fgraph)
    clf
    subplot(2, 1 , 1)
    plot(spikes,ones(length(spikes),1)*5*sd_eeg,'r.');
    hold on;
    plot(eog_filt);

    subplot(2, 1 , 2)
    hold on;
    plot(spikemat);plot(mean(spikemat,2),'Color','k','LineWidth',4);
end

% Update the event structure
%--------------------------------------------------------------------------
if ~isempty(spikes)
    for n = 1:D.ntrials
        cspikes   = spikes(spikes>(D.nsamples*(n-1)) & spikes<(D.nsamples*n));
        ctime  = D.trialonset(n)+(cspikes - D.nsamples*(n-1)-1)/D.fsample;
        ctime  = num2cell(ctime);

        ev = events(D, n);

        if iscell(ev)
            ev = ev{1};
        end

        if ~isempty(ev) && ~S.append
            ind1 = strmatch('artefact_saccade', {ev.type}, 'exact');
            if ~isempty(ind1)
                ind2 = strmatch(D.chanlabels(chanind), {ev(ind1).value}, 'exact');
                if ~isempty(ind2)
                    ev(ind1(ind2)) = [];
                end
            end
        end

        Nevents = numel(ev);
        for i=1:numel(ctime)
            if ctime{i} == 0
                %likely to be trial border falsely detected as saccade
                continue;
            end
            ev(Nevents+i).type  = 'artefact_saccade';
            ev(Nevents+i).value = char(D.chanlabels(chanind));
            if S.excwin == 0
                ev(Nevents+i).duration = [];
                ev(Nevents+i).time     = ctime{i};
            else
                ev(Nevents+i).time     = max(D.trialonset(n), ctime{i} - 5e-4*S.excwin);
                ev(Nevents+i).duration = min(1e-3*S.excwin, (D.time(end)-D.time(1))-(ev(Nevents+i).time-D.trialonset(n)))+...
                    min(ctime{i} - 5e-4*S.excwin, 0);
            end
        end

        if ~isempty(ev)
            [dum, I] = sort([ev.time]);
            ev = ev(I);
            D = events(D, n, ev);
        end
    end
else
    warning('No saccade events detected in the selected channel.');
end

res = D;

spm('FigName','M/EEG saccade detection: done');


text:
classdef SettingsInterpolation < AbstractSettings

    properties (Access = protected)
        defaultParamsName = 'paramsMaterialInterpolation.json'
    end

    properties (Access = public)
        constitutiveProperties
        typeOfMaterial
        interpolation
        dim
        ndim
        type
        nElem
        ngaus
        simpAllType
    end

    methods (Access = public)

        function obj = SettingsInterpolation(varargin)
            if nargin == 1
                obj.loadParams(varargin{1})
            end
            obj.init();
        end

    end

    methods (Access = private)

        function init(obj)
            s = obj.constitutiveProperties;
            if isstruct(s)
                obj.constitutiveProperties = SettingsConstitutiveProperties(s);
            end
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
        	% Stergerea spatiul de lucru si a figurii curente
	clear; clf;
			% Introducerea punctelor definite
			% -	vectorul x cu abscisele punctelor
	x=0:5;
            % -	vectorul y cu ordonatele punctelor
	y=[0 0.5 4.5 0 2 0];
			% Generarea vectorului xx cu pasul fin
	xx=0:0.1:5;
            % Reprezentarea grafica cu subplot-uri
	h=subplot(2,2,1)
            % Precizarea positiei si marimii celulei de figura
    set(h,'position',[0.05,0.55,0.4,0.4])
            % Se reprezinta cu *-uri negre punctele date
	plot(x,y,'ko');
	hold on
		    % Interpolarea liniara
            % si reprezentarea functiilor obtinute
	yy=interp1(x,y,xx,'linear');
	plot(xx,yy,'r','LineWidth',1.5);
            % Personalizrea reprezentarii grafice
	grid on;
	title('LINEAR');

		    % Interpolarea de tip nearest
	h=subplot(2,2,2)
	set(h,'position',[0.5,0.55,0.4,0.4])
    plot(x,y,'ko');
	hold on
	yy=interp1(x,y,xx,'nearest');
	plot(xx,yy,'g','LineWidth',1.5);
	grid on;
	title('NEAREST');

			% Interpolarea de tip spline
	h=subplot(2,2,3)
    set(h,'position',[0.05,0.05,0.4,0.4])
 	plot(x,y,'ko');
	hold on
	yy=interp1(x,y,xx,'spline');
	plot(xx,yy,'m','LineWidth',1.5);
	grid on;
	title('SPLINE')

            % Interpolarea de tip cubic
	h=subplot(2,2,4)
    set(h,'position',[0.5,0.05,0.4,0.4])
    plot(x,y,'ko');
	hold on
	yy=interp1(x,y,xx,'cubic');
	plot(xx,yy,'b','LineWidth',1.5);
	grid on;
	title('CUBIC')


text:
function tf = regexpmatch(s,pat,varargin)
% tf = regexpmatch(s,pat,p1,v1,...)
% Either s xor pat is expected to be a cellstr.
% Optional PVs:
% - caseinsens, logical scalar

assert(iscellstr(s)&&ischar(pat) || ischar(s)&&iscellstr(pat),...
  'Invalid input arguments.');

caseinsens = myparse(varargin,'caseinsens',false);
if caseinsens
  fcn = @regexpi;
else
  fcn = @regexp;
end

if iscellstr(s)
  tf = cellfun(@(x)~isempty(fcn(x,pat,'once')),s);
else
  tf = cellfun(@(x)~isempty(fcn(s,x,'once')),pat);
end

author: kristinbranson

repo: JAABA


text:
% This is the testing demo of FFDNet for denoising noisy grayscale images corrupted by
% AWGN with clipping setting. The noisy input is 8-bit quantized.
% "FFDNet: Toward a Fast and Flexible Solution for CNN based Image Denoising"
%  2018/03/23
% If you have any question, please feel free to contact with me.
% Kai Zhang (e-mail: cskaizhang@gmail.com)

%clear; clc;
format compact;
global sigmas; % input noise level or input noise level map
addpath(fullfile('utilities'));

folderModel = 'models';
folderTest  = 'testsets';
folderResult= 'results';
imageSets   = {'BSD68','Set12'}; % testing datasets
setTestCur  = imageSets{1};      % current testing dataset

showResult  = 1;
useGPU      = 1; % CPU or GPU. For single-threaded (ST) CPU computation, use "matlab -singleCompThread" to start matlab.
pauseTime   = 0;

imageNoiseSigma = 25;  % image noise level, 25.5 is the default setting of imnoise( ,'gaussian')
inputNoiseSigma = 25;  % input noise level

folderResultCur       =  fullfile(folderResult, [setTestCur,'_Clip_',num2str(imageNoiseSigma),'_',num2str(inputNoiseSigma)]);
if ~isdir(folderResultCur)
    mkdir(folderResultCur)
end

load(fullfile('models','FFDNet_Clip_gray.mat'));
net = vl_simplenn_tidy(net);

% for i = 1:size(net.layers,2)
%     net.layers{i}.precious = 1;
% end

if useGPU
    net = vl_simplenn_move(net, 'gpu') ;
end

% read images
ext         =  {'*.jpg','*.png','*.bmp'};
filePaths   =  [];
for i = 1 : length(ext)
    filePaths = cat(1,filePaths, dir(fullfile(folderTest,setTestCur,ext{i})));
end

% PSNR and SSIM
PSNRs = zeros(1,length(filePaths));
SSIMs = zeros(1,length(filePaths));

for i = 1:length(filePaths)

    % read images
    label = imread(fullfile(folderTest,setTestCur,filePaths(i).name));
    [w,h,~]=size(label);
    if size(label,3)==3
        label = rgb2gray(label);
    end

    [~,nameCur,extCur] = fileparts(filePaths(i).name);
    label = im2single(label);

    % add noise
    randn('seed',0);
    %input = imnoise(label,'gaussian'); % corresponds to imageNoiseSigma = 25.5;
    input = imnoise(label,'gaussian',0,(imageNoiseSigma/255)^2);

    if mod(w,2)==1
        input = cat(1,input, input(end,:)) ;
    end
    if mod(h,2)==1
        input = cat(2,input, input(:,end)) ;
    end

    % tic;
    if useGPU
        input = gpuArray(input);
    end

    % set noise level map
    sigmas = inputNoiseSigma/255; % see "vl_simplenn.m".

    % denoising
    res    = vl_simplenn(net,input,[],[],'conserveMemory',true,'mode','test');
    output = res(end).x;

    if mod(w,2)==1
        output = output(1:end-1,:);
        input  = input(1:end-1,:);
    end
    if mod(h,2)==1
        output = output(:,1:end-1);
        input  = input(:,1:end-1);
    end

    if useGPU
        output = gather(output);
        input  = gather(input);
    end
    % toc;
    % calculate PSNR, SSIM and save results
    [PSNRCur, SSIMCur] = Cal_PSNRSSIM(im2uint8(label),im2uint8(output),0,0);
    if showResult
        imshow(cat(2,im2uint8(input),im2uint8(label),im2uint8(output)));
        title([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])
        %imwrite(im2uint8(output), fullfile(folderResultCur, [nameCur, '_' num2str(imageNoiseSigma,'%02d'),'_' num2str(inputNoiseSigma,'%02d'),'_PSNR_',num2str(PSNRCur*100,'%4.0f'), extCur] ));
        drawnow;
        pause(pauseTime)
    end
    disp([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])
    PSNRs(i) = PSNRCur;
    SSIMs(i) = SSIMCur;
end

disp([mean(PSNRs),mean(SSIMs)]);

author: cszn

repo: FFDNet

save_path: github-repos/MATLAB/cszn-FFDNet


text:
function holdout_sets = xval_select_holdout_set_categoricalcovs(covs)

u = unique(covs, 'rows');
nu = size(u, 1);  % number of unique cells; also size of holdout sets

[N, k] = size(covs);

onevec = ones(N, 1);

% indices for each cell
for i = 1:nu
    cell_indices{i} = all(covs - u(i * onevec, :) == 0, 2);
end

nobs_per_cell = sum(cat(2, cell_indices{:}));
nfolds = max(nobs_per_cell);  % number of folds; max() leaves some unbalanced holdout sets; min keeps balance but does not test all obs

% random selection of one obs per cell for each fold
for i = 1:nu
    wh_obs{i} = find(cell_indices{i});
    wh_obs{i} = wh_obs{i}(randperm(nobs_per_cell(i)));
end

% deal observations into folds
for i = 1:nfolds
    wh = [];
    for j = 1:nu
        if nobs_per_cell(j) >= i
            wh = [wh wh_obs{j}(i)];
        end
    end

    holdout_sets{i} = logical(false * onevec);
    holdout_sets{i}(wh) = true;

end

end  % function

% checking stuff
% allsets = cat(2, holdout_set{:});
% sum(allsets)
% sum(allsets, 2)
% covs(holdout_set{1}, :)
% covs(holdout_set{2}, :)
% covs(holdout_set{3}, :)
% covs(holdout_set{4}, :)
% covs(holdout_set{end}, :)

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function [camCorners, usedImIdx] = getCameraCorners(calibInfo)
%% Extract checkerboard corners given calibInfo.

%% License
% ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
% Copyright (c) 2018 Bingyao Huang
% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:

% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.

% If you publish results obtained using this software, please cite our paper.

% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.

%%
% Get a list of images that has 'light' in file name.
imLightNames = ImgProc.getImageNames(calibInfo.path, 'lightGrid', calibInfo.sets);

% resize image to width = 640, since MATLAB detectCheckerboardPoints may fail on large images.
w = 640;
imCheckerboard = readAllImgs(imLightNames);

if(size(imCheckerboard, 2) > w)
    imCheckerboardSmall = imresize(imCheckerboard, [nan, w]);
else
    imCheckerboardSmall = imCheckerboard;
end

% extract checkerboard corners
[camCornersTemp, boardSize, usedImIdx] = detectCheckerboardPoints(imCheckerboardSmall);

if(size(imCheckerboard, 2) > w)
    % scale checkerboard coordinates to the orginal size
    camCornersTemp = camCornersTemp * size(imCheckerboard, 2) / w;
end

if(nnz(boardSize == calibInfo.boardSize) < 2)
    error('Extracted checkerboard size does not match calib-info.yml, please check calib-info.yml and checkerboard image');
end

% initialize corner coordiantes with [-1, -1] if fail to extract corners
% from some images, this is to avoid MT GUI file not found error
numImages = numel(usedImIdx);
numCorners = (boardSize(1)-1)*(boardSize(2)-1);

camCorners = -ones(numCorners,2, numImages);
camCorners(:,:,usedImIdx) = camCornersTemp;

if(nnz(usedImIdx) < length(usedImIdx))
    warning(['Unable to extract checkerboard corners in set(s): ','[', num2str(find(usedImIdx == 0))',']'])
end
end

function imD = readAllImgs(imgPath, ext, idx)

if(nargin < 2)
    imgDs = imageDatastore(imgPath);
else
    imgDs = imageDatastore(imgPath, 'FileExtensions', ext);
end

numImgs = length(imgDs.Files);

if(nargin < 3)
    idx = 1:numImgs;
end

% read all images as cell (very fast)
imD = imgDs.readall;

% keep only the idx
imD = imD(idx);

% convert to 4D mat
imD = cat(4, imD{:});
end

author: BingyaoHuang

repo: single-shot-pro-cam-calib


text:
%STAMP_MAP Stamping and storing of mappings for fast reusage
%
%		C = STAMP_MAP(A,W) or C = A*W
%		U = STAMP_MAP(V,W) or U = V*W
%
% This routine is equivalent to MAP except that it stores previous
% results (C or U) and retrieves them when the same inputs (A and W
% or V and W) are given. This is especially good in case of combining
% classifier studies when the same mappings have to be computed multiple
% times.
%
% Note that only the highest level of calls to MAP are stored by STAMP_MAP.
% If multiple calls to lower level calls (e.g. somewhere included in a
% complicated combined classifier) are expected, they should be called
% first explicitely.
%
% STAMP_MAP is automatically called inside MAP (and thereby by every
% overloaded * operation between datasets and mappings) controlled by
% the following settings:
%
% STAMP_MAP(0)  - disables all storage and retrieval of mappings.
%                 This should be called when no duplicates are expected
%                 as it prevents the unnecessary checking of inputs.
% STAMP_MAP(1)  - Retrieving of stored results only only.
%                 No new results are stored.
% STAMP_MAP(2)  - Enables retrieval as well as storage of results.
%
% SEE ALSO (PRTools Guide)
% DATASETS, MAPPINGS, MAP

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

function c = stamp_map(a,b)

	persistent CHECK_STAMPS nstamps cell_stamp stamps

	if isempty(CHECK_STAMPS)
		CHECK_STAMPS = 0;
		nstamps = 0;
		stamps = zeros(1000,3);
		cell_stamp = cell(1,1000);
	end

	if nargin == 0
		c = CHECK_STAMPS;
	elseif nargin == 1
		if a < 3
			CHECK_STAMPS = a;
			if nargout > 0
				c = a;
			end
		else
			disp(nstamps)
			for j=1:nstamps
				fprintf('STAMPS: %10.6e %10.6e: ',stamps(j,:));
				cell_stamp{j}
			end
		end

	else

		if CHECK_STAMPS == 0 % checking is off, no stamp_mapping

			c = []; % execution call: try to pass this routine

		elseif iscell(a) | iscell(b) % don't handle cell constructs

			c = [];

		elseif CHECK_STAMPS == 1 | CHECK_STAMPS == 2  % checking is on

			sa = getstamp(a);
			sb = getstamp(b);
			Ja = find(stamps(1:nstamps,1)==sa);
			J = [];
			if ~isempty(Ja)
				Jb = find(stamps(Ja,2)==sb);
				if ~isempty(Jb)   % found, we have it!
					J = Ja(Jb);
					if ~isempty(J) & length(J) > 1
						error('Stamps are not unique')
					end
					c = cell_stamp{J}; % use it!
					stamps(J,3) = stamps(J,3)+1;
					%disp(['found: ' getname(a) '..,..' getname(b)])
				end
			end
			if isempty(J)                       % not found, let map do the work
				checkstamps = CHECK_STAMPS;       % Take care that we skip stamp_map
				CHECK_STAMPS = checkstamps+2;     % when we call map
				c = prmap(a,b); % during execution of map CHECK_STAMPS will be reset
				CHECK_STAMPS = checkstamps;       % so this is in fact not needed
				if CHECK_STAMPS == 2        % store as well
					%disp(['stored: ' getname(a) '..,..' getname(b)])
					nstamps = nstamps + 1;
					if nstamps > length(cell_stamp)
						stamps = [stamps; zeros(1000,3)];
						cell_stamp = [cell_stamp cell(1,1000)];
					end
					stamps(nstamps,1:2) = [sa,sb];
					cell_stamp{nstamps} = c;
				end
			end

		elseif CHECK_STAMPS == 3 | CHECK_STAMPS == 4

			CHECK_STAMPS = CHECK_STAMPS-2;  % reset of computation of map
			c = [];

		else

			;

		end

	end

return

%GETSTAMP Compute unique stamp for data
%
% S = GETSTAMP(A)
%
%Computes 64-bit stamp S of input A

function s = getstamp(a)

s = 0;
type = class(a);

switch(type)

	case 'char'
		a = abs(a);
		n = length(a(:));
		s = s + abs(sin(1:n))*(a(:));

	case 'double'
		n = length(a(:));
		s = s + abs(sin(1:n)*a(:));

	case {'prmapping','prdataset','prdatafile'}
		a = struct2cell(struct(a));
		s = s + getstamp(a);

	case 'struct'
		a = struct2cell(a);
		s = s + getstamp(a);

	case 'cell'
		for j=1:length(a(:))
			s = s + getstamp(a{j});
		end

	otherwise
		try
			n = length(a(:));
			s = s + abs(sin(1:n))*abs(double(a(:)));
		catch
			;
		end

end

author: marianux

repo: ecg-kit

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


text:
function spm_DFP_plot(QU,pU)
% plots particles for spm_DFP
% FORMAT spm_DFP_plot(QU,Nt)
% FORMAT spm_DFP_plot(QU,pU)
%--------------------------------------------------------------------------
% QU{t}(p).x{d}  - ensemble of hidden states
% QU{t}(p).v{d}  - ensemble of causal states
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_DFP_plot.m 6540 2015-09-05 10:06:42Z karl $

% defaults for plotting
%--------------------------------------------------------------------------
clf
try
    pX = pU.x{1};
    pV = pU.v{2};
    Nt = length(pX);
catch
    try Nt = pU; catch, Nt = length(QU); end
end

% time-series specification
%--------------------------------------------------------------------------
nx    = size(QU{1}(1).x{1},1);
nv    = size(QU{1}(1).v{1},1);
np    = length(QU{1});
nt    = length(QU);

% unpack states
%--------------------------------------------------------------------------
for t = 1:nt
    for j = 1:np
        for i = 1:nx
            X{i}(t,j) = QU{t}(j).x{1}(i);
        end
        for i = 1:nv
            V{i}(t,j) = QU{t}(j).v{1}(i);
        end
    end
end

% causes
%--------------------------------------------------------------------------
if nt < 2, return, end

subplot(2,1,1)
for i = 1:nv
    plot(1:nt,V{i},':','Color',[1 1 1]/(2 + i - 1))
    hold on
    if np < 16
        plot(nt,V{i}(nt,:),'.','Color',[1 1 1]/(2 + i - 1),'MarkerSize',32)
        plot(nt,V{i}(nt,:),'.','Color',[1 1 1],'MarkerSize',4)
    else
        plot(nt,V{i}(nt,:),'.','Color',[1 0 0],'MarkerSize',8)
    end
    plot(1:nt,mean(V{i},2),'--b','LineWidth',2)
    hold on
end
try
    hold on
    plot((1:nt) - 1,pV,'r')
end
hold off
title('causes','FontSize',16);
xlabel('time (steps)','FontSize',14)
grid on
axis square
set(gca,'XLim',[1 Nt])

% hidden states
%--------------------------------------------------------------------------
if ~nx, drawnow, return, end

subplot(2,1,2)
for i = 1:nx
    plot(1:nt,X{i},':','Color',[1 1 1]/(2 + i - 1))
    hold on
    if np < 16
        plot(nt,X{i}(nt,:),'.','Color',[1 1 1]/(2 + i - 1),'MarkerSize',32)
        plot(nt,X{i}(nt,:),'.','Color',[1 1 1],'MarkerSize',4)
    else
        plot(nt,X{i}(nt,:),'.','Color',[1 0 0],'MarkerSize',8)
    end
    plot(1:nt,mean(X{i},2),'--b','LineWidth',2)
    hold on
end
try
    hold on
    plot((1:nt) - 1,pX,'r')
end
hold off
title('hidden states','FontSize',16);
xlabel('time (steps)','FontSize',14)
grid on
axis square
set(gca,'XLim',[1 Nt])
drawnow

return

% movie
%--------------------------------------------------------------------------
spm_figure('GetWin','DFP');
subplot(2,1,2)
try
    load DFP_movie
    M(end + 1) = getframe;
catch
    M = getframe;
end
save DFP_movie M


text:
function test_mcmc_reflective()

N = 2;
mu = zeros(N,1);
Q = [1 1; -1 1]; %orth(randn(N));
D = (1-0.95)*eye(N);
D(1) = 1;
Cov = Q*D*Q';
%Cov = W'*W;
L = chol(Cov, 'lower');

get_logpdf = @(x) (@()gaussian_logpdf(x, mu, L));
get_dlogpdf = @(x) (@()gaussian_dlogpdf(x, mu, L));

x_init = 10*ones(N,1);
%x_init = zeros(N,1);

M = 1000;

% Test metropolis-hastings
y_mh = zeros(N,M);
if 1
  q = @(x) normrnd(x,0.3);
  logpdf_q = @(x,x0) normal_logpdf(x,x0,0.3);
  sampler = mcmc_init_metropolishastings(x_init, get_logpdf, q, logpdf_q);
  for m=1:M
    y_mh(:,m) = sampler();
  end
end

% Test hamiltonian
y_h = zeros(N,M);
if 1
  sampler = mcmc_init_hamiltonian(x_init, get_logpdf, get_dlogpdf, 0.3, 10);
  for m=1:M
    y_h(:,m) = sampler();
  end
end

% Test slice
y_s = zeros(N,M);
if 1
  sampler = mcmc_init_slicesampling(x_init, get_logpdf);
  for m=1:M
    y_s(:,m) = sampler();
  end
end

% Test inside reflective
y_r = zeros(N,M);
if 1
  sampler = mcmc_init_reflective(x_init, get_logpdf, get_dlogpdf, 0.01, ...
                                 300, 'type', 'inside');
  for m=1:M
    y_r(:,m) = sampler();
  end
  % TODO: Is this correct?
  y_r(:,isnan(y_r(1,:))) = [];
end

y = bsxfun(@plus, mu, L*randn(N,M));

figure(1)
clf();
plot(y(1,:), y(2,:), 'k.')
hold on
plot(y_mh(1,:), y_mh(2,:), 'r.')
plot(y_h(1,:), y_h(2,:), 'c.')
plot(y_s(1,:), y_s(2,:), 'b.')
plot(y_r(1,:), y_r(2,:), 'g.')

% Burn-in
M0 = 100;
y_mh = y_mh(:,M0:end);
y_h = y_h(:,M0:end);
y_s = y_s(:,M0:end);
y_r = y_r(:,M0:end);

M0 = 100;

T = Cov + mu*mu'
YY = y*y' / (size(y,2))
YY_mh = y_mh*y_mh' / (size(y_mh,2))
YY_h = y_h*y_h' / (size(y_h,2))
YY_s = y_s*y_s' / (size(y_s,2))
YY_r = y_r*y_r' / (size(y_r,2))

% Auto-correlation
figure(2)
clf();
lag = 100;
subplot(5,1,1)
plot(0:lag, acorr(y',lag))
subplot(5,1,2)
plot(0:lag, acorr(y_mh',lag))
subplot(5,1,3)
plot(0:lag, acorr(y_h',lag))
subplot(5,1,4)
plot(0:lag, acorr(y_s',lag))
subplot(5,1,5)
plot(0:lag, acorr(y_r',lag))

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


text:
function y=sum_rate_direct(x,A,B,omega,K)
    tmp=zeros(K,K);
    for i0=1:K
        for k0=1:K
            tmp(i0,k0)=abs(x'*A(:,:,i0,k0)+B(i0,k0))^2;
        end
    end
    yt=zeros(K,1);
    for k0=1:K
        tmp1=sum(tmp(:,k0));
        tmp2=tmp1-tmp(k0,k0);
        yt(k0)=log(1+tmp(k0,k0)/(tmp2+1));
    end
    y=-omega*yt;
end

author: guohuayan


text:
% absolute value of smoothed change in orientation
function [data,units] = compute_abssmoothdtheta(trx,n)

flies = trx.exp2flies{n};
nflies = numel(flies);
data = cell(1,nflies);
for i = 1:nflies,
  fly = flies(i);
  data{i} = abs(trx(fly).smoothdtheta);
end
units = parseunits('rad/s');


text:
function [ y, j ] = j_borrow_islamic ( y, j )

%*****************************************************************************80
%
%% J_BORROW_ISLAMIC borrows year-days from years in an Islamic date.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 June 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input/output, integer Y, J, a YJ date.
%
  while ( j <= 0 )

    y = y - 1;

    days = year_length_islamic ( y );

    j = j + days;

  end

  return
end


text:
function a = spiral(hyper)

%=================================================================================
% TOY SPIRAL data generation object
%=================================================================================
% A=spiral(H) returns a spiral toy data object initialized with hyperparameters H.
%
% This generates 2 spirals with 4*m points per spiral, where 1*m points are
% points on two perfect spiral and 3*m points are some additive noise on
% the first quarter.
%
%
% Hyperparameters, and their defaults
%  n=1           --  a parameter :-) play to explore
%  m=50          --  number of used points per winding
%
% Model
%
% Methods:
%  generate,train,test
%  Example :
%   d=gen(spiral({'n=1','m=50'}));
%   [r s0]=train(svm(kernel('rbf',1)),d)
%   plot(s0,[ -20 20 -20 20]);
%=================================================================================
% Reference :
% Author    :
% Link      :
%=================================================================================

  a.m=50;
  a.n=2;
  a.noise=1;

  p=algorithm('spiral');
  a= class(a,'spiral',p);

  if nargin==1
    eval_hyper;
  end


text:
%Enumerates the different types of data in the WDK and provides
%functionality to convert them to strings
classdef DataType
    properties (Access = public, Constant)
        kDataFile = 0;
        kSignal = 1;
        kSignal2 = 2;
        kSignal3 = 3;
        kSignalN = 4;
        kEvent = 5;
        kSegment = 6;
        kFeature = 7;
        kFeatureVector = 8;
        kTable = 9;
        kTableSet = 10;
        kLabels = 11;
        kAny = 12;
        kNull = 13;
        kAnnotation = 14;
        kClassificationResult = 15;
        kRegressionResult = 16;
    end

    properties (Access = public, Constant)
        TypeStrings = {'DataFile' , 'Signal (1D)', 'Signal (2D)', 'Signal (3D)',...
            'Signal', 'Event', 'Segment', 'Feature', 'FeatureVector', ...
            'Table','TableSet', 'Labels', 'Any', 'Null', 'Annotation', 'ClassificationResult','RegressionResult'};
    end

    methods (Access = public, Static)
        function str = DataTypeToString(type)
            str = DataType.TypeStrings{type+1};
        end
    end
end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function test_failed = test_blockfwt()
test_failed = 0;

disp('-------------TEST_BLOCKFWT--------------');

L = 567;
W = [1,3];

Lb = [78,64,58,1021];

wa = {'dden3','ana:symorth1'};
ws = {'dden3','syn:symorth1'};
J = [5];

for wId = 1:numel(W)
for lId = 1:numel(L)
f = tester_rand(L(lId),W(wId));
for lbId = 1:numel(Lb)
for waId=1:numel(wa)

Fa = blockframeaccel(frame('fwt',wa{waId},J),Lb(lbId),'segola');
Fs = blockframeaccel(frame('fwt',ws{waId},J),Lb(lbId),'segola');

a = Fa.g.a(1);
m = numel(Fa.g.g{1}.h);
rmax = (a^J-1)/(a-1)*(m-1);

f = postpad(f,L(lId)+rmax);
block(f,'offline','L',Lb(lbId));

colC = {};
colfhat = {};

for ii=1:ceil(L(lId)/Lb(lbId))
    fb = blockread();
    c  = blockana(Fa,fb);
    ccell = comp_fwtpack2cell(Fa,c);

    colC{end+1} = ccell;

    chat = cell2mat(ccell);

    fhat = blocksyn(Fs,chat,size(fb,1));
    colfhat{end+1} = fhat;
end

err = 0;
cwhole = fwt(f,wa{waId},J,'zero','cell');
for ii=1:numel(colC{1})
   cc{ii} = cell2mat(cellfun(@(cEl) cEl{ii},colC','UniformOutput',0));
   Ltmp = min([size(cwhole{ii},1),size(cc{ii},1)]);
   err = err + norm(cwhole{ii}(1:Ltmp,:)-cc{ii}(1:Ltmp,:));
end

[test_failed,fail]=ltfatdiditfail(err,test_failed);
fprintf('COEFS L:%3i, W:%3i, Lb=%3i, %s, err=%.4e %s\n',L(lId),W(wId),Lb(lbId),wa{waId},err,fail);

fhat = cell2mat(colfhat.');

fhat = fhat(rmax+1:end,:);

Lcrop = min([size(fhat,1),size(f,1)]);

res = norm([f(1:Lcrop,:)-fhat(1:Lcrop,:)]);
[test_failed,fail]=ltfatdiditfail(res,test_failed);
fprintf('REC   L:%3i, W:%3i, Lb=%3i, %s, err=%.4e %s\n',L(lId),W(wId),Lb(lbId),wa{waId},res,fail);

end
end
end
end

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function text2speech(str, lang, t_play)
% This is a command line demo on how to use the ActiveX VideoLAN.VLCPlugin.2 in combination with the
% unofficial google text to speech (TTS) engine to generate speech from text.
% You need to install the VLC-Media-Player and have a internetconnection to call the google service.
%
% The input parameters are:
%   - the string you want to convert:                       str
%   - then string of language code for the str:             lang   {'en','de','es', 'fr'}
%   - and the time in seconds until programm resumes:       t_play
%     if the time is to short, you'll maybe not hear everything
%
% Function call:
%     text2speech --> says 'Hello World' in english
%     text2speech('Guten Morgen!','de') --> says good morning in german
%     text2speech('Je t'aime.','fr')    --> says I love you in french
%
% Bugs and suggestions:
%    Please send to Sven Koerner: koerner(underline)sven(add)gmx.de
%
% You need to download and install first:
%    The VLC Media Player:  http://www.videolan.org/vlc/
%
%
% Programmed by Sven Koerner: koerner(underline)sven(add)gmx.de
% Date: 2011/11/04

% Standard time until close is 2 Seconds
if nargin < 3
    t_play = 2;
end
% Standard language is english
if nargin < 2
    lang = 'en';
end

% Standard sentence
if nargin < 1,
    str = 'Hello World!';
end;

% Create invisible figure
fig = figure('units','characters','position', [1 1 1 1] ,'Toolbar','none','DoubleBuffer', 'on', 'Name', 'Read it!', 'NumberTitle', 'off','MenuBar','none','Visible','off');

% Preapare String:
% limit string to at least 100 characters and replace blanks
try
    str = strrep(str(1:100),' ','+');
catch
    str = strrep(str,' ','+');
end;

% insert the vlc-component invisible to figure
vlc1 = actxcontrol('VideoLAN.VLCPlugin.2', [1 1 0 0], fig);
vlc1.Volume   = 50;   % Set Volume
vlc1.AutoLoop = 0;    % Set Autoloop
vlc1.playlist.add(['http://translate.google.com/translate_tts?tl=',lang ,'&q=', str] );  % Unofficial text to speech  by google
vlc1.playlist.play;   % play it
pause(t_play);        % wait a while
close();              % close the fig

author: Sable

repo: mcbench-benchmarks