text:
function varargout = VBA_spm_select(varargin)
% File selector
% FORMAT [t,sts] = spm_select(n,typ,mesg,sel,wd,filt,frames)
% n      - number of files [Default: Inf]
%          A single value or a range.  e.g.
%          1       - select one file
%          Inf     - select any number of files
%          [1 Inf] - select 1 to Inf files
%          [0 1]   - select 0 or 1 files
%          [10 12] - select from 10 to 12 files
% typ    - file type [Default: 'any']
%          'any'   - all files
%          'image' - Image files (".img" and ".nii")
%                    Note that it gives the option to select individuals
%                    volumes of the images.
%          'mesh'  - Surface mesh files (".gii")
%          'xml'   - XML files
%          'mat'   - MATLAB .mat files or .txt files (assumed to contain
%                    ASCII representation of a 2D-numeric array)
%          'batch' - SPM batch files (.m, .mat and XML)
%          'dir'   - select a directory
%          Other strings act as a filter to regexp. This means that
%          e.g. DCM*.mat files should have a typ of '^DCM.*\.mat$'
% mesg   - a prompt [Default: 'Select files...']
% sel    - list of already selected files [Default: {}]
% wd     - directory to start off in [Default: pwd]
% filt   - value for user-editable filter [Default: '.*']
% frames - image frame numbers to include [Default: '1']
%
% t      - selected files
% sts    - status (1 means OK, 0 means window quit)
%
% FORMAT [files,dirs] = spm_select('List',direc,filt)
% Return files matching the filter 'filt' and directories within 'direc'
% direc  - directory to search [Default: pwd]
% filt   - filter to select files with regexp, e.g. '^w.*\.img$' [Default: '.*']
%
% files  - files matching 'filt' in directory 'direc'
% dirs   - subdirectories of 'direc'
%
% FORMAT [files,dirs] = spm_select('ExtList',direc,filt,frames)
% As above, but for selecting frames of 4D NIfTI files
% frames - vector of frames to select (defaults to 1, if not specified).
%          If the frame number is Inf, all frames for the matching images
%          are listed.
%
% FORMAT [files,dirs] = spm_select('FPList',direc,filt)
% FORMAT [files,dirs] = spm_select('ExtFPList',direc,filt,frames)
% As above, but return files with full paths (i.e. prefixes 'direc' to each)
%
% FORMAT [files,dirs] = spm_select('FPListRec',direc,filt)
% FORMAT [files,dirs] = spm_select('ExtFPListRec',direc,filt,frames)
% As above, but return files with full paths (i.e. prefixes 'direc' to each)
% and search through sub directories recursively.
%__________________________________________________________________________
% Copyright (C) 2005-2014 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_select.m 6181 2014-09-17 16:35:39Z guillaume $

% For developers:
%--------------------------------------------------------------------------
% FORMAT cpath = spm_select('CPath',path,cwd)
% Canonicalise paths: prepend cwd to relative paths, process '..' & '.'
% directories embedded in path.
% path   - string matrix containing path name
% cwd    - current working directory [Default: '.']
% cpath  - canonicalised paths, in same format as input path argument
%
% FORMAT [t,ind] = spm_select('Filter',files,typ,filt,frames)
% Filter the list of files (cell or char array) in the same way as the
% GUI would do. There is an additional typ 'extimage' which will match
% images with frame specifications, too. Also, there is a typ 'extdir',
% which will match canonicalised directory names. The 'frames' argument
% is currently ignored, i.e. image files will not be filtered out if
% their frame numbers do not match.
% t returns the filtered list (cell or char array, depending on input),
% ind an index array, such that t = files{ind}, or t = files(ind,:).
%
% FORMAT spm_select('PrevDirs',dir)
% Add directory dir to list of previous directories.
% FORMAT dirs = spm_select('PrevDirs')
% Retrieve list of previous directories.
%
% FORMAT files = spm_select('Expand',files)
% Return a list of image filenames with appended frame numbers.

persistent isInitSelect;
if isempty(isInitSelect)
    isInitSelect = true;
    VBA_spm_select('init');
    if nargin == 1 && strcmpi(varargin{1},'init'), return; end
end

%-Commands that are not passed to cfg_getfile
local_cmds = {'regfilter', 'init', 'expand'};

if nargin && ischar(varargin{1}) && any(strcmpi(varargin{1},local_cmds))
    switch lower(varargin{1})
        case 'init'
            if ~isdeployed && ~exist('cfg_getfile','file')
                addpath(fullfile(spm('dir'),'matlabbatch'));
            end
            VBA_spm_select('regfilter');
            VBA_spm_select('prevdirs',spm('Dir'));

        case 'regfilter'
            % Regexp based filters without special handlers
            cfg_getfile('regfilter', 'mesh',  {'\.gii$'});
            cfg_getfile('regfilter', 'gifti', {'\.gii$'});
            cfg_getfile('regfilter', 'nifti', {'\.nii$','\.img$'});
            % Filter for 3D images that handles frame expansion
            frames = cfg_entry;
            frames.name    = 'Frames';
            frames.tag     = 'frames';
            frames.strtype = 'n';
            frames.num     = [1 Inf];
            frames.val     = {1};
            cfg_getfile('regfilter', 'image',...
                {'.*\.nii(,\d+){0,2}$','.*\.img(,\d+){0,2}$'},...
                false, @VBA_spm_select_image, {frames});

        case 'expand'
            varargout{1} = VBA_spm_select_expand(varargin{2});
            if ischar(varargin{2}), varargout{1} = char(varargout{1}); end
    end
else
    needchar = false;
    % cfg_getfile expects cellstr arguments for multi-line strings
    if nargin > 1 && ischar(varargin{1}) && ...
            ismember(lower(varargin{1}),{'filter','cpath'}) && ischar(varargin{2})
        varargin{2} = cellstr(varargin{2});
        needchar = true;
    elseif nargin > 0 && ischar(varargin{1}) && ...
            ismember(lower(varargin{1}),{'extlist','extfplist','extfplistrec'})
        varargin{1} = varargin{1}(4:end);
        if nargin > 3
            varargin{5} = struct('frames', varargin{4});
        else
            varargin{5} = struct('frames', Inf);
        end
        varargin{4} = varargin{3};
        varargin{3} = 'image';
    end

    [t, sts] = cfg_getfile(varargin{:});

    % cfg_getfile returns cellstr arrays, convert to char arrays
    if nargin > 0 && ischar(varargin{1})
        switch lower(varargin{1})
            case {'filter','cpath'}
                if needchar
                    t = char(t);
                end
            case {'list','fplist','extlist','extfplist','fplistrec','extfplistrec'}
                t = char(t);
                sts = char(sts);
        end
    else
        t = char(t);
    end

    varargout{1} = t;
    if nargout > 1
        varargout{2} = sts;
    end
end

%==========================================================================
% FUNCTION varargout = spm_select_image(cmd, varargin)
%==========================================================================
function varargout = VBA_spm_select_image(cmd, varargin)
% Implements extended filtering for NIfTI images (including 3D frame
% selection)
switch lower(cmd)
    case 'list'
        dr     = varargin{1};
        files  = varargin{2};
        prms   = varargin{3};
        frames = prms.frames;
        ii = cell(1,numel(files));
        if numel(frames)==1 && isnan(frames)
            [ii{:}] = deal(1);
        elseif numel(frames)~=1 || frames(1)~=1
            % if domsg
            %     msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']);
            % end
            for i=1:numel(files)
                try
                    n = VBA_spm_select_get_nbframes(fullfile(dr,files{i}));
                    d4 = (1:n)';
                catch
                    d4 = 1;
                end
                if all(isfinite(frames))
                    ii{i} = intersect(d4, frames(:))';
                else
                    ii{i} = d4(:)';
                end
            end
        elseif numel(frames)==1 && frames(1)==1
            [ii{:}] = deal(1);
        end

        % if domsg
        %     msg(ob,['Listing ' num2str(numel(f)) ' files...']);
        % end

        % Combine filename and frame number(s)
        nii      = cellfun(@numel, ii);
        cfiles   = cell(sum(nii),1);
        fi       = cell(numel(files),1);
        for k = 1:numel(fi)
            fi{k} = k*ones(1,nii(k));
        end
        ii = [ii{:}];
        fi = [fi{:}]';
        if numel(frames)==1 && isnan(frames)
            cfiles = files;
        else
            for i=1:numel(cfiles)
                cfiles{i} = sprintf('%s,%d', files{fi(i)}, ii(i));
            end
        end
        varargout{1} = cfiles;
        varargout{2} = fi;
    case 'filter'
        % Do not filter for frame numbers
        varargout{1} = varargin{1};
        varargout{2} = 1:numel(varargout{1});
end

%==========================================================================
% FUNCTION ofiles = spm_select_expand(ifiles)
%==========================================================================
function ofiles = VBA_spm_select_expand(ifiles)
ifiles = cellstr(ifiles);
ofiles = {};
for i=1:numel(ifiles)
    [p,f,e,n] = VBA_spm_fileparts(ifiles{i});
    if ~isempty(n)
        ofiles = [ofiles; ifiles{i}];
    else
        n = VBA_spm_select_get_nbframes(ifiles{i});
        vfiles = cell(n,1);
        for j=1:n
            vfiles{j} = [ifiles{i} ',' num2str(j)];
        end
        ofiles = [ofiles; vfiles];
    end
end

%==========================================================================
% FUNCTION n = spm_select_get_nbframes(file)
%==========================================================================
function n = VBA_spm_select_get_nbframes(file)
N   = nifti(file);
dim = [N.dat.dim 1 1 1 1 1];
n   = dim(4);

% % A faster, direct implementation
% [p,f,e] = fileparts(file);
% unchanged = true;
% ind = find(e==',');
% if ~isempty(ind)
%     unchanged = false;
%     e = e(1:(ind(1)-1));
% end
% switch e
%     case {'.img'}
%         unchanged = false;
%         e = '.hdr';
%     case {'.IMG'}
%         unchanged = false;
%         e = '.HDR';
% end
% if ~unchanged
%     file = fullfile(p,[f e]);
% end
%
% n = [];
%
% fp  = fopen(file,'r','native');
% if fp==-1, return; end
%
% %sts = fseek(fp,344,'bof');
% %if sts==-1, fclose(fp); return; end
% %mgc = deblank(char(fread(fp,4,'uint8')'));
%
% sts = fseek(fp,40,'bof');
% if sts==-1, fclose(fp); return; end
% dim = fread(fp,8,'*int16');
% fclose(fp);
% if isempty(dim), return; end
% if dim(1)<1 || dim(1)>7
%     dim = swapbytes(dim);
% end
% dim = double(dim(2:(dim(1)+1)))';
% dim = [dim 1 1 1 1 1];
% n   = dim(4);

author: MBB-team

repo: VBA-toolbox


text:
function [Xnorm] = L1infnorm(X)
% ||X||_{1,2} = sum_i||X^i||_inf
Xnorm = sum(max(abs(X),[],2));

author: jiayuzhou

repo: MALSAR

save_path: github-repos/MATLAB/jiayuzhou-MALSAR


text:
function hf=anim8(varargin)

%% Parse input

switch nargin
    case 2
        hf=varargin{1};
        animStruct=varargin{2};
end

%% Visualisation settings

% fontColor='w';
fontSize=15;
% cMap=gjet(250);

scrollBarWidth=50;

%% Defining slider

animTime=animStruct.Time(:);

minT=1;
maxT=numel(animTime);
w=maxT-minT;
sliceIndexI=1; %Initial index
tickSizeMajor_I=ceil(w/20);

%% Initialize display

figure(hf); drawnow;

%Initialize slider
jSlider = javax.swing.JSlider(minT,maxT);
javacomponent(jSlider,[0,0,round(hf.Position(3)),scrollBarWidth]);
set(jSlider, 'MajorTickSpacing',tickSizeMajor_I, 'MinorTickSpacing',1, 'PaintTicks',true, 'PaintLabels',true,...
    'Background',java.awt.Color.white, 'snapToTicks',true, 'StateChangedCallback',{@updateViewFunc,{hf,jSlider}},'Orientation',jSlider.HORIZONTAL);

%% Set resize function

set(hf,'ResizeFcn',{@setScrollSizeFunc,{hf,scrollBarWidth,jSlider}});

%% Initialize figure callbacks

set(hf,'KeyPressFcn', {@figKeyPressFunc,{hf}});%'WindowButtonDownFcn', {@figMouseDown,{hf}},'WindowButtonUpFcn', {@mouseup,hf});

%% Initialise buttons

filePath=mfilename('fullpath');
toolboxPath=fileparts(fileparts(filePath));
iconPath=fullfile(toolboxPath,'icons');

% hb = findall(hf,'Type','uitoolbar');
hb = uitoolbar(hf);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Help button

%get icon
D=importdata(fullfile(iconPath,'help.jpg'));
S=double(D);
S=S-min(S(:));
S=S./max(S(:));
S(S==1)=NaN;
if size(S,3)==1
    S=repmat(S,[1 1 3]);
end
% Create a uipushtool in the toolbar
uipushtool(hb,'TooltipString','Help','CData',S,'Tag','help_button','ClickedCallback',@helpFunc,'Separator','on');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Play button

%get icon 1
D=importdata(fullfile(iconPath,'play.jpg'));
S=double(D);
S=S-min(S(:));
S=S./max(S(:));
S(S==1)=NaN;
if size(S,3)==1
    S=repmat(S,[1 1 3]);
end
iconPlay=S;

%get icon 2
D=importdata(fullfile(iconPath,'stop.jpg'));
S=double(D);
S=S-min(S(:));
S=S./max(S(:));
S(S==1)=NaN;
if size(S,3)==1
    S=repmat(S,[1 1 3]);
end
iconStop=S;

% Create a uitoggletool in the toolbar
hPlay=uitoggletool(hb,'TooltipString','Play','CData',iconPlay,'Tag','play_button','ClickedCallback',{@playFunc,{hf}});

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Time button

%get icon
D=importdata(fullfile(iconPath,'time.jpg'));
S=double(D);
S=S-min(S(:));
S=S./max(S(:));
S(S==1)=NaN;
if size(S,3)==1
    S=repmat(S,[1 1 3]);
end
% Create a uipushtool in the toolbar
uipushtool(hb,'TooltipString','Time','CData',S,'Tag','time_button','ClickedCallback',{@timeFunc,{hf}}); %,'Separator','on'

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Cycle button

%get icon
D=importdata(fullfile(iconPath,'cycle.jpg'));
S=double(D);
S=S-min(S(:));
S=S./max(S(:));
S(S==1)=NaN;
if size(S,3)==1
    S=repmat(S,[1 1 3]);
end
% Create a uitoggletool in the toolbar
hCycle=uitoggletool(hb,'TooltipString','Cycle forward-backward','CData',S,'Tag','cycle_button');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Save animation button

%get icon
D=importdata(fullfile(iconPath,'saveAnimation.jpg'));
S=double(D);
S=S-min(S(:));
S=S./max(S(:));
S(S==1)=NaN;
if size(S,3)==1
    S=repmat(S,[1 1 3]);
end
% Create a uipushtool in the toolbar
uipushtool(hb,'TooltipString','Save .gif animation','CData',S,'Tag','saveAnimation_button','ClickedCallback',{@saveAnimationFunc,{hf}}); %,'Separator','on'

%% Text fields

% title(sprintf('%6.16e ',T),'FontSize',hf.UserData.anim8.fontSize);
% title(sprintf('%f',T),'FontSize',hf.UserData.anim8.fontSize);

hTextTime = uicontrol(hf,'Style','text',...
    'String',[' Time: ',sprintf('%f',animTime(1))],...
    'Position',[0 scrollBarWidth round(hf.Position(3)) round(scrollBarWidth/2)],'BackgroundColor',[1 1 1],'HorizontalAlignment','Left'); %hf.Color

%% Set figure UserData

hf.UserData.anim8.sliderHandles={jSlider};
% hf.UserData.anim8.ButtonHandles.Sample=hSample;
hf.UserData.anim8.animStruct=animStruct;
hf.UserData.anim8.fontSize=fontSize;
% animHandles=animStruct.Handles; %Handles of objects to animate
% animProps=animStruct.Props; %Properties of objects to animate
% animSets=animStruct.Set; %Property values for to set in order to animate
% animTime=animStruct.Time;
hf.UserData.anim8.playDir=1;
hf.UserData.anim8.ButtonHandles.Play=hPlay;
hf.UserData.anim8.ButtonHandles.hCycle=hCycle;
hf.UserData.anim8.ButtonHandles.hTextTime=hTextTime;
hf.UserData.anim8.pauseTime=3/numel(animStruct.Time);%mean(diff(animStruct.Time));
hf.UserData.anim8.shiftMag=1;%ceil(numel(animStruct.Time)/20);
hf.UserData.anim8.icons.play=iconPlay;
hf.UserData.anim8.icons.stop=iconStop;

% Store current settings
hf.UserData.anim8.WindowButtonDownFcn=hf.WindowButtonDownFcn;
hf.UserData.anim8.WindowButtonUpFcn=hf.WindowButtonUpFcn;
hf.UserData.anim8.KeyPressFcn=hf.KeyPressFcn;
hf.UserData.anim8.WindowScrollWheelFcn=hf.WindowScrollWheelFcn;
hf.UserData.anim8.BusyAction=hf.BusyAction;

%Export figure widget settings
hf.UserData.efw.defaultPath=fullfile(cd,'efw');
hf.UserData.efw.imName=['figure',num2str(get(hf,'Number'))];
hf.UserData.efw.imExt='png';
hf.UserData.efw.imRes='50';
hf.UserData.efw.exportFigOpt='-nocrop';
hf.UserData.efw.exportGifOpt='1';

%% Initialize slider locations
set(jSlider,'Value',sliceIndexI);

%%
drawnow;
end

%% Scroll bar resizing

function setScrollSizeFunc(~,~,inputCell)
hf=inputCell{1};
scrollBarWidth=inputCell{2};

jSlider=inputCell{3};
javacomponent(jSlider,[0,0,round(hf.Position(3)), scrollBarWidth]);

set(hf.UserData.anim8.ButtonHandles.hTextTime,'Position',[0 scrollBarWidth round(hf.Position(3)) round(scrollBarWidth/2)]);
end

%% Help

function helpFunc(~,~)

msgText={'* Play button or press the space bar -> Start animation',...
    '* Stop button or press the space bar -> Stop animation',...
    '* Time button -> Change time stepping settings',...
    '* Cycle button -> Toggle forward / forward-backward mode',...
    '* Save button -> Export snap shorts (e.g. jpg) and animated .gif files',...
    '* Press the v key to activate the view control widget (vcw), note that vcw changes key press functions until vcw is deactivated',...
    };
helpdlg(msgText,'Help information');

end

%% play

function playFunc(~,~,inputCell)
hf=inputCell{1};
shiftMag=hf.UserData.anim8.shiftMag;

set(hf.UserData.anim8.ButtonHandles.Play,'CData',hf.UserData.anim8.icons.stop,'TooltipString','Stop');

while strcmp(get(hf.UserData.anim8.ButtonHandles.Play,'State'),'on')
    tic
    if strcmp(get(hf.UserData.anim8.ButtonHandles.hCycle,'State'),'on')

        jSlider=hf.UserData.anim8.sliderHandles{1};

        sliderValue=get(jSlider,'Value');
        sliderValueNew=sliderValue+(shiftMag*hf.UserData.anim8.playDir);

        sliderMax=get(jSlider,'Maximum');
        sliderMin=get(jSlider,'Minimum');

        if sliderValueNew<sliderMin
            hf.UserData.anim8.playDir=hf.UserData.anim8.playDir*-1;
            sliderValueNew=sliderValue+(shiftMag*hf.UserData.anim8.playDir);
        elseif sliderValueNew>sliderMax
            hf.UserData.anim8.playDir=hf.UserData.anim8.playDir*-1;
            sliderValueNew=sliderValue+(shiftMag*hf.UserData.anim8.playDir);
        end

        set(jSlider,'Value',sliderValueNew);

    else
        shiftSlider(hf.UserData.anim8.sliderHandles{1},shiftMag);
    end

    drawnow;

    t=toc;
    if (hf.UserData.anim8.pauseTime-t)>0
        pause(hf.UserData.anim8.pauseTime-t);
    end
end

set(hf.UserData.anim8.ButtonHandles.Play,'CData',hf.UserData.anim8.icons.play,'TooltipString','Play');

end

%% Time
function timeFunc(~,~,inputCell)
hf=inputCell{1};

prompt = {'Enter pause time:','Enter step size:'};
dlg_title = 'Time stepping settings';
defaultOptions = {num2str(hf.UserData.anim8.pauseTime),num2str(hf.UserData.anim8.shiftMag)};
s=40+max([cellfun(@numel,prompt) cellfun(@numel,defaultOptions)]);
Q = inputdlg(prompt,dlg_title,[1 s],defaultOptions);
if ~isempty(Q)
    if ~isempty(Q{1})
        hf.UserData.anim8.pauseTime=str2double(Q{1});
    end
    if ~isempty(Q{2})
        hf.UserData.anim8.shiftMag=str2double(Q{2});
    end
end

end

%% Save Animation

function saveAnimationFunc(~,~,inputCell)
hf=inputCell{1};
jSlider=hf.UserData.anim8.sliderHandles{1};

%%

defStruct=hf.UserData.efw;
prompt = {'Save path (leave empty to browse to desired folder instead):',...
    'Image name:','Image extension (i.e. png, jpg, bmp, or tif):',...
    'Image resolution (e.g. 120):',...
    'Extra export_fig options (comma seperated, no spaces e.g. -nocrop,-transparent,-painters):',...
    'Export gif option'};
dlg_title = 'Export Gif Widget (see: help efw and help export_fig)';
defaultOptions = {defStruct.defaultPath,defStruct.imName,defStruct.imExt,defStruct.imRes,defStruct.exportFigOpt,hf.UserData.efw.exportGifOpt};

s=25+max([cellfun(@numel,prompt) cellfun(@numel,defaultOptions)]);

Q = inputdlg(prompt,dlg_title,[1 s],defaultOptions);

if ~isempty(Q)
    if isempty(Q{1})
        Q{1}=uigetdir(defStruct.defaultPath,'Select save path');
        if Q{1}==0
            return;
        end
    end

    if isempty(Q{2})
        error('Empty input. Please enter a file name');
    end

    if ~exist(Q{1},'dir') %create output folder if it does not exist already
        mkdir(Q{1});
    end

    if isempty(Q{3})
        warning('Empty input. No image format specified, using jpg files.');
        Q{3}='jpg';
    end

    fileName=fullfile(Q{1},Q{2});
    exportGifCell{1,1}=fileName;

    stringSet=Q{3}; %The image extension
    stringNoSpaces=regexprep(stringSet,'[^\w'']',''); %Remove potential extra spaces

    if ~strcmp(stringNoSpaces(1),'-') %If first character is not '-'
        stringNoSpaces=['-',stringNoSpaces]; %Add '-' to start, e.g. 'jpg' becomes '-jpg'
    end

    %Check format validaty and keep if valid
    if any(strcmp(stringNoSpaces,{'-png','-jpg','-tiff','-bmp'}))
        exportGifCell{1,end+1}=stringNoSpaces; %Add to input list
    else
        error('Wrong image format requested');
    end

    figRes=['-r',Q{4}];
    exportGifCell{1,end+1}=figRes;

    if ~isempty(Q{5})
        stringSet=Q{5}; %The set of potentially multiple options
        stringSetSep = strsplit(stringSet,',');
        for q=1:1:numel(stringSetSep)
            stringNoSpaces=regexprep(stringSetSep{q},'[^\w'']',''); %Remove potential extra spaces
            if ~strcmp(stringNoSpaces(1),'-') %If first character is not '-'
                stringNoSpaces=['-',stringNoSpaces]; %Add '-' to start, e.g. 'jpg' becomes '-jpg'
            end
            exportGifCell{1,end+1}=stringNoSpaces; %Add to input list
        end
    end

    if ~isempty(Q{6})
        exportGifOpt=Q{6};
    end

    fileNameGif=exportGifCell{1,1};
    exportGifCellSub=exportGifCell;

    c=1;
    stepRange=1:hf.UserData.anim8.shiftMag:numel(hf.UserData.anim8.animStruct.Time);
    for q=stepRange
        set(jSlider,'Value',q);
        fileNameNow=[fileNameGif,'_',num2str(q)];
        exportGifCellSub{1,1}=fileNameNow;
        figure(hf);
        export_fig(exportGifCellSub{:});
        gifStruct.FileNames{c}=[fileNameNow,'.',exportGifCell{1,2}(2:end)];
        c=c+1;
    end

    if strcmp(exportGifOpt,'1')
        %Add reverse path
        if strcmp(get(hf.UserData.anim8.ButtonHandles.hCycle,'State'),'on')
            numFiles=numel(gifStruct.FileNames);
            if numFiles>2
                for q=(numFiles-1):-1:2
                    gifStruct.FileNames{end+1}=gifStruct.FileNames{q};
                end
            end
        end

        gifStruct.DelayTime=hf.UserData.anim8.pauseTime;
        gifStruct.FileNameGif=fileNameGif;

        exportGif(gifStruct);
    end

    %Override defaults
    defStruct.defaultPath=Q{1};
    defStruct.imName=Q{2};
    defStruct.imExt=Q{3};
    defStruct.imRes=Q{4};
    defStruct.exportFigOpt=Q{5};
    defStruct.efw.exportGifOpt=Q{6};

    hf.UserData.efw=defStruct;

end

end

%% Figure key press

function figKeyPressFunc(~,eventData,inputCell)

hf=inputCell{1}; %Figure handle

% step = 1;
% if ismember('shift', eventData.Modifier)
%     step = -step; %Make negative while shift is down
% end
%
% if ismember('control', eventData.Modifier)
%     step = step * 4; %Increase speed
% end

% Key input options
switch eventData.Key
    case {'leftarrow','downarrow'}
        shiftSlider(hf.UserData.anim8.sliderHandles{1},-1*hf.UserData.anim8.shiftMag);
    case {'rightarrow','uparrow'}
        shiftSlider(hf.UserData.anim8.sliderHandles{1},1*hf.UserData.anim8.shiftMag);
    case 'v' % Activate vcw
        set(hf.UserData.cFigure.Handles.vcw,'State','On');
    case'space'
        if strcmp(get(hf.UserData.anim8.ButtonHandles.Play,'State'),'off')
            set(hf.UserData.anim8.ButtonHandles.Play,'State','on');
            playFunc([],[],{hf});
        else
            set(hf.UserData.anim8.ButtonHandles.Play,'State','off');
        end
end

end

%% updateViewFunc

function updateViewFunc(~,~,inputCell)

hf=inputCell{1};
jSlider=inputCell{2};
animStruct=hf.UserData.anim8.animStruct;

sliderValue=get(jSlider,'Value');

T=animStruct.Time(sliderValue);
H=animStruct.Handles{sliderValue};%e.g. [hp,hp]; %Handles of objects to animate
P=animStruct.Props{sliderValue};% e.g. {'FaceColor','Vertices'}; %Properties of objects to animate
S=animStruct.Set{sliderValue};%e.g.{c(q,:),V}; %Property values for to set in order to animate

set(hf.UserData.anim8.ButtonHandles.hTextTime,'String',[' Time: ',sprintf('%f',T)],'FontSize',hf.UserData.anim8.fontSize);

for q=1:1:numel(H)
    h=H(q); % Current graphics handle
    p=P{q}; % Current graphics property
    s=S{q}; % Current property setting
    h.(p)=s;% Setting the property
end

end

%% Shift slider

function shiftSlider(jSlider,shiftMag)

sliderValue=get(jSlider,'Value');
sliderValueNew=sliderValue+shiftMag;

sliderMax=get(jSlider,'Maximum');
sliderMin=get(jSlider,'Minimum');

if sliderValueNew<sliderMin
    set(jSlider,'Value',sliderMax);
elseif sliderValueNew>sliderMax
    set(jSlider,'Value',1);
else
    set(jSlider,'Value',sliderValueNew);
end

end

%%
% _*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) 2017  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: MultiDIC

repo: MultiDIC

save_path: github-repos/MATLAB/MultiDIC-MultiDIC


text:
function f=lorenz_ext(t,X)
%
%  Lorenz equation
%
%               dx/dt = SIGMA*(y - x)
%               dy/dt = R*x - y -x*z
%               dz/dt= x*y - BETA*z
%
%        In demo run SIGMA = 10, R = 28, BETA = 8/3
%        Initial conditions: x(0) = 0, y(0) = 1, z(0) = 0;
%        Reference values for t=10 000 :
%              L_1 = 0.9022, L_2 = 0.0003, LE3 = -14.5691
%
%        See:
%    K. Ramasubramanian, M.S. Sriram, "A comparative study of computation
%    of Lyapunov spectra with different algorithms", Physica D 139 (2000) 72-86.
%
% --------------------------------------------------------------------
% Copyright (C) 2004, Govorukhin V.N.

% Values of parameters
SIGMA = 10;
R = 28;
BETA = 8/3;

x=X(1); y=X(2); z=X(3);

Y= [X(4), X(7), X(10);
    X(5), X(8), X(11);
    X(6), X(9), X(12)];

f=zeros(9,1);

%Lorenz equation
f(1)=SIGMA*(y-x);
f(2)=-x*z+R*x-y;
f(3)=x*y-BETA*z;

%Linearized system

 Jac=[-SIGMA, SIGMA,     0;
         R-z,    -1,    -x;
           y,     x, -BETA];

%Variational equation
f(4:12)=Jac*Y;

%Output data must be a column vector

author: Sable

repo: mcbench-benchmarks


text:
function w = Lambert_W(x,branch)
% Lambert_W  Functional inverse of x = w*exp(w).
% w = Lambert_W(x), same as Lambert_W(x,0)
% w = Lambert_W(x,0)  Primary or upper branch, W_0(x)
% w = Lambert_W(x,-1)  Lower branch, W_{-1}(x)
%
% See: http://blogs.mathworks.com/cleve/2013/09/02/the-lambert-w-function/

% Copyright 2013 The MathWorks, Inc.

% Effective starting guess
if nargin < 2 || branch ~= -1
   w = ones(size(x));  % Start above -1
else
   w = -2*ones(size(x));  % Start below -1
end
v = inf*w;

% Haley's method
while any(abs(w - v)./abs(w) > 1.e-8)
   v = w;
   e = exp(w);
   f = w.*e - x;  % Iterate to make this quantity zero
   w = w - f./((e.*(w+1) - (w+2).*f./(2*w+2)));
end


text:
function display(X)
%DISPLAY   Display information about a CHEBFUN2.
%   DISPLAY(F) outputs important information about the CHEBFUN2 F to the command
%   window, including its domain of definition, length (number of pivots used to
%   represent it), and a summary of its structure.
%
%   It is called automatically when the semicolon is not used at the end of a
%   statement that results in a CHEBFUN2.
%
% See also DISP.

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

if ( isequal(get(0, 'FormatSpacing'), 'compact') )
	disp([inputname(1), ' =']);
	disp(X);
else
	disp(' ');
	disp([inputname(1), ' =']);
	disp(' ');
    disp(X);
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function [subTSeries, subTrials] = er_dataSubset(mv, runs);
% Grab time series and trials (event-related design) data for the
% selected runs only from the mv struct.
%
% [subTSeries, subTrials] = er_dataSubset(mv, runs);
%
% ras, 06/30/08. Originally written circa 2005, but I found it generally
% useful and broke it off from mv_amps.
allRuns = unique(mv.trials.run);

% Part 1: Need to find rows in tSeries
% corresponding to the selected runs:
%
tr = mv.params.framePeriod;
nConds = sum(mv.trials.condNums>0);
nFrames = size(mv.tSeries,1);

% first construct an index, for each frame of the tSeries,
% of the run that frame came from:
runIndex = zeros(1,nFrames);

firstTrials = find(nVals(mv.trials.run)==1);
firstFrames = mv.trials.onsetFrames(firstTrials);
runIndex(firstFrames) = mv.trials.run(firstTrials);

% fill in each unassigned entry in the index
% with the current run (given in the previous entry):
% NOTE: possible bug below: runIndex(I) = runIndex(I-1);
% this works if all runs have the same # of frames, but if
% using some short runs, may overwrite prev runs. Need to
% subsample I to find runIndex(I)==0. I'm waiting to
% correct this until I get time to thoroughly check it.
I = intersect(firstFrames+1,1:nFrames); % restrict to max # frames
while any(runIndex(I)==0)
    runIndex(I) = runIndex(I-1);
    I = intersect(I+1, 1:nFrames);
end

% now grab the appropriate rows from the tSeries:
ind = find(ismember(runIndex, runs));
subTSeries = mv.tSeries(ind,:);

% part 2: get event onset/condition data
% for selected runs in subTrials struct:
%
subTrials = mv.trials;
if ~isequal(runs,allRuns)
    % subTrials needs to reflect only selected runs,
    % (tricky):

    % First, find the # of frames in each run:
    lastTrials = [firstTrials(2:end)-1 length(mv.trials.onsetFrames)];
    lastTrialFrames = mv.trials.onsetFrames(lastTrials);
    framesPerRun = [lastTrialFrames(1) diff(lastTrialFrames)];

    % Next, select event data only for selected subsets:
    ok = find(ismember(subTrials.run,runs));
    subTrials.onsetSecs = subTrials.onsetSecs(ok);
    subTrials.onsetFrames = subTrials.onsetFrames(ok);
    subTrials.cond = subTrials.cond(ok);
    subTrials.label = subTrials.label(ok);
    subTrials.run = subTrials.run(ok);
    subTrials.parfiles = subTrials.parfiles(runs);

    % Lastly, correct the onset information: since onsets
    % are counted cumulatively, they will reflect
    % non-selected runs. Correct for this overcounting:
    skippedRuns = setdiff(allRuns,runs);
    for j = skippedRuns
        offset = framesPerRun(j);
        laterRuns = find(subTrials.run>j);
        subTrials.onsetFrames(laterRuns) = ...
            subTrials.onsetFrames(laterRuns) - offset;
        subTrials.onsetSecs(laterRuns) = ...
            subTrials.onsetSecs(laterRuns) - offset*tr;
    end
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function planC = clearCache(planC, doseNum)
%
% 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/>.

    indexS = planC{end};
    planC{indexS.dose}(doseNum).cachedColor = [];
    planC{indexS.dose}(doseNum).cachedTime = [];
    planC{indexS.dose}(doseNum).numCachedSlices = 0;

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function [success] = modelAddOutsideDependencies(dependencyName,varargin)
	% Used to request certain outside dependencies from users.
	% Biafra Ahanonu
	% started: 2017.11.16 [16:50:28]
	% inputs
		%
	% outputs
		%

	% changelog
		% 2019.10.15 [12:29:30] - Added flag to prevent recursive loop between resetMiji and modelAddOutsideDependencies.
		% 2021.02.01 [??15:19:40] - Update `_external_programs` to call ciapkg.getDirExternalPrograms() to standardize call across all functions.
		% 2021.06.20 [00:20:12] - Updated to add support for ImageJ call instead of Fiji.
		% 2021.08.08 [19:30:20] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
		% 2021.12.26 [09:10:55] - No longer use Fiji-based Miji.
	% TODO
		%

	import ciapkg.api.* % import CIAtah functions in ciapkg package API.

	%========================
	options.exampleOption = '';
	options.defaultExternalProgramDir = ciapkg.getDirExternalPrograms();
	options.recursionExit = 0;
	% get options
	options = getOptions(options,varargin);
	% display(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	% 	eval([fn{i} '=options.' fn{i} ';']);
	% end
	%========================

	try
		success = 0;
		switch dependencyName
			case 'miji'
				if exist('MIJ','class')==8
					disp('Miji loaded!')
					return;
				else
					manageMiji('startStop','setupImageJ');
					if exist('MIJ','class')==8
						disp('Miji loaded!')
						return;
					end
                end

                % No longer use Fiji-based Miji.
                return;

				if exist('Miji.m','file')==2
					display(['Miji located in: ' which('Miji.m')]);
					% Miji is loaded, continue
				elseif ~isempty(java.lang.System.getProperty('plugins.dir'))&options.recursionExit==0
					disp('Miji JAR files already loaded, skipping. If Miji issue, use "resetMiji".')
				else
					% pathToMiji = inputdlg('Enter path to Miji.m in Fiji (e.g. \Fiji.app\scripts):',...
					%              'Miji path', [1 100]);
					% pathToMiji = pathToMiji{1};
					% display('Dialog box: Enter path to Miji.m in Fiji (likely in "scripts" folder, e.g. \Fiji.app\scripts)')
					fijiList = getFileList(options.defaultExternalProgramDir,'(Fiji.app|fiji-.*-20151222(?!.zip|.dmg))');
					if ~isempty(fijiList)
						if ismac
							checkMijiPath = [fijiList{1} filesep 'scripts'];
						elseif isunix
							checkMijiPath = [fijiList{1} filesep 'Fiji.app' filesep 'scripts'];
						elseif ispc
							checkMijiPath = [fijiList{1} filesep 'Fiji.app' filesep 'scripts'];
						else
							checkMijiPath = [fijiList{1} filesep 'Fiji.app' filesep 'scripts'];
						end
						% checkMijiPath = [options.defaultExternalProgramDir filesep 'Fiji.app' filesep 'scripts'];
						if exist(checkMijiPath,'dir')==7
							fprintf('AUTOMATICALLY adding Miji path: %s\n',checkMijiPath);
							pathToMiji = checkMijiPath;
						end
					end
					if exist('pathToMiji','var')==0
						if exist(options.defaultExternalProgramDir,'dir')==7
							loadPathHere = options.defaultExternalProgramDir;
							loadStr = ['Enter path to Miji.m in Fiji (likely in "scripts" folder, e.g. ' filesep ciapkg.pkgName options.defaultExternalProgramDir '\Fiji.app\scripts)'];
						else
							loadPathHere = '\.';
							loadStr = ['Enter path to Miji.m in Fiji (likely in "scripts" folder, e.g. \Fiji.app\scripts)'];
						end
						disp(['Dialog box: ' loadStr])
						pathToMiji = uigetdir(loadPathHere,loadStr);
					end
					if ischar(pathToMiji)
						privateLoadBatchFxnsPath = 'private\settings\privateLoadBatchFxns.m';
						if exist(privateLoadBatchFxnsPath,'file')~=0
							fid = fopen(privateLoadBatchFxnsPath,'at')
							fprintf(fid, '\npathtoMiji = ''%s'';\n', pathToMiji);
							fclose(fid);
						end
						addpath(pathToMiji);
					end

					if options.recursionExit==1
						return;
					end

					% % If MIJ class not loaded, load Miji.m.
					% if exist('MIJ')~=8
					% 	% Load Miji so paths added to javaclasspath('-dynamic')
					% 	currP=pwd;Miji;cd(currP);
					% 	MIJ.exit;
					% end

					% % First attempt to open Miji
					% try
					% 	MIJ.start;
					% catch err
					% 	disp(repmat('@',1,7))
					% 	disp(getReport(err,'extended','hyperlinks','on'));
					% 	disp(repmat('@',1,7))

					% 	disp('Reset Java class path and Miji then try again');
					% 	resetMiji

					% 	% Try again after resetting Miji.
					% 	try
					% 		MIJ.start;
					% 	catch err
					% 		disp(repmat('@',1,7))
					% 		disp('Apparently Miji hates your computer, sorry!')
					% 		disp(getReport(err,'extended','hyperlinks','on'));
					% 		disp(repmat('@',1,7))
					% 	end
					% end

					% Get Miji properly loaded in the path
					resetMiji;

					% % Load Miji so paths added to javaclasspath('-dynamic')
					% currP=pwd;Miji;cd(currP);
					% MIJ.exit;
				end
			otherwise
				display('Incorrect option input.')
				% do nothing
		end
	catch err
		display(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		display(repmat('@',1,7))
	end
end

author: bahanonu

repo: ciatah

save_path: github-repos/MATLAB/bahanonu-ciatah


text:
function cos_deg_test ( )

%*****************************************************************************80
%
%% COS_DEG_TEST tests R4_COS_DEG and R8_COS_DEG.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 September 2011
%
%  Author:
%
%    John Burkardt
%
  addpath ( '../test_values' );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'COS_DEG_TEST:\n' );
  fprintf ( 1, '  Test COS_DEGREE_VALUES, R4_COS_DEG, R8_COS_DEG.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '             X     COS_DEG(X)\n' );
  fprintf ( 1, '                R4_COS_DEG(X)         Diff\n' );
  fprintf ( 1, '                R8_COS_DEG(X)         Diff\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, x, fx1 ] = cos_degree_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fx2 = r4_cos_deg ( single ( x ) );
    fx3 = r8_cos_deg ( x );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  %14.4f  %14.6g\n', x, fx1 );
    fprintf ( 1, '                  %14.6g  %14.6g\n', fx2, abs ( fx1 - fx2 ) );
    fprintf ( 1, '                  %14.6g  %14.6g\n', fx3, abs ( fx1 - fx3 ) );

  end

  rmpath ( '../test_values' );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [ graph ] = bidirectional_graph()

ends = neighbour_joint_list();
starts = 1:length(ends);

graph = [starts, ends; ...
         ends,   starts];
graph = graph';
end

author: eldar

repo: deepcut

save_path: github-repos/MATLAB/eldar-deepcut


text:
function event = read_serial_event(filename)

% READ_SERIAL_EVENT
%
% changed A.Hadjipapas 2010
%
% The only thing transmitted is the event.value (no info about sample) but it works

% Copyright (C) 2007, Christian Hesse
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

%% serial port on windows or linux platform
[port, opt] = filetype_check_uri(filename);
% determine whether any serial port objects are already associated with the
% target serial port
temp = instrfind;
if isempty(temp)||~any(strcmpi(temp.Port,port))
  s=serial(port);
  s.Baudrate =str2double(opt{2});
  fopen(s);
end

%% try to read a message from the serial port
if ~isempty(s.BytesAvailable) && s.BytesAvailable~=0
  %% NOTE: Here I only use fread,which delivers numerical outputs. I
  %% then check whether the message is longer than 3 and if it is
  %% I assume it was a string to begin with and then deocde it
  %% back to char
  msg = fread(s,s.BytesAvailable);
  if length(msg)>3

    msg=char(msg');
    event.type='char';
  else
    event.type='uint';
  end
  %% The only thing transmitted is the event.value
  event.value=msg;
  %% FIX THIS: here sample is always at a fixed value (i.e true sample (e.g. write_event) is not
  %% transmitted)
  event.sample=1;
  event.duration=[];
end

%% this is the old code
%
%     % serial port on windows or linux platform
%     [port, opt] = filetype_check_uri(filename);
%     % determine whether any serial port objects are already associated with the
%     % target serial port
%     s = [];
%     temp = instrfind;
%     if isa(temp,'instrument')
%       % find all serial ports
%       i1 = strcmpi({temp(:).Type},'serial');
%       if any(i1)
%         % find all serial ports whose name matches that of the specified port
%         i2 = strmatch(lower(port),lower({temp(find(i1)).Name}));
%         % set s to the (first) matching port if present (and open if necessary)
%         if ~isempty(i2)
%           s = temp(i2(1));
%           if ~strcmp(s.Status,'open'), fopen(s); end
%         end
%       end
%     end
%     % create, configure a serial port object if necessary and open the port
%     if ~isa(s,'serial')
%       s = serial(port);
%       if ~isempty(opt) && iscell(opt), s = set(s,opt); end
%       fopen(s);
%     end
%     % try to read a message from the serial port
%     msg = [];
%     % FIXME: this currently assumes that all messages are terminated by the
%     % "newline" character (ascii character 10)
%     try
%       msg = fscanf(s,'%s\n');
%     end
%     % convert message to event structure
%     event = msg2struct(msg);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [x,g,j,gg] = kmeans(d,k,x0,l)
%KMEANS Vector quantisation using K-means algorithm [X,ESQ,J]=(D,K,X0,L)
%
%  Inputs:
%
%    D(N,P)  contains N data vectors of dimension P
%    K       is number of centres required
%    X0(K,P) are the initial centres (optional)
%
%      or alternatively
%
%    X0      gives the initialization method
%            'f'   pick K random elements of D as the initial centres [default]
%            'p'   randomly divide D into K sets and choose the centroids
%    L       gives max number of iterations (use 0 if you just want to calculate G and J)
%
%  Outputs:
%
%    X(K,P)  is output row vectors (omitted if L=0)
%    G       is mean square error
%    J(N)    indicates which centre each data vector belongs to
%    GG(L)   gives the mean square error at the start of each iteration (omitted if L=0)
%
% It is often a good idea to scale the input data so that it has equal variance in each
% dimension before calling KMEANS.

%  Originally based on a routine by Chuck Anderson, anderson@cs.colostate.edu, 1996

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

memsize=voicebox('memsize');
[n,p] = size(d);
nb=min(n,max(1,floor(memsize/(8*p*k))));    % block size for testing data points
nl=ceil(n/nb);                  % number of blocks
if nargin<4
    l=300;                  % very large max iteration count
    if nargin<3
        x0='f';             % use 'f' initialization mode
    end
end
if ischar(x0)
    if k<n
        if any(x0)=='p'                  % Initialize using a random partition
            ix=ceil(rand(1,n)*k);       % allocate to random clusters
            ix(rnsubset(k,n))=1:k;      % but force at least one point per cluster
            x=zeros(k,p);
            for i=1:k
                x(i,:)=mean(d(ix==i,:),1);
            end
        else                                % Forgy initialization: choose k random points [default]
            x=d(rnsubset(k,n),:);         % sample k centres without replacement
        end
    else
        x=d(mod((1:k)-1,n)+1,:);    % just include all points several times
    end
else
    x=x0;
end
m=zeros(n,1);           % minimum distance to a centre
j=zeros(n,1);           % index of closest centre
gg=zeros(l,1);
wp=ones(1,p);
kk=1:p;
kk=kk(ones(n,1),:);
kk=kk(:);

if l>0
    for ll=1:l                 % loop until x==y causes a break

        % find closest centre to each data point [m(:),j(:)] = distance, index

        ix=1;
        jx=n-nl*nb;
        for il=1:nl
            jx=jx+nb;        % increment upper limit
            ii=ix:jx;
            z = disteusq(d(ii,:),x,'x');
            [m(ii),j(ii)] = min(z,[],2);
            ix=jx+1;
        end
        y = x;              % save old centre list

        % calculate new centres as the mean of their assigned data values (or zero for unused centres)

        nd=full(sparse(j,1,1,k,1));         % number of points allocated to each centre
        md=max(nd,1);                       % remove zeros
        jj=j(:,wp);
        x=full(sparse(jj(:),kk,d(:),k,p))./md(:,wp);    % calculate the new means
        fx=find(nd==0);

        % if any centres are unused, assign them to data values that are not exactly on centres
        % choose randomly if there are more such points than needed

        if ~isempty(fx)
            q=find(m~=0);
            if length(q)<=length(fx)
                x(fx(1:length(q)),:)=d(q,:);
            else
                if length(fx)>1
                    [rr,ri]=sort(rand(length(q),1));
                    x(fx,:)=d(q(ri(1:length(fx))),:);
                else
                    x(fx,:) = d(q(ceil(rand(1)*length(q))),:);
                end
            end
        end

        % quit if the centres are unchanged

        gg(ll)=sum(m,1);
        if x==y
            break
        end
    end
    gg=gg(1:ll)/n;
%     ll % *** DEBUG ***
%     gg' % *** DEBUG ***
    g=gg(end);
else            % if l==0 then just calculate G and J (but rename as X and G)
    ix=1;
    jx=n-nl*nb;
    for il=1:nl
        jx=jx+nb;        % increment upper limit
        ii=ix:jx;
        z = disteusq(d(ii,:),x,'x');
        [m(ii),j(ii)] = min(z,[],2);
        ix=jx+1;
    end
    x=sum(m,1)/n;
    g=j;
end

author: covarep

repo: covarep

save_path: github-repos/MATLAB/covarep-covarep


text:
function [skinDetection,faceIm,skinImB_3] = selectFaceTemplateManualHueSaturationSelection(skinDetection, Im)

hueSatMapResolution     = 500;

xyCoor = round([min(skinDetection.bboxPolygon(1:2:end)) min(skinDetection.bboxPolygon(2:2:end)) max(skinDetection.bboxPolygon(1:2:end)) max(skinDetection.bboxPolygon(2:2:end))]);
xyCoor(xyCoor<1) = 1;

if length(size(Im)) == 3
    faceIm = Im(xyCoor(2):xyCoor(4),xyCoor(1):xyCoor(3),:);
else
    faceIm = Im(xyCoor(2):xyCoor(4),xyCoor(1):xyCoor(3));
end

% reset face sectors
faceGridVal = zeros(skinDetection.nFaceSectors,skinDetection.nFaceSectors);
faceGridVal(:) = 1:skinDetection.nFaceSectors^2;

% Divide face region in face sectors and rotate depending on the angle of the face
boxSize         = round(sqrt((skinDetection.bboxPolygon(4)-skinDetection.bboxPolygon(2))^2+(skinDetection.bboxPolygon(3)-skinDetection.bboxPolygon(1))^2))-1;
faceGridVal     = imrotate(imresize(faceGridVal,[boxSize boxSize],'Method','Nearest'),atand((skinDetection.bboxPolygon(4)-skinDetection.bboxPolygon(2))/(skinDetection.bboxPolygon(1)-skinDetection.bboxPolygon(3))));
if size(faceIm,1) > size(faceGridVal,1) | size(faceIm,2) > size(faceGridVal,2)
    if length(size(Im)) == 3
        faceIm      = faceIm(1:size(faceGridVal,1),1:size(faceGridVal,2),:);
    else
        faceIm      = faceIm(1:size(faceGridVal,1),1:size(faceGridVal,2));
    end
    faceGridVal = faceGridVal(1:size(faceIm,1),1:size(faceIm,2));
else
    faceGridVal = faceGridVal(1:size(faceIm,1),1:size(faceIm,2));
end
faceIm = double(faceIm);

if skinDetection.firstTimeDetected==1 & skinDetection.nTimesDetected ==1 ;  % only first time when face is detected

    % Select HSV skin color
    hsvChannels = rgb2hsv(faceIm);
    huemap = hsvChannels(:,:,1);
    satmap = hsvChannels(:,:,2);
    intmap = hsvChannels(:,:,3);

    figure();
    subplot(2,2,1)
    imshow(uint8(faceIm));

    subplot(2,2,2)
    imagesc(huemap);
    colormap('jet')
    colorbar
    axis off

    subplot(2,2,3);
    hist(huemap(:),linspace(0,1,256));
    title('Hue Histogram')

    subplot(2,2,4);
    hist(satmap(:),linspace(0,1,256));
    title('Saturation Histogram')

    R = satmap(:);
    TH = huemap(:)*2*pi;

    % make polar plot of colors in image
    [X,Y] = pol2cart(TH,R);

    imSize = hueSatMapResolution;
    tempHueIm = zeros(imSize,imSize);
    tempSatIm = zeros(imSize,imSize);
    tempIntIm = zeros(imSize,imSize);

    Xn = round(X*(imSize/2-1)+imSize/2+1);
    Yn = round(Y*(imSize/2-1)+imSize/2+1);
    zeroCoor = imSize/2;

    % fill maps
    tempHueIm((Xn-1).*imSize+Yn) = huemap(:);
    tempSatIm((Xn-1).*imSize+Yn) = satmap(:);
    tempIntIm((Xn-1).*imSize+Yn) = intmap(:);

    colorspaceIm = reshape([tempHueIm tempSatIm tempIntIm],size(tempIntIm,1),size(tempIntIm,1),3);
    colorspaceIm = hsv2rgb(colorspaceIm);

    dontstop = 1;
    while dontstop

        figure(999);
        imshow(uint8(colorspaceIm));
        hold on
        plot(zeroCoor,zeroCoor,'go');
        title({'Select the wedge range of skin colors by clicking '; 'the left mouse button at top left and bottom right corner'});
        drawnow;

        pause(1);

        xi = [];
        yi = [];
        for i = 1:2
            [xi(i), yi(i)] = ginput(1);

            % draw selection point
            plot(xi(i),yi(i),'gx');

            % draw red line showing the edges of the wedges
            plot(linspace(zeroCoor,imSize,2),polyval(polyfit([zeroCoor xi(i)],[zeroCoor yi(i)],1),linspace(zeroCoor,imSize,2)),'r')

            drawnow;
        end
        [TH,R] = cart2pol(xi-zeroCoor,yi-zeroCoor);

        for i = 1:2

            % draw green line
            plot(linspace(xi(1),xi(2),2),polyval(polyfit([zeroCoor xi(i)],[zeroCoor yi(i)],1),linspace(xi(1),xi(2),2)),'g')
            [xic,yic] = pol2cart(linspace(TH(1),TH(2),10),zeros(1,10)+R(i));

            plot(xic+zeroCoor,yic+zeroCoor,'g')
        end
        drawnow;
        hold off

        [~,R] = cart2pol((xi-zeroCoor-1)/(imSize/2-1),(yi-zeroCoor-1)/(imSize/2-1));

        % recompute range of skin color hue and saturation values
        TH(TH<=0) = TH(TH<=0)+2*pi;
        TH = TH./(2*pi);

        disp(['Range of selected hue values: ' num2str(TH)]);
        disp(['Range of selected saturation values: ' num2str(R)]);

        if R(1) >= R(2)
            error('Radius of second point should be larger than first point!');
        end

%         skinDetection.skinImB = huemap>TH(1) & satmap>R(1) & satmap<R(2) | huemap<TH(2) & satmap>R(1) & satmap<R(2);

        if TH(1) > TH(2)
            skinDetection.skinImB = huemap>TH(1) & huemap<=1 & satmap>R(1) & satmap<R(2) | huemap<TH(2) & huemap>=0 & satmap>R(1) & satmap<R(2);
        elseif TH(1) < TH(2)
            skinDetection.skinImB = huemap>TH(1) & huemap<TH(2) & satmap>R(1) & satmap<R(2);
        else
            skinDetection.skinImB = satmap>R(1) & satmap<R(2);
        end

        selectIm = faceIm;
        selectIm(reshape(repmat(~skinDetection.skinImB,1,3),size(faceIm,1),size(faceIm,2),3)) = NaN;

        h = figure(998);
        imshow(uint8(selectIm))
        hold on
        text(10,10,['Selected hue range: ' num2str(TH)],'Color','g')
        text(10,40,['Selected saturation range: ' num2str(R)],'Color','g')
        title('Press "A" for accept, press "R" to reject and reselect skin colors');
        drawnow;
        hold off

        keyspressed = [];

        k=0;
        while ~k
            k = waitforbuttonpress;
            currkey = get(gcf,'currentcharacter');
            if strcmp(currkey,'a') | strcmp(currkey,'r')
                k = 1;
            else
                k = 0;
            end
        end

        if strcmp(currkey,'a')
            dontstop = 0;
        else
            close(h);
        end
    end

    skinDetection.TH = TH;
    skinDetection.R = R;

end

if mod(skinDetection.f,skinDetection.calcFrameRate) & skinDetection.calcFrameRate > 1 | skinDetection.calcFrameRate==1

    % Select HSV skin color
    hsvChannels = rgb2hsv(faceIm);
    huemap = hsvChannels(:,:,1);
    satmap = hsvChannels(:,:,2);
    intmap = hsvChannels(:,:,3);

    if skinDetection.TH(1) > skinDetection.TH(2)
        skinDetection.skinImB = huemap>skinDetection.TH(1) & huemap<=1 & satmap>skinDetection.R(1) & satmap<skinDetection.R(2) | huemap<skinDetection.TH(2) & huemap>=0 & satmap>skinDetection.R(1) & satmap<skinDetection.R(2);
    elseif skinDetection.TH(1) < skinDetection.TH(2)
        skinDetection.skinImB = huemap>skinDetection.TH(1) & huemap<skinDetection.TH(2) & satmap>skinDetection.R(1) & satmap<skinDetection.R(2);
    else
        skinDetection.skinImB = satmap>skinDetection.R(1) & satmap<skinDetection.R(2);
    end
end

if size(skinDetection.skinImB,1)~=size(faceGridVal,1) | size(skinDetection.skinImB,2)~=size(faceGridVal,2)
    skinDetection.skinImB = imresize(skinDetection.skinImB,[size(faceGridVal,1) size(faceGridVal,2)]);
end

for gridIdx = 1:skinDetection.nFaceSectors^2 % check which grid sectors have enough skin detected
    if sum(faceGridVal(:)==gridIdx & skinDetection.skinImB(:))/sum(faceGridVal(:)==gridIdx) > skinDetection.fracPixelsPresent;
        skinDetection.skinImB(faceGridVal(:)==gridIdx) = 1;
    else
        skinDetection.skinImB(faceGridVal(:)==gridIdx) = 0;
    end
end

skinImB_3   = repmat(skinDetection.skinImB,1,1,3);

author: marnixnaber

repo: rPPG

save_path: github-repos/MATLAB/marnixnaber-rPPG


text:
% Chapter 15 - Local and Global Bifurcations.
% Programs_15a - Determining the coefficients of the Lyapunov function
% for a Lienard system.
% Copyright Birkhauser 2013. Stephen Lynch.

% V3=[V30;V21;V12;V03], V4=[V40;V31;V22;V13;V04;eta4],
% V5=[V50;V41;V32;V23;V14;V05],V6=[V60;V51;V42;V33;V24;V15;V06;eta6]
% Symbolic Math toolbox required.

% When determining coefficients of V_{4m} set V_{2m,2m}=0.
% When determining coefficients of V_{4m+2} set V_{2m,2m+2}+V_{2m+2,2m}=0.

clear all

syms a1 a2 b2 a3 b3 a4 b4 a5 b5;
A=[3 0 -2 0;0 0 1 0;0 -1 0 0;0 2 0 -3];
B=[b2; 0; a2; 0];

V3=A\B

A=[0 -1 0 0  0 -1;0 3 0 -3 0 -2;0 0 0 1 0 -1;4 0 -2 0 0 0;0 0 2 0 -4 0; 0 0 1 0 0 0];
B=[a3; -2*a2*b2; 0; b3-2*a2^2;0;0];

V4=A\B

A=[5 0 -2 0 0 0;0 0 3 0 -4 0;0 0 0 0 1 0;0 -1 0 0 0 0;0 4 0 -3 0 0;0 0 0 2 0 -5];
B=[b4-10*a2^2*b2/3;0;0;a4-2*a2^3;-2*a2*b3;0];

V5=A\B

A=[6 0 -2 0 0 0 0 0;0 0 4 0 -4 0 0 0;0 0 0 0 2 0 -6 0;0 0 1 0 1 0 0 0;
   0 -1 0 0 0 0 0 -1;0 5 0 -3 0 0 0 -3;0 0 0 3 0 -5 0 -3;0 0 0 0 0 1 0 -1];
B=[b5-6*a2*a4-4*a2^2*b2^2/3+8*a2^4;16*a2^4/3+4*a2^2*b3/3-8*a2*a4/3;0;0;
   a5-8*a2^3*b2/3;-2*a2*b4+8*a2^3*b2+2*a2*b2*b3-4*a4*b2;
   16*a2^3*b2/3+4*a2*b2*b3/3-8*a4*b2/3;0];

V6=A\B

L0=-a1
eta4=V4(6,1);
[n,d]=numden(-3/8*a3+1/4*a2*b2);
L1=n
a3=2*a2*b2;
eta6=V6(8,1);
[n,d]=numden(-5/16*a5+1/8*a2*b4-5/24*a2*b2*b3+5/12*a4*b2);
L2=n

% End of Programs_15a.


text:
classdef (Abstract) nme_branch < mp.nm_element

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

%     properties
%     end

    methods
        function name = name(obj)
            name = 'branch';
        end

        function np = np(obj)
            np = 2;     %% this is a 2 port element
        end
    end     %% methods
end         %% classdef

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function movingcircle
% MOVINGCIRCLE will track the interface defined by x^2+y^2 = (0.5-t)^2
%--------------------------------------------------------------------------
% Copyright (C) 2008 Long Chen. See COPYRIGHT.txt for details.
%--------------------------------------------------------------------------

close all; clear all;
%---------------------- Parameters ----------------------------------------
figure(1); set(gcf,'Units','normal'); set(gcf,'Position',[0,0,0.8,0.4]);
t = 0; dt = 0.075; maxIt = 30;
%---------------------- Initial Grid --------------------------------------
node = [-1 -1; 1 -1; 1 1; -1 1];
elem = [2 3 1; 4 1 3];
N0 = size(elem,1);
for i = 1:5
	[node,elem] = uniformbisect(node,elem);
end
u = -sign(f(node,t));
subplot(1,2,1); showmesh(node,elem); pause(0.1)
subplot(1,2,2);  showsolution(node,elem,u,[0,90]); colorbar;
for k = 1:maxIt
	if (mod(k,4) == 0), t = t + dt; end
	%---------- detect element cross interface or away from interface -----
	eta = abs(sign(f(node(elem(:,1),:),t)) + sign(f(node(elem(:,2),:),t))...
            + sign(f(node(elem(:,3),:),t)));
	refineElem = find(eta < 3);
    coarsenElem = find(eta == 3);
    %---------- refine elements cross the interface -----------------------
    [node,elem] = bisect(node,elem,refineElem);
    u = -sign(f(node,t));
    subplot(1,2,1); showmesh(node,elem); pause(0.025)
    subplot(1,2,2);  showsolution(node,elem,u); view(2); colorbar;
    %---------- coarsen elements away from the interface ------------------
    [node,elem] = coarsen(node,elem,coarsenElem);
    u = -sign(f(node,t));
    subplot(1,2,1);  showmesh(node,elem); pause(0.025)
    subplot(1,2,2);  showsolution(node,elem,u); view(2); colorbar;
end
end
%-------------------- End of MOVINGCIRCLE --------------------------------

%-------------------- Sub functions called by MOVINGCIRCLE ---------------
function z = f(p,t)
z = sum(p.^2,2) - (0.5-t)^2;
end

repo: Aero-matlab


text:
function asSetAllWindows(CW)
global asObjs
for i = 1 : length(asObjs)
    asObjs(i).window.setCW(CW);
end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function class_out = force_membership_wc(f_in, class_in, f_out, par)
% class = function force_membership_wc(f_in, class_in, f_out, par)
% Given classified points, try to classify new points via template matching
%
% f_in:          features of classified points  (# input spikes x n_features)
% class_in:      classification of those points
% f_out:         features of points to be classified (nspk x n_features)
% par        environment variables, of which the following are
%                required:
%                    o par.template_sdnum - max radius of cluster,
%                                                   in std devs.
%                    o par.template_k     - # of nearest neighbors
%                    o par.template_k_min - min # of nn for vote
%                    o par.template_type  - nn, center, ml, mahal

nspk = size(f_out,1);
class_out = zeros(1,size(f_out,1));
switch par.template_type
    case 'nn'
        sdnum = par.template_sdnum;
        k     = par.template_k;
        k_min = par.template_k_min;
        sd    = sqrt(sum(var(f_in,1)))*ones(1,size(f_in,1));
        for i=1:nspk,
            nn = nearest_neighbor(f_out(i,:),f_in,sdnum*sd,Inf*ones(size(f_in)),Inf,k);
            if( nn )
                winner = mode(class_in(nn));
                if nnz(class_in(nn)==winner)<k_min
                    class_out(i) = 0;
                else
                    class_out(i) = winner;
                end
            else
                class_out(i) = 0;
            end
        end

    case 'center'
        [centers, sd, pd] = build_templates(class_in,f_in); % we are going to ignore pd
        sdnum = par.template_sdnum;
        for i=1:nspk,
            class_out(i) = nearest_neighbor(f_out(i,:),centers,sdnum*sd);
        end

    case 'ml'
        [mu inv_sigma] = fit_gaussian(f_in,class_in);
        for i=1:nspk,
            class_out(i) = ML_gaussian(f_out(i,:),mu,inv_sigma);
        end
    case 'mahal'
        classes = unique(class_in);
        mdistance = zeros(length(classes), nspk);
        maxdist   = zeros(1, length(classes));
        for ci = 1:length(classes)
           i = classes(ci);
           mdistance(i,:) = mahal(f_out, f_in(class_in ==i, :));
           maxdist(i) = sqrt(mean(mahal(f_in(class_in ==i, :), f_in(class_in ==i, :))));
        end
        sdnum = par.template_sdnum;
        for i = 1:nspk
             [d winner] = min(mdistance(:,i));
             if sqrt(d) < sdnum*maxdist(winner)
                 class_out(i) = classes(winner);
             end
        end

    otherwise
        sprintf('force_membership(): <%s> is not a known template type.\n',par.template_type);

end

author: csn-le


text:
function mertens_values_test ( )

%*****************************************************************************80
%
%% MERTENS_VALUES demonstrates the use of MERTENS_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 October 2007
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'MERTENS_VALUES:\n' );
  fprintf ( 1, '  MERTENS_VALUES returns values of \n' );
  fprintf ( 1, '  the Mertens function.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     N         MERTENS(N)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, n, fn ] = mertens_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fprintf ( 1, '  %4d  %10d\n', n, fn );

  end

  return
end


text:
classdef BoxPanel < uix.Panel & uix.mixin.Panel
    %uix.BoxPanel  Box panel
    %
    %  p = uix.BoxPanel(p1,v1,p2,v2,...) constructs a box panel and sets
    %  parameter p1 to value v1, etc.
    %
    %  A box panel is a decorated container with a title box, border, and
    %  buttons to dock and undock, minimize, get help, and close.  A box
    %  panel shows one of its contents and hides the others.
    %
    %  See also: uix.Panel, uipanel, uix.CardPanel

    %  Copyright 2009-2016 The MathWorks, Inc.
    %  $Revision: 1599 $ $Date: 2018-04-07 07:15:03 +1000 (Sat, 07 Apr 2018) $

    properties( Dependent )
        TitleColor % title background color [RGB]
        Minimized % minimized [true|false]
        MinimizeFcn % minimize callback
        Docked % docked [true|false]
        DockFcn % dock callback
        HelpFcn % help callback
        CloseRequestFcn % close request callback
    end

    properties( Dependent, SetAccess = private )
        TitleHeight % title panel height [pixels]
    end

    properties( Access = private )
        TitleBox % title bar box
        TitleText % title text label
        EmptyTitle = '' % title when empty, [] otherwise
        TitleAccess = 'public' % 'private' when getting or setting Title, 'public' otherwise
        TitleHeight_ = -1 % cache of title text height (-1 denotes stale cache)
        MinimizeButton % title button
        DockButton % title button
        HelpButton % title button
        CloseButton % title button
        Docked_ = true % backing for Docked
        Minimized_ = false % backing for Minimized
    end

    properties( Constant, Access = private )
        NullTitle = char.empty( [2 0] ) % an obscure empty string, the actual panel Title
        BlankTitle = ' ' % a non-empty blank string, the empty uicontrol String
    end

    properties
        MaximizeTooltipString = 'Expand this panel' % tooltip string
        MinimizeTooltipString = 'Collapse this panel' % tooltip string
        UndockTooltipString = 'Undock this panel' % tooltip string
        DockTooltipString = 'Dock this panel' % tooltip string
        HelpTooltipString = 'Get help on this panel' % tooltip string
        CloseTooltipString = 'Close this panel' % tooltip string
    end

    methods

        function obj = BoxPanel( varargin )
            %uix.BoxPanel  Box panel constructor
            %
            %  p = uix.BoxPanel() constructs a box panel.
            %
            %  p = uix.BoxPanel(p1,v1,p2,v2,...) sets parameter p1 to value
            %  v1, etc.

            % Define default colors
            foregroundColor = [1 1 1];
            backgroundColor = [0.05 0.25 0.5];

            % Set default colors
            obj.ForegroundColor = foregroundColor;

            % Create panels and decorations
            titleBox = uix.HBox( 'Internal', true, 'Parent', obj, ...
                'Units', 'pixels', 'BackgroundColor', backgroundColor );
            titleText = uix.Text( 'Parent', titleBox, ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'String', obj.BlankTitle, 'HorizontalAlignment', 'left' );

            % Create buttons
            minimizeButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'Enable', 'on' );
            dockButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'Enable', 'on' );
            helpButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'String', '?', ...
                'TooltipString', obj.HelpTooltipString, 'Enable', 'on' );
            closeButton = uix.Text( ...
                'ForegroundColor', foregroundColor, ...
                'BackgroundColor', backgroundColor, ...
                'FontWeight', 'bold', 'String', char( 215 ), ...
                'TooltipString', obj.CloseTooltipString, 'Enable', 'on' );

            % Store properties
            obj.Title = obj.NullTitle;
            obj.TitleBox = titleBox;
            obj.TitleText = titleText;
            obj.MinimizeButton = minimizeButton;
            obj.DockButton = dockButton;
            obj.HelpButton = helpButton;
            obj.CloseButton = closeButton;

            % Create listeners
            addlistener( obj, 'BorderWidth', 'PostSet', ...
                @obj.onBorderWidthChanged );
            addlistener( obj, 'BorderType', 'PostSet', ...
                @obj.onBorderTypeChanged );
            addlistener( obj, 'FontAngle', 'PostSet', ...
                @obj.onFontAngleChanged );
            addlistener( obj, 'FontName', 'PostSet', ...
                @obj.onFontNameChanged );
            addlistener( obj, 'FontSize', 'PostSet', ...
                @obj.onFontSizeChanged );
            addlistener( obj, 'FontUnits', 'PostSet', ...
                @obj.onFontUnitsChanged );
            addlistener( obj, 'FontWeight', 'PostSet', ...
                @obj.onFontWeightChanged );
            addlistener( obj, 'ForegroundColor', 'PostSet', ...
                @obj.onForegroundColorChanged );
            addlistener( obj, 'Title', 'PreGet', ...
                @obj.onTitleReturning );
            addlistener( obj, 'Title', 'PostGet', ...
                @obj.onTitleReturned );
            addlistener( obj, 'Title', 'PostSet', ...
                @obj.onTitleChanged );

            % Draw buttons
            obj.redrawButtons()

            % Set properties
            try
                uix.set( obj, varargin{:} )
            catch e
                delete( obj )
                e.throwAsCaller()
            end

        end % constructor

    end % structors

    methods

        function value = get.TitleColor( obj )

            value = obj.TitleBox.BackgroundColor;

        end % get.TitleColor

        function set.TitleColor( obj, value )

            % Set
            obj.TitleBox.BackgroundColor = value;
            obj.TitleText.BackgroundColor = value;
            obj.MinimizeButton.BackgroundColor = value;
            obj.DockButton.BackgroundColor = value;
            obj.HelpButton.BackgroundColor = value;
            obj.CloseButton.BackgroundColor = value;

        end % set.TitleColor

        function value = get.CloseRequestFcn( obj )

            value = obj.CloseButton.Callback;

        end % get.CloseRequestFcn

        function set.CloseRequestFcn( obj, value )

            % Set
            obj.CloseButton.Callback = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.CloseRequestFcn

        function value = get.DockFcn( obj )

            value = obj.DockButton.Callback;

        end % get.DockFcn

        function set.DockFcn( obj, value )

            % Set
            obj.DockButton.Callback = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.DockFcn

        function value = get.HelpFcn( obj )

            value = obj.HelpButton.Callback;

        end % get.HelpFcn

        function set.HelpFcn( obj, value )

            % Set
            obj.HelpButton.Callback = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.HelpFcn

        function value = get.MinimizeFcn( obj )

            value = obj.MinimizeButton.Callback;

        end % get.MinimizeFcn

        function set.MinimizeFcn( obj, value )

            % Set
            obj.MinimizeButton.Callback = value;
            obj.TitleText.Callback = value;
            if isempty( value )
                obj.TitleText.Enable = 'inactive';
            else
                obj.TitleText.Enable = 'on';
            end

            % Mark as dirty
            obj.redrawButtons()

        end % set.MinimizeFcn

        function value = get.Docked( obj )

            value = obj.Docked_;

        end % get.Docked

        function set.Docked( obj, value )

            % Check
            assert( islogical( value ) && isequal( size( value ), [1 1] ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''Docked'' must be true or false.' )

            % Set
            obj.Docked_ = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.Docked

        function value = get.Minimized( obj )

            value = obj.Minimized_;

        end % get.Minimized

        function set.Minimized( obj, value )

            % Check
            assert( islogical( value ) && isequal( size( value ), [1 1] ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''Minimized'' must be true or false.' )

            % Set
            obj.Minimized_ = value;

            % Show selected child
            obj.showSelection()

            % Mark as dirty
            obj.Dirty = true;

        end % set.Minimized

        function value = get.TitleHeight( obj )

            value = obj.TitleBox.Position(4);

        end % get.TitleHeight

        function set.MaximizeTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''MaximizeTooltipString'' must be a string.' )

            % Set
            obj.MaximizeTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.MaximizeTooltipString

        function set.MinimizeTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''MinimizeTooltipString'' must be a string.' )

            % Set
            obj.MinimizeTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.MinimizeTooltipString

        function set.UndockTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''UndockTooltipString'' must be a string.' )

            % Set
            obj.UndockTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.UndockTooltipString

        function set.DockTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''DockTooltipString'' must be a string.' )

            % Set
            obj.DockTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.DockTooltipString

        function set.HelpTooltipString( obj, value )

            % Check
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''HelpTooltipString'' must be a string.' )

            % Set
            obj.HelpTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.HelpTooltipString

        function set.CloseTooltipString( obj, value )

            % assert that value is a char array
            assert( ischar( value ), ...
                'uix:InvalidPropertyValue', ...
                'Property ''CloseTooltipString'' must be a string.' )

            obj.CloseTooltipString = value;

            % Mark as dirty
            obj.redrawButtons()

        end % set.CloseTooltipString

    end % accessors

    methods( Access = private )

        function onBorderWidthChanged( obj, ~, ~ )

            % Mark as dirty
            obj.Dirty = true;

        end % onBorderWidthChanged

        function onBorderTypeChanged( obj, ~, ~ )

            % Mark as dirty
            obj.Dirty = true;

        end % onBorderTypeChanged

        function onFontAngleChanged( obj, ~, ~ )

            obj.TitleText.FontAngle = obj.FontAngle;

        end % onFontAngleChanged

        function onFontNameChanged( obj, ~, ~ )

            % Set
            obj.TitleText.FontName = obj.FontName;

            % Mark as dirty
            obj.TitleHeight_ = -1;
            obj.Dirty = true;

        end % onFontNameChanged

        function onFontSizeChanged( obj, ~, ~ )

            % Set
            fontSize = obj.FontSize;
            obj.TitleText.FontSize = fontSize;
            obj.HelpButton.FontSize = fontSize;
            obj.CloseButton.FontSize = fontSize;
            obj.DockButton.FontSize = fontSize;
            obj.MinimizeButton.FontSize = fontSize;

            % Mark as dirty
            obj.TitleHeight_ = -1;
            obj.Dirty = true;

        end % onFontSizeChanged

        function onFontUnitsChanged( obj, ~, ~ )

            fontUnits = obj.FontUnits;
            obj.TitleText.FontUnits = fontUnits;
            obj.HelpButton.FontUnits = fontUnits;
            obj.CloseButton.FontUnits = fontUnits;
            obj.DockButton.FontUnits = fontUnits;
            obj.MinimizeButton.FontUnits = fontUnits;

        end % onFontUnitsChanged

        function onFontWeightChanged( obj, ~, ~ )

            obj.TitleText.FontWeight = obj.FontWeight;

        end % onFontWeightChanged

        function onForegroundColorChanged( obj, ~, ~ )

            foregroundColor = obj.ForegroundColor;
            obj.TitleText.ForegroundColor = foregroundColor;
            obj.MinimizeButton.ForegroundColor = foregroundColor;
            obj.DockButton.ForegroundColor = foregroundColor;
            obj.HelpButton.ForegroundColor = foregroundColor;
            obj.CloseButton.ForegroundColor = foregroundColor;

        end % onForegroundColorChanged

        function onTitleReturning( obj, ~, ~ )

            if strcmp( obj.TitleAccess, 'public' )

                obj.TitleAccess = 'private'; % start
                if ischar( obj.EmptyTitle )
                    obj.Title = obj.EmptyTitle;
                else
                    obj.Title = obj.TitleText.String;
                end

            end

        end % onTitleReturning

        function onTitleReturned( obj, ~, ~ )

            obj.Title = obj.NullTitle; % unset Title
            obj.TitleAccess = 'public'; % finish

        end % onTitleReturned

        function onTitleChanged( obj, ~, ~ )

            if strcmp( obj.TitleAccess, 'public' )

                % Set
                obj.TitleAccess = 'private'; % start
                title = obj.Title;
                if isempty( title )
                    obj.EmptyTitle = title; % store
                    obj.TitleText.String = obj.BlankTitle; % set String to blank
                else
                    obj.EmptyTitle = []; % not empty
                    obj.TitleText.String = title; % set String to title
                end
                obj.Title = obj.NullTitle; % unset Title
                obj.TitleAccess = 'public'; % finish

                % Mark as dirty
                obj.TitleHeight_ = -1;
                obj.Dirty = true;

            end

        end % onTitleChanged

    end % property event handlers

    methods( Access = protected )

        function redraw( obj )
            %redraw  Redraw
            %
            %  p.redraw() redraws the panel.
            %
            %  See also: redrawButtons

            % Compute positions
            bounds = hgconvertunits( ancestor( obj, 'figure' ), ...
                [0 0 1 1], 'normalized', 'pixels', obj );
            tX = 1;
            tW = max( bounds(3), 1 );
            tH = obj.TitleHeight_; % title height
            if tH == -1 % cache stale, refresh
                tH = ceil( obj.TitleText.Extent(4) );
                obj.TitleHeight_ = tH; % store
            end
            tY = 1 + bounds(4) - tH;
            p = obj.Padding_;
            cX = 1 + p;
            cW = max( bounds(3) - 2 * p, 1 );
            cH = max( bounds(4) - tH - 2 * p, 1 );
            cY = tY - p - cH;
            contentsPosition = [cX cY cW cH];

            % Redraw contents
            selection = obj.Selection_;
            if selection ~= 0
                uix.setPosition( obj.Contents_(selection), contentsPosition, 'pixels' )
            end
            obj.TitleBox.Position = [tX tY tW tH];
            obj.redrawButtons()

        end % redraw

        function showSelection( obj )
            %showSelection  Show selected child, hide the others
            %
            %  c.showSelection() shows the selected child of the container
            %  c, and hides the others.

            % Call superclass method
            showSelection@uix.mixin.Panel( obj )

            % If minimized, hide selected contents too
            selection = obj.Selection_;
            if selection ~= 0 && obj.Minimized_
                child = obj.Contents_(selection);
                child.Visible = 'off';
                if isa( child, 'matlab.graphics.axis.Axes' )
                    child.ContentsVisible = 'off';
                end
                % As a remedy for g1100294, move off-screen too
                margin = 1000;
                if isa( child, 'matlab.graphics.axis.Axes' ) ...
                        && strcmp(child.ActivePositionProperty, 'outerposition' )
                    child.OuterPosition(1) = -child.OuterPosition(3)-margin;
                else
                    child.Position(1) = -child.Position(3)-margin;
                end
            end

        end % showSelection

    end % template methods

    methods( Access = private )

        function redrawButtons( obj )
            %redrawButtons  Redraw buttons
            %
            %  p.redrawButtons() redraws the titlebar buttons.
            %
            %  Buttons use unicode arrow symbols:
            %  https://en.wikipedia.org/wiki/Arrow_%28symbol%29#Arrows_in_Unicode

            % Retrieve button box and buttons
            box = obj.TitleBox;
            titleText = obj.TitleText;
            minimizeButton = obj.MinimizeButton;
            dockButton = obj.DockButton;
            helpButton = obj.HelpButton;
            closeButton = obj.CloseButton;

            % Detach all buttons
            titleText.Parent = [];
            minimizeButton.Parent = [];
            dockButton.Parent = [];
            helpButton.Parent = [];
            closeButton.Parent = [];

            % Attach active buttons
            titleText.Parent = box;
            minimize = ~isempty( obj.MinimizeFcn );
            if minimize
                minimizeButton.Parent = box;
                box.Widths(end) = minimizeButton.Extent(3);
            end
            dock = ~isempty( obj.DockFcn );
            if dock
                dockButton.Parent = box;
                box.Widths(end) = dockButton.Extent(3);
            end
            help = ~isempty( obj.HelpFcn );
            if help
                helpButton.Parent = box;
                helpButton.TooltipString = obj.HelpTooltipString;
                box.Widths(end) = helpButton.Extent(3);
            end
            close = ~isempty( obj.CloseRequestFcn );
            if close
                closeButton.Parent = box;
                closeButton.TooltipString = obj.CloseTooltipString;
                box.Widths(end) = closeButton.Extent(3);
            end

            % Update icons
            if obj.Minimized_
                minimizeButton.String = char( 9662 );
                minimizeButton.TooltipString = obj.MaximizeTooltipString;
            else
                minimizeButton.String = char( 9652 );
                minimizeButton.TooltipString = obj.MinimizeTooltipString;
            end
            if obj.Docked_
                dockButton.String = char( 8599 );
                dockButton.TooltipString = obj.UndockTooltipString;
            else
                dockButton.String = char( 8600 );
                dockButton.TooltipString = obj.DockTooltipString;
            end

        end % redrawButtons

    end % helper methods

end % classdef

author: goGPS-Project


text:
function [var, U, lambda] = ppca(x, ppca_dim)
%PPCA	Probabilistic Principal Components Analysis
%
%	Description
%	 [VAR, U, LAMBDA] = PPCA(X, PPCA_DIM) computes the principal
%	component subspace U of dimension PPCA_DIM using a centred covariance
%	matrix X. The variable VAR contains the off-subspace variance (which
%	is assumed to be spherical), while the vector LAMBDA contains the
%	variances of each of the principal components.  This is computed
%	using the eigenvalue and eigenvector  decomposition of X.
%
%	See also
%	EIGDEC, PCA
%

%	Copyright (c) Ian T Nabney (1996-2001)

if ppca_dim ~= round(ppca_dim) | ppca_dim < 1 | ppca_dim > size(x, 2)
   error('Number of PCs must be integer, >0, < dim');
end

[ndata, data_dim] = size(x);
% Assumes that x is centred and responsibility weighted
% covariance matrix
[l Utemp] = eigdec(x, data_dim);
% Zero any negative eigenvalues (caused by rounding)
l(l<0) = 0;
% Now compute the sigma squared values for all possible values
% of q
s2_temp = cumsum(l(end:-1:1))./[1:data_dim]';
% If necessary, reduce the value of q so that var is at least
% eps * largest eigenvalue
q_temp = min([ppca_dim; data_dim-min(find(s2_temp/l(1) > eps))]);
if q_temp ~= ppca_dim
  wstringpart = 'Covariance matrix ill-conditioned: extracted';
  wstring = sprintf('%s %d/%d PCs', ...
      wstringpart, q_temp, ppca_dim);
  warning(wstring);
end
if q_temp == 0
  % All the latent dimensions have disappeared, so we are
  % just left with the noise model
  var = l(1)/data_dim;
  lambda = var*ones(1, ppca_dim);
else
  var = mean(l(q_temp+1:end));
end
U = Utemp(:, 1:q_temp);
lambda(1:q_temp) = l(1:q_temp);

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt