text:
classdef MimToolbarPanel < GemPanel
    % MimToolbarPanel. Part of the gui for the TD MIM Toolkit.
    %
    %     This class is used internally within the TD MIM Toolkit to help
    %     build the user interface.
    %
    %     MimToolbarPanel represents a dynamic panel containing tool
    %     controls that can enable or disable themselves when updated.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties (Access = private)
        ControlGroups
        ControlGroupSeparators
        OrderedControlGroupList
        GuiApp
        ModeTabName
        ModeToSwitchTo
        OrganisedPlugins
        ToolMap
        AppDef
        Visibility
        GroupVertically
        AllowWrapping
    end

    properties (Constant)
        ToolbarHeight = 85
        RowHeight = 85
        LeftMargin = 10
        RightMargin = 20
        HorizontalSpacing = 10
    end

    methods
        function obj = MimToolbarPanel(parent, organised_plugins, mode_tab_name, mode_to_switch_to, visibility, gui_app, app_def, group_vertically, allow_wrapping)
            obj = obj@GemPanel(parent);

            obj.ModeTabName = mode_tab_name;
            obj.ModeToSwitchTo = mode_to_switch_to;
            obj.Visibility = visibility;
            obj.TopBorder = ~group_vertically;
            obj.AppDef = app_def;
            obj.GuiApp = gui_app;
            obj.ControlGroups = containers.Map;
            obj.ControlGroupSeparators = containers.Map;
            obj.OrderedControlGroupList = {};
            obj.ToolMap = containers.Map;
            obj.OrganisedPlugins = organised_plugins;
            obj.GroupVertically = group_vertically;
            obj.AllowWrapping = allow_wrapping;

            obj.AddTools();
        end

        function Resize(obj, new_position)
            Resize@GemPanel(obj, new_position);

            % After calling Resize@GemPanel, the position will have been adjusted due to the border
            new_position = obj.InnerPosition;

            resize_list = obj.ComputeSizes(new_position(3));

            % Do the actual resize
            panel_height = max(1, new_position(4));
            panel_top = new_position(2) + panel_height;
            for resize_item = resize_list
                item = resize_item{1}{1};
                new_size = resize_item{1}{2};
                new_size(2) = new_size(2) + panel_top;
                item.Resize(new_size);
            end

        end

        function resize_list = ComputeSizes(obj, width)
            % Create a structure containing the new positions

            min_x = 1 + obj.LeftMargin;
            max_x = width - obj.RightMargin;
            x_position = min_x;

            row_height = obj.RowHeight;
            y_column_top = 0;
            y_column_base = y_column_top - row_height;

            is_first_separator = true;
            resize_list = [];

            for tool_group_key = obj.OrderedControlGroupList
                tool_group_panel = obj.ControlGroups(tool_group_key{1});

                if tool_group_panel.Enabled
                    group_panel_height = tool_group_panel.GetRequestedHeight;
                    group_panel_width = tool_group_panel.GetWidth;

                    if (obj.AllowWrapping) && (x_position > min_x) && (obj.GroupVertically || (x_position + group_panel_width > max_x))
                        x_position = min_x;
                        y_column_top = y_column_top - row_height;
                        y_column_base = y_column_top - row_height;
                    end

                    if obj.GroupVertically
                        separator = obj.ControlGroupSeparators(tool_group_key{1});
                        y_position = y_column_top - separator.GetRequestedHeight;
                        if is_first_separator
                            is_first_separator = false;
                            separator.TopBorder = false;
                        else
                            separator.TopBorder = true;
                        end
                        separator.Enable();

                        resize_list{end + 1} = {separator, [1, y_position, width, separator.GetRequestedHeight()]};
                        y_column_top = y_column_top - separator.GetRequestedHeight();
                        y_column_base = y_column_top - row_height;
                    end

                    y_offset = round((row_height - group_panel_height)/2);
                    y_position = y_column_base + y_offset;
                    resize_list{end + 1} = {tool_group_panel, [x_position, y_position, group_panel_width, group_panel_height]};
                    x_position = x_position + obj.HorizontalSpacing + group_panel_width;

                else
                    if obj.GroupVertically
                        separator = obj.ControlGroupSeparators(tool_group_key{1});
                        separator.Disable();
                    end
                end
            end
        end

        function Update(obj, gui_app)
            % Calls each group panel and updates the controls. In some cases, controls will
            % become enabled that were previously disabled; this requires the position
            % (since this may not have been set if this is the first time the control has been made visible)

            for tool_group_key = obj.OrderedControlGroupList
                tool_group_panel = obj.ControlGroups(tool_group_key{1});
                tool_group_panel.Update(gui_app);
            end

            if ~isempty(obj.Position)
                obj.Resize(obj.Position);
            end

        end

        function height = GetRequestedHeight(obj, width)
            if obj.GroupVertically
                resize_list = obj.ComputeSizes(width);
                if isempty(resize_list)
                    height = 0;
                else
                    height = abs(resize_list{end}{2}(2));
                end
            else
                height = obj.ToolbarHeight;
            end
        end

        function mode = GetModeTabName(obj)
            mode = obj.ModeTabName;
        end

        function visibility = GetVisibility(obj)
            visibility = obj.Visibility;
        end

        function mode = GetModeToSwitchTo(obj)
            mode = obj.ModeToSwitchTo;
        end

        function AddPlugins(obj, current_dataset)
        end

        function UpdateForNewImage(obj, current_dataset, window, level)
        end

        function AddPreviewImage(obj, plugin_name, preview_fetcher, window, level)
        end

        function RefreshPlugins(obj, current_dataset, window, level)
        end

    end

    methods (Access = private)
        function AddTools(obj)
            tools = obj.OrganisedPlugins.GetOrderedPlugins(obj.ModeTabName);
            for tool = tools
                obj.AddTool(tool{1});
            end
        end

        function AddTool(obj, tool_wrapper)
            tool = tool_wrapper.PluginObject;
            tool_name = class(tool);
            category_key = tool.Category;
            if ~obj.ControlGroups.isKey(category_key)
                new_group = GemLabelButtonGroup(obj, category_key, '', category_key);
                obj.ControlGroups(category_key) = new_group;
                obj.OrderedControlGroupList{end + 1} = category_key;
                obj.AddChild(new_group);

                if obj.GroupVertically
                    separator = GemSeparator(obj, category_key);
                    obj.ControlGroupSeparators(category_key) = separator;
                    obj.AddChild(separator);
                end
            end
            icon_found = false;

            if isprop(tool, 'Icon')
                icons_paths = obj.AppDef.GetIconsFolders;
                for icon_path = icons_paths
                    if CoreDiskUtilities.FileExists(icon_path{1}, tool.Icon)
                        icon = imread(fullfile(icon_path{1}, tool.Icon));
                        icon_found = true;
                        break;
                    end
                end
            end

            if ~icon_found
                icon = imread(obj.AppDef.GetDefaultPluginIcon);
            end

            % IconColour overrides greyscale
            if isprop(tool, 'IconColour')
                size_icon = size(icon);
                icon = double(icon/255);
                icon_bw = repmat(0.21*icon(:,:,1) + 0.72*icon(:,:,2) + 0.07*icon(:,:,3), [1,1,3]);
                colour_tint = repmat(shiftdim(double(tool.IconColour), -1), [size_icon(1:2), 1]);
                icon = uint8(255*colour_tint.*icon_bw);
            elseif obj.AppDef.ForceGreyscale
                icon = repmat(0.21*icon(:,:,1) + 0.72*icon(:,:,2) + 0.07*icon(:,:,3), [1,1,3]);
            end

            tool_group = obj.ControlGroups(category_key);
            if isa(tool, 'MimGuiPluginSlider')
                new_control = MimPluginLabelSlider(obj, tool, icon, obj.GuiApp);
                new_control.StackVertically = tool.StackVertically;
            elseif isa(tool, 'MimGuiPluginEditBox')
                new_control = MimPluginLabelEditBox(obj, tool, icon, obj.GuiApp);
                new_control.StackVertically = tool.StackVertically;
            else
                new_control = MimPluginLabelButton(obj, tool, icon, @tool_wrapper.RunPlugin);
                new_control.ButtonWidth = 8*tool.ButtonWidth;
            end
            tool_group.AddControl(new_control);
            tool_struct = [];
            tool_struct.Control = new_control;
            tool_struct.ToolObject = tool;
            obj.ToolMap(tool_name) = tool_struct;
        end
    end
end

author: tomdoel

repo: pulmonarytoolkit


text:
function  filelist =  filehound(filespec)
%==========================================================================
% syntax:
%         filelist =  filehound(filespec)
% or:     filelist =  filehound
%         for default search for *.m files
%
% description   : recursively examines directories for presence of files
% 		  matching the filter defined by input parameter 'filespec'
%
% parameters in : filespec = (optional) filter for filenames default = '*.m'
% filespec can be of any kind: a wild card can be used both for filename
% and for extension.
%
% Examples:
%   filelist = filehound('*')
%   filelist = filehound('*.*')
%
% Search for all files in current directory and subdirectories
%
%   filelist = filehound('myfile')
%   filelist = filehound('myfile.*')
%
% Search for all files whose name is 'myfile' independently from extension
%
%   filelist = filehound('*.ext')
%
% Search for files with specific extension 'ext'
%
% Search of file is powered also by wild-card handling (i.e.: '*'). The
% only assumption is that the current program assumes that '*' is at least
% a permitted char, i.e. '*' cannot be an empty string. In this way: 'ab*c'
% cannot be equivalent to 'abc' in the search. Moreover '*abc' refers to
% the last part of a string, 'ab*c' sets constraints on first two letters
% of the string and the last letter, 'abc*', requires that the first three
% letters of the string are 'abc'. The string here is meant both filename
% and extension. Hence possible calls of filehound can be:
%
%  filelist = filehound('*x.m*t')
%  filelist = filehound('a*x.mt*')
%  filelist = filehound('ax*.*mt')
%  ...
%  ...
%  and all the other possbile combinations. Only one wild-card for filename
%  and extension is allowed.
%
% parameters out: filelist = cell array with paths for specified files
%
% filename      : filehound.m
%
%==========================================================================

%==========================================================================
% author        : Maurizio De Pitta', Tel-Aviv University
%                 mauriziodepitta@gmail.com, maurizio@post.tau.ac.il
%
% Based on filehound.m by Ronald Ouwerkerk, File ID: 171 on Matlab Central
% / File Exchange
%
% version 1.1, Tel Aviv, Sept 1st, 2008: Adopts filesep use (thanks to
% Thierry Dalon for the suggestion)
% version 1.0, Tel Aviv, July 7th, 2008
%
% To do: user-defined option to produce report TXT file with all the file
% found according to specified criteria
%==========================================================================
% global fout
global delimiter

%==========================================================================
% set default
%==========================================================================
if nargin == 0
  filespec = '*.m';
end;

% Original directory
olddir = pwd;

% Identifies filename part and extention part in filespec
delimiter = '.';
k = findstr(filespec,delimiter);
if isempty(k) % filespec is only the name of the file
    fnspec = filespec;
    extspec = '*';
else
    fnspec = filespec(1:k-1); % assumes that k is scalar (i.e.: only one '.' is in the file name and it is associated to extension
    extspec = filespec(k+1:end);
end

% %==========================================================================
% % Get parent directory to search and filename for collected files
% %==========================================================================
% fileuititle = 'Select directory and filename for report';
% [filename, pathname] = uiputfile('*.txt', fileuititle);
% if isempty(filename)
%   filename = 'report.txt';
%   pathname = pwd;
% else
%   eval(['cd ',pathname]);
% end;

% %==========================================================================
% % create filename for collected files delete old copies
% %==========================================================================
% topdir = pwd;
% outfilename = [topdir, filesep, filename];
% if exist(outfilename, 'file')
%   eval(['delete ',outfilename]);
% end;

%==========================================================================
% recursively scan all subdirectories
%==========================================================================
filelist = [];
% fout = fopen(outfilename,'a');
filelist = scandir(filelist, fnspec, extspec);
% fclose(fout);
eval(['cd ',olddir,';']);

%==========================================================================
% END main
%==========================================================================
%==========================================================================
% local function scandir
% Scans the present directory and recursively scans all directories below
%==========================================================================
function filelist = scandir(filelist, fnspec, extspec)
%==========================================================================
% define the global file ID
%==========================================================================
% global fout
global delimiter

%==========================================================================
% define set of leagl chars for dirnames
%==========================================================================
legalchar = '-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';

%==========================================================================
% get dir list
%==========================================================================
thisdir = pwd;
thisdirlist = dir(thisdir);

%==========================================================================
% find files (not isdir)
%==========================================================================
kdir = [thisdirlist(:).isdir];
allfilelist = struct2cell(thisdirlist(~kdir));
allfilelist = allfilelist(1,:);

% Builds cell array of filename and extension strings (only though if there
% are files in the current directory, in case not it skips to
% subdirectories)
if ~isempty(allfilelist)
    for i = 1:length(allfilelist)
        [tok,rem] = strtok(allfilelist(i),delimiter);
        filename(i) = tok;
        % This assignment takes all the extensions without '.'
        extension(i) = {rem{1}(2:end)};
    end

    % Wildcard handling on extspec
    iext = wildcardhandling(extspec,extension);
    % Wildcard handling on fnspec
    ifn = wildcardhandling(fnspec,filename);

%==========================================================================
% files matching the pattern of filespec
%==========================================================================
    % redefine k
    k = intersect(ifn,iext);
    allfilelist = allfilelist(k);
    nfiles = length(allfilelist);
    listpos = length(filelist);
    count = 0;

    for filei = 1:nfiles
        filestr = [thisdir,filesep,allfilelist{filei}];
        count = count+1;
        filelist{listpos + count} = filestr;
    end
end

%==========================================================================
% find subdirectories
%==========================================================================
kdir = [thisdirlist(:).isdir];
thisdirlist = thisdirlist(kdir);
ndirs = length(thisdirlist);

%==========================================================================
% scan all subdirectories recursively
%==========================================================================
for diri= 1:ndirs
  subdirname = thisdirlist(diri).name;
  if ~strcmp(subdirname,'.') & ~strcmp(subdirname,'..')
     ipos =  ismember(subdirname,legalchar);
     if length(subdirname(ipos)) < length(subdirname)
       msgstr = sprintf('Skipped directory %s because its name', subdirname);
       msgstr = sprintf('%s contains illegal characters\n',msgstr);
       disp(msgstr)
     else
       cmdstr = ['cd ',subdirname,';'];
       % Subdirectory checking - output messaging
       disp(cmdstr);
       eval(cmdstr);
       filelist = scandir(filelist, fnspec, extspec);
       cmdstr = ['cd ',thisdir,';'];
       eval(cmdstr);
    end;
  end
end
%==========================================================================
%END local function scandir
%==========================================================================
%==========================================================================
%local function wildcardhandling
%==========================================================================
function index = wildcardhandling(chkstr,liststr)
% Returns indexes of strings in liststr that match generic chkstr
% expression, this latter containing at most one '*' in any position
%
index = 1:length(liststr);
lstr = length(chkstr);
wcpos = findstr(chkstr,'*');
if isempty(wcpos) % liststr is specified
    k = strmatch(chkstr,liststr,'exact');
else
    k = [];
    % There is a wildcard in liststr specification - depending on the
    % position, different actions are taken
    if (wcpos==1)&(wcpos==lstr) % chkstr = '*'
        k = index;
    elseif (wcpos==1)&(wcpos<length(chkstr))  %'.*xx'
        for i = 1:length(liststr)
            if (length(liststr{i}(2:end))>=(lstr-1)) & strcmp(chkstr(2:end),liststr{i}(end-length(chkstr(2:end))+1:end))
                k = [k i];
            end
        end
    elseif (wcpos~=1)&(wcpos<length(chkstr))  %'.x*x'
        for i = 1:length(liststr)
            if (length(liststr{i}(liststr{i}~=wcpos))>=(lstr-1)) & strcmp(chkstr(1:wcpos-1),liststr{i}(1:length(chkstr(1:wcpos-1)))) & strcmp(chkstr(wcpos+1:end),liststr{i}(end-length(chkstr(wcpos+1:end))+1:end))
                k = [k i];
            end
        end
    else (wcpos~=1)&(wcpos==length(chkstr))   %'.xx*'
        for i = 1:length(liststr)
            if (length(liststr{i}(1:end-1))>=(lstr-1)) & strcmp(chkstr(1:end-1),liststr{i}(1:length(chkstr(1:end-1))))
                k = [k i];
            end
        end
    end
end
index = index(k);
%==========================================================================
%END local function wildcardhandling
%==========================================================================

author: Sable

repo: mcbench-benchmarks


text:
function varargout = tapas_uniqc_example_slider4d()
%creates 4D dataset numerically and runs tapas_uniqc_slider4d to show capability of it
%
%    tapas_uniqc_example_slider4d()
%
% IN
%
% OUT
%
% EXAMPLE
%   tapas_uniqc_example_slider4d
%
%   See also

% Author: Lars Kasper
% Created: 2013-05-15
% Copyright (C) 2013 Institute for Biomedical Engineering, ETH/Uni Zurich.

Y = tapas_uniqc_create_shepp_logan_4d();
nSli = 1;
tapas_uniqc_slider4d(Y, @tapas_uniqc_plot_image_diagnostics, nSli);

if nargout > 1
    varargout{1} = Y;
end

author: translationalneuromodeling

repo: tapas


text:
%------------------------------------------------------------------
%--------- Show Conf Mat ------------------------------------------
%------------------------------------------------------------------

function ShowConfMat(ConfMatOpt)
disp('Stimulus\Response | Anger | Happiness | Neutral | Sadness | Surprise');
disp('--------------------------------------------------------------------');
disp(sprintf('Anger                  %4.2f     %4.2f      %4.2f     %4.2f      %4.2f ',    ConfMatOpt(1,1), ConfMatOpt(1,2), ConfMatOpt(1,3), ConfMatOpt(1,4),  ConfMatOpt(1,5)));
disp(sprintf('Happiness              %4.2f     %4.2f      %4.2f     %4.2f      %4.2f ', ConfMatOpt(2,1), ConfMatOpt(2,2), ConfMatOpt(2,3), ConfMatOpt(2,4),  ConfMatOpt(2,5)));
disp(sprintf('Neutral                %4.2f     %4.2f      %4.2f     %4.2f      %4.2f ',    ConfMatOpt(3,1), ConfMatOpt(3,2), ConfMatOpt(3,3), ConfMatOpt(3,4),  ConfMatOpt(3,5)));
disp(sprintf('Sadness                %4.2f     %4.2f      %4.2f     %4.2f      %4.2f ',  ConfMatOpt(4,1), ConfMatOpt(4,2), ConfMatOpt(4,3), ConfMatOpt(4,4),  ConfMatOpt(4,5)));
disp(sprintf('Surprise               %4.2f     %4.2f      %4.2f     %4.2f      %4.2f ',    ConfMatOpt(5,1), ConfMatOpt(5,2), ConfMatOpt(5,3), ConfMatOpt(5,4),  ConfMatOpt(5,5)));
disp('------------------------------------------------------------------------------');
return


text:
function [y,deriv] = neg_gaussll_taylor(w,x)
% This is an MV2DF. See MV2DF_API_DEFINITION.readme.
% This function represents the part of log N(x|0,W) that is dependent on
%   W = reshape(w,...), where w is variable and x is given.
%
% y = -0.5*x'*inv(W)*x - 0.5*log(det(W)), where W is positive definite and W = reshape(w,...)

if nargin==0
    test_this();
    return;
end

if isempty(w)
    y = @(w)neg_gaussll_taylor(w,x);
    return;
end

if isa(w,'function_handle')
    outer = neg_gaussll_taylor([],x);
    y = compose_mv(outer,w,[]);
    return;
end

dim = length(x);
W = reshape(w,dim,dim);

[inv_map,logdet] = invchol_taylor(W);
z = inv_map(x);
y = 0.5*x'*z + 0.5*logdet;
deriv = @(dy) deriv_this(dy,z,inv_map);

end

function [g,hess,linear] = deriv_this(dy,z,inv_map)
G1 = z*z.';
G2 = inv_map(eye(length(z)));
grad = 0.5*(G2(:)-G1(:));
g = dy*grad;
linear = false;
hess = @(d) hess_this(grad,z,inv_map,dy,d);
end

function [h,Jd] = hess_this(grad,z,inv_map,dy,d)
dim = sqrt(length(d));
D = reshape(d,dim,dim);
H1 = inv_map(D*z)*z' + z*inv_map(D'*z)';
H2 = inv_map(inv_map(D)');
h = 0.5*dy*(H1(:)-H2(:));
if nargout>1
    Jd =  grad.'*d(:);
end
end

function test_this()
m = 3;
n = 10;

w = [];
A = UtU(w,n,m); %A is m-by-m
x = randn(m,1);

f = neg_gaussll_taylor(A,x);
w = randn(m*n,1);

test_MV2DF(f,w,true);
end

author: nesl


text:
function varargout = anaglyph(varargin)
% ANAGLYPH - displays an anaglyph obtained by two stereoscopical images
%
% anaglyph with no arguments, opens a dialog to pick an image which contains
% two stereoscopical images in a single image file.
%
% anaglyph('filename') displays an anaglyph of the image "filename"
% (with extension), which contains two stereoscopical images in a single
% image file (bmp, jpg, or other supported image type).
%
% anaglyph('filename1', 'filename2') displays an anaglyph from the two images
% "filename1", "filename2" (with extension) one for the right eye and one for
% the left one.
%
% anaglyph(A) displays an anaglyph of the image A, in memory,
% which contains two stereoscopical images in a single image
% file (bmp, jpg, or other supported image type).
%
% anaglyph(A,B) displays an anaglyph from the two images A and B, in memory,
% (with extension) one for the right eye and one for the left one.
%
% Inputs: one or two names of image files or of matlab variables
%
% Outputs (optional):
%    the figure handle to the anaglyph
%
% Notes:
% One can swap the two images during the visualization.
%
% Version 2.0 NEWS
% - now plots also images in memory
% - with no args, opens a dialog to choose the image
% - zoom function
%
% Example:
%    anaglyph('foto3d.bmp')
%
% Other m-files required: none
% Subfunctions: plotAnaglyph, swap
% MAT-files required: none
%
% See also: stereoview
%
% Author: Iari-Gabriel Marino, Ph.D., nonlinear optics
% University of Parma, Dept. of Physics, ITALY
% email address: iarigabriel.marino@fis.unipr.it
% Website: http://www.fis.unipr.it/raman/index2.htm
% Personal: http://www.fis.unipr.it/home/marino/
% November 2006; Last revision: 6-Nov-2006
%
%------------- BEGIN CODE --------------

switch nargin
    case 0
        [imageName, pathname] = uigetfile({'*.*'}, 'Pick a stereo image..');
        m = imread([pathname imageName(1:end-4)],imageName(end-2:end));
        [x,y,z] = size(m);
        if rem(y,2) == 0,
            dx = m(:,1:y/2,:);
            sx = m(:,y/2+1:end,:);
        elseif rem(y,2) == 1,
            dx = m(:,1:fix(y/2),:);
            sx = m(:,fix(y/2)+1:end-1,:);
        end
    case 1
        % cuts the image in two
        imageName = varargin{1};
        if isstr(imageName) % if it is a string, I load it
            m = imread(imageName(1:end-4),imageName(end-2:end));
        else % else it is a variable yet in memory:
            m = imageName;
        end
        [x,y,z] = size(m);
        if rem(y,2) == 0,
            dx = m(:,1:y/2,:);
            sx = m(:,y/2+1:end,:);
        elseif rem(y,2) == 1,
            dx = m(:,1:fix(y/2),:);
            sx = m(:,fix(y/2)+1:end-1,:);
        end
    case 2
        % assign each image
        namedx = varargin{1};
        namesx = varargin{2};
        if and(isstr(namedx),isstr(namesx)) % if they are strings, I load them
            dx = imread(namedx(1:end-4),namedx(end-2:end));
            sx = imread(namesx(1:end-4),namesx(end-2:end));
        else % else they should be variable yet in memory
            dx = namedx;
            sx = namesx;
        end
end

figH = figure;
set(figH,'userdata',0);

swapButt = uicontrol(figH,'style','pushbutton','String','Swap RL','value',0,'pos',[20 10 58 20]);
zoomInButt = uicontrol(figH,'style','pushbutton','String','Zoom +','pos',[80 10 58 20]);
zoomOutButt = uicontrol(figH,'style','pushbutton','String','Zoom -','pos',[140 10 58 20]);

set(swapButt,'callback',{@swap,dx,sx,figH});
set(zoomInButt,'callback',{@zoomCLB,-0.1})
set(zoomOutButt,'callback',{@zoomCLB,+0.1})

plotAnaglyph(dx,sx);

if nargout == 1,
    varargout = {figH};
end

% -------------------------------------------------------
% Plots the anaglyphic image
function plotAnaglyph(A,B);

r = zeros(size(A));
gb = zeros(size(B));

r(:,:,1) = double(A(:,:,1));
gb(:,:,2:3) = double(B(:,:,2:3));

% subplot(1,2,1)
% image(uint8(r)); axis equal
%
% subplot(1,2,2)
% image(uint8(gb)); axis equal

image(uint8(r+gb));
axis equal
set(gca,'YTickLabel',[])
set(gca,'XTickLabel',[])
set(gca,'XTick',[])
set(gca,'YTick',[])
set(gca,'color',[0 0 0])
set(gcf,'color',[0 0 0])
shg

% -------------------------------------------------------
% Swaps right/left
function swap(UiHandle,action,A,B,figH)
flag = get(figH,'userdata');
switch flag
case 1
    plotAnaglyph(A,B);
    set(figH,'userdata',0);
case 0
    plotAnaglyph(B,A);
    set(figH,'userdata',1);
end
% -------------------------------------------------------
% Zoom
function zoomCLB(UiHandle,action,D)
origCVA = get(gca,'CameraViewAngle');
set(gca,'CameraViewAngle',origCVA+D)
%------------- END OF CODE --------------


text:
function Mh = hmxSingle(Mh)
%+========================================================================+
%|                                                                        |
%|         OPENHMX - LIBRARY FOR H-MATRIX COMPRESSION AND ALGEBRA         |
%|           openHmx is part of the GYPSILAB toolbox for Matlab           |
%|                                                                        |
%| COPYRIGHT : Matthieu Aussal (c) 2017-2018.                             |
%| PROPERTY  : Centre de Mathematiques Appliquees, Ecole polytechnique,   |
%| route de Saclay, 91128 Palaiseau, France. All rights reserved.         |
%| LICENCE   : This program is free software, distributed in the hope that|
%| it will be useful, but WITHOUT ANY WARRANTY. Natively, you can use,    |
%| redistribute and/or modify it under the terms of the GNU General Public|
%| License, as published by the Free Software Foundation (version 3 or    |
%| later,  http://www.gnu.org/licenses). For private use, dual licencing  |
%| is available, please contact us to activate a "pay for remove" option. |
%| CONTACT   : matthieu.aussal@polytechnique.edu                          |
%| WEBSITE   : www.cmap.polytechnique.fr/~aussal/gypsilab                 |
%|                                                                        |
%| Please acknowledge the gypsilab toolbox in programs or publications in |
%| which you use it.                                                      |
%|________________________________________________________________________|
%|   '&`   |                                                              |
%|    #    |   FILE       : hmxSingle.m                                   |
%|    #    |   VERSION    : 0.40                                          |
%|   _#_   |   AUTHOR(S)  : Matthieu Aussal                               |
%|  ( # )  |   CREATION   : 14.03.2017                                    |
%|  / 0 \  |   LAST MODIF : 14.03.2018                                    |
%| ( === ) |   SYNOPSIS   : Convert H-Matrix to single precision          |
%|  `---'  |                                                              |
%+========================================================================+

% Position
Mh.pos = {single(Mh.pos{1}),single(Mh.pos{2})};

%%% H-Matrix (recursion)
if (Mh.typ == 0)
    for i = 1:4
        Mh.chd{i} = hmxSingle(Mh.chd{i});
        Mh.row{i} = single(Mh.row{i});
        Mh.col{i} = single(Mh.col{i});
    end
    Mh = hmxFusion(Mh);

%%% Compressed leaf
elseif (Mh.typ == 1)
    Mh.dat{1} = single(Mh.dat{1});
    Mh.dat{2} = single(Mh.dat{2});

%%% Full leaf
elseif (Mh.typ == 2)
    Mh.dat = single(Mh.dat);

%%% Unknown type
else
    error('hmxSingle.m : unavailable case')
end
end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function V = pcapred_decomp (X,T,options)
% it assumes that X is centered

is_cell_strings = iscell(X) && ischar(X{1});
is_cell_matrices = iscell(X) && ~ischar(X{1});
is_struct = ~is_cell_strings && ~is_cell_matrices && isstruct(X);

orders = formorders(options.order,options.orderoffset,options.timelag,options.exptimelag);

N = 0;
if is_cell_strings || is_cell_matrices
    [~,XX] = loadfile(X{1},T{1},options);
    if options.zeromean==0, XX = XX(:,2:end); end
    XX2 = (XX' * XX);
    N = N + size(XX,1);
    for n=2:length(T)
        [~,XX] = loadfile(X{n},T{n},options);
        if options.zeromean==0, XX = XX(:,2:end); end
        XX2 = XX2 + (XX' * XX);
        N = N + size(XX,1);
    end
elseif is_struct
    XX = formautoregr(X.X,T,orders,options.maxorder,1,1);
    N = size(XX,1);
    XX2 = (XX' * XX);
else
    XX = formautoregr(X,T,orders,options.maxorder,1,1);
    N = size(XX,1);
    XX2 = (XX' * XX);
end

[V,~,~] = svd( XX2 / (N-1) );
V = V(:,(1:options.pcapred) + (options.vcomp-1) );

end

author: OHBA-analysis

repo: HMM-MAR


text:
function B = B_Matrix(phi,th,psi,v,Lt,Lc)

%This function is the jacobian of the system dynamics with respect to the
%actuators. It is derived in Derive_EoM.m

B = [...

                   -cos(phi)*cos(psi)*sin(th),                      v*cos(phi)*sin(psi)*sin(th);
                    cos(phi)*cos(psi)*cos(th),                     -v*cos(phi)*cos(th)*sin(psi);
                       (cos(psi)*sin(phi))/Lt,                        -(v*sin(phi)*sin(psi))/Lt;
 (Lt*sin(psi) - Lc*cos(psi)*sin(phi))/(Lc*Lt), (v*(Lt*cos(psi) + Lc*sin(phi)*sin(psi)))/(Lc*Lt)];

end

author: MatthewPeterKelly

repo: dscTutorials


text:
function data = readImage(img)
    data.intensity = mean2(img);
    data.red = mean2(img(:,:,1));
    data.green = mean2(img(:,:,2));
    data.blue = mean2(img(:,:,3));

    gimg = rgb2gray(img);
    range = rangefilt(gimg);
    std = stdfilt(gimg);
    entropy = entropyfilt(gimg);

    data.mean_range = mean2(range);
    data.std_range = std2(range);
    data.mean_std = mean2(std);
    data.std_std = std2(std);
    data.mean_entropy = mean2(entropy);
    data.std_entropy = std2(entropy);

end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text: load  data1

author: Eurus-Holmes


text:
function geometry_test1895 ( )

%*****************************************************************************80
%
%% TEST1895 tests SPHERE_UNIT_AREA_ND, SPHERE_UNIT_AREA_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2005
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST1895:\n' );
  fprintf ( 1, '  SPHERE_UNIT_AREA_ND evaluates the area of the unit\n' );
  fprintf ( 1, '  sphere in N dimensions.\n' );
  fprintf ( 1, '  SPHERE_UNIT_AREA_VALUES returns some test values.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '     DIM_NUM    Exact          Computed\n' );
  fprintf ( 1, '             Area           Area\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, dim_num, area ] = sphere_unit_area_values ( n_data );

    if ( n_data == 0 )
      break
    end

    area2 = sphere_unit_area_nd ( dim_num );

    fprintf ( 1, '  %6d  %10f  %10f\n', dim_num, area, area2 );

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function GMST=TAI2GAST(Jul1,Jul2,version,deltaT)
%%TAI2GAST Convert from international atomic time (TAI) to Greenwhich
%          apparent sidereal time (GAST), which is a measure of the
%          rotational direction of the Earth.
%
%INPUTS: Jul1,Jul2 Two parts of a pseudo-Julian date given in TAI. The
%                  units of the date are days. The full date is the sum of
%                  both terms. The date is broken into two parts to
%                  provide more bits of precision. It does not matter how
%                  the date is split.
%          version An optional integer specifying the theory to use for
%                  GMST. The theory chosen should be consistent with other
%                  values used in astronomical routines. Possible values
%                  are
%                  1982 Compute GAST ion accordance with the International
%                     Astronomical Union's (IAU's) 1982 model.
%                  2000 Compute GMST in line with IAU 2000 resolutions
%                     related to precession and nutation.
%                  2006 (The default if omitted) Compute GMST in line with
%                     IAU 2006 resolutions related to precession and
%                     nutation.
%           deltaT An optional parameter specifying the offset between TT
%                  and UT1 in seconds. If this parameter is omitted, then
%                  the value of the function getEOP will be used.
%
%OUTPUTS: GAST The Greenwhich apparent sideral time in radians.
%
%The function just calls TAI2TT and then TT2GAST.
%
%GAST is defined in Section 5.5.7 of [1].
%
%REFERENCES:
%[1] G. Petit and B. Luzum, IERS Conventions (2010), International Earth
%    Rotation and Reference Systems Service Std. 36, 2010.
%
%April 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

[Jul1,Jul2]=TAI2TT(Jul1,Jul2);

if(nargin==2)
    GMST=TT2GAST(Jul1,Jul2);
elseif(nargin==3)
    GMST=TT2GAST(Jul1,Jul2,version);
else
    GMST=TT2GAST(Jul1,Jul2,version,deltaT);
end

end

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

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
clear all, close all, clc

t = (-3:.01:3)';

Utrue = [cos(17*t).*exp(-t.^2) sin(11*t)];
Strue = [2 0; 0 .5];
Vtrue = [sin(5*t).*exp(-t.^2) cos(13*t)];

X = Utrue*Strue*Vtrue';
figure, imshow(X);

%%
sigma = 1;
Xnoisy = X+sigma*randn(size(X));
figure, imshow(Xnoisy);

%%
[U,S,V] = svd(Xnoisy);

N = size(Xnoisy,1);
cutoff = (4/sqrt(3))*sqrt(N)*sigma; % Hard threshold
r = max(find(diag(S)>cutoff)); % Keep modes w/ sig > cutoff
Xclean = U(:,1:r)*S(1:r,1:r)*V(:,1:r)';
figure, imshow(Xclean)

%%
cdS = cumsum(diag(S))./sum(diag(S));  % Cumulative energy
r90 = min(find(cdS>0.90));  % Find r to capture 90% energy

X90 = U(:,1:r90)*S(1:r90,1:r90)*V(:,1:r90)';
figure, imshow(X90)

%% plot singular values

semilogy(diag(S),'-ok','LineWidth',1.5), hold on, grid on
semilogy(diag(S(1:r,1:r)),'or','LineWidth',1.5)
plot([-20 N+20],[cutoff cutoff],'r--','LineWidth',2)
axis([-10 610 .003 300])
rectangle('Position',[-5,20,100,200],'LineWidth',2,'LineStyle','--')

figure
semilogy(diag(S),'-ok','LineWidth',1.5)
hold on, grid on
semilogy(diag(S(1:r,1:r)),'or','LineWidth',1.5)
plot([-20 N+20],[cutoff cutoff],'r--','LineWidth',2)
axis([-5 100 20 200])

figure
plot(cdS,'-ok','LineWidth',1.5)
hold on, grid on
plot(cdS(1:r90),'ob','LineWidth',1.5)
plot(cdS(1:r),'or','LineWidth',1.5)
set(gca,'XTick',[0 300 r90 600],'YTick',[0 .5 0.9 1.0])
xlim([-10 610])
plot([r90 r90 -10],[0 0.9 0.9],'b--','LineWidth',1.5)

author: dynamicslab


text:
function [weight] = corn_kernel(data, w, c)
% This program output the final portfolio the CORN strategy on data
% This version has one expert, thus straightforwardly go expert.
%
% function [weight] = corn_kernel(data, w, c)
%
% weight: final portfolio, used for next rebalance
%
% data: market sequence vectors
% w: window size
% c: correlation coefficient threshold
%
% Example: [weight] = corn_kernel(data, w, c);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of OLPS: http://OLPS.stevenhoi.org/
% Original authors: Bin LI, Steven C.H. Hoi
% Contributors:
% Change log:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

weight = corn_expert(data, w, c);

% if (size(weight, 1) == 1),
%     weight=weight';
% end

end

author: OLPS

repo: OLPS

save_path: github-repos/MATLAB/OLPS-OLPS


text:
%% dtiInit validation function
%
% Download example data from the RDT
% Set default parameters for rapid processing, excluding eddy current
%
% Run dtiInit and we will set some numbers to check for asserts.
%
% RL/BW Vistasoft Team, 2016

%% Get the example diffusion weighted imaging data from the RDT

rd = RdtClient('vistasoft');
rd.crp('/vistadata/diffusion/dtiInit/raw');
rd.listArtifacts('print',true)

rd.readArtifact('dti','type','bvec','destinationFolder',pwd);
rd.readArtifact('dti','type','bval','destinationFolder',pwd);
rd.readArtifact('dti.nii','type','gz','destinationFolder',pwd);

rd.crp('/vistadata/diffusion/dtiInit');
rd.listArtifacts('print',true)
rd.readArtifact('t1.nii','type','gz','destinationFolder',pwd);

%%

dwRawFileName = fullfile(pwd,'dti.nii.gz');
t1FileName = fullfile(pwd,'t1.nii.gz');
niT1 = niftiRead(t1FileName);

params = dtiInitParams;
params.eddyCorrect    = -1;  % This takes a long time so we turn eddy current and motion correction
params.phaseEncodeDir = 2;   % We have super powers and know this
params.clobber = true;       % Silently over-write files.
params.dwOutMm = niT1.pixdim;% Match the T1 so we can crop together

params.outDir = fullfile(vistaRootPath,'local');         % Stash output
[dt6FileName, outBaseDir] = dtiInit(dwRawFileName,t1FileName,params);

%%
slices = 50:59;
niftiView('dti_aligned_trilin_noMEC.nii.gz','slices',slices);
niftiView('t1.nii.gz','slices',slices);

% Original, before upsampling
niftiView('dti_b0.nii.gz','slices',slices);

% Can we show the white matter mask on top of the dti_aligned?

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function X=IG(l,m,J)

N=randn(J,1);
Y=N.^2;
X = m + (.5*m*m/l)*Y - (.5*m/l)*sqrt(4*m*l*Y+m*m*(Y.^2));
U=rand(J,1);

I=find(U>m./(X+m));
X(I)=m*m./X(I);


text:
%%%  PosCtrl_tune
clear
path('./icon/',path);
Init;

% constant value
RAD2DEG = 57.2957795;
DEG2RAD = 0.0174533;
% throttle when UAV is hovering
THR_HOVER = 0.609;
%% Initial condition
ModelInit_PosE = [0, 0, -100];
ModelInit_VelB = [0, 0, 0];
ModelInit_AngEuler = [0, 0, 0];
ModelInit_RateB = [0, 0, 0];
ModelInit_Rads = 557.142;

%% control parameter
% attitude PID parameters
Kp_PITCH_ANGLE = 6.5;
Kp_PITCH_AngleRate = 0.1;
Ki_PITCH_AngleRate = 0.02;
Kd_PITCH_AngleRate = 0.001;
Kp_ROLL_ANGLE = 6.5;
Kp_ROLL_AngleRate = 0.1;
Ki_ROLL_AngleRate = 0.02;
Kd_ROLL_AngleRate = 0.001;
Kp_YAW_AngleRate = 0.5;
Ki_YAW_AngleRate = 0.01;
Kd_YAW_AngleRate = 0.00;
% position PID parameters
Kpxp = 1.0;
Kpyp = 1.0;
Kpzp = 4.0;
Kvxp = 2.5; Kvxi = 0.4; Kvxd = 0.01;
Kvyp = 2.5; Kvyi = 0.4; Kvyd = 0.01;
Kvzp = 0.45; Kvzi = 0.01; Kvzd = 0.005;
% integral saturation
Saturation_I_RP_Max = 0.3;
Saturation_I_RP_Min = -0.3;
Saturation_I_Y_Max = 0.2;
Saturation_I_Y_Min = -0.2;
Saturation_I_ah = 3.43;
Saturation_I_az = 5;

% max control angle,default 35deg
MAX_CONTROL_ANGLE_ROLL = 35;
MAX_CONTROL_ANGLE_PITCH  = 35;
% max control angle rate,rad/s
MAX_CONTROL_ANGLE_RATE_PITCH = 220;
MAX_CONTROL_ANGLE_RATE_ROLL = 220;
MAX_CONTROL_ANGLE_RATE_Y = 200;
% max control speed, m/s
MAX_CONTROL_VELOCITY_XY = 5;
MAX_CONTROL_VELOCITY_Z = 3;
% throttle amplitude
MAX_MAN_THR = 0.9;
MIN_MAN_THR = 0.05;
%% run simulink model
PosCtrl_tune

author: RflySim

repo: RflyExpCode

save_path: github-repos/MATLAB/RflySim-RflyExpCode


text:
function f = dot(F, G)
%DOT   Vector dot product.
%   DOT(F, G) returns the dot product of the SPHEREFUN objects F and G. DOT(F,
%   G) is the same as F'*G.
%
% See also SPHEREFUNV/CROSS.

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

if ( isempty(F) || isempty(G) )
    f = spherefun();
    return
end

Fc = F.components;
Gc = G.components;

f = Fc{1}.*Gc{1} + Fc{2}.*Gc{2} + Fc{3}.*Gc{3};

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function y = convolve2(x, m, shape, tol)
%CONVOLVE2 Two dimensional convolution.
%   Y = CONVOLVE2(X, M) performs the 2-D convolution of matrices X and
%   M. If [mx,nx] = size(X) and [mm,nm] = size(M), then size(Y) =
%   [mx+mm-1,nx+nm-1]. Values near the boundaries of the output array are
%   calculated as if X was surrounded by a border of zero values.
%
%   Y = CONVOLVE2(X, M, SHAPE) where SHAPE is a string returns a
%   subsection of the 2-D convolution with size specified by SHAPE:
%
%       'full'    - (default) returns the full 2-D convolution,
%       'same'    - returns the central part of the convolution
%                   that is the same size as X (using zero padding),
%       'valid'   - returns only those parts of the convolution
%                   that are computed without the zero-padded
%                   edges, size(Y) = [mx-mm+1,nx-nm+1] when
%                   size(X) > size(M),
%       'wrap'    - as for 'same' except that instead of using
%                   zero-padding the input X is taken to wrap round as
%                   on a toroid.
%       'reflect' - as for 'same' except that instead of using
%                   zero-padding the input X is taken to be reflected
%                   at its boundaries.
%
%   CONVOLVE2 is fastest when mx > mm and nx > nm - i.e. the first
%   argument is the input and the second is the mask.
%
%   If the rank of the mask M is low, CONVOLVE2 will decompose it into a
%   sum of outer product masks, each of which is applied efficiently as
%   convolution with a row vector and a column vector, by calling CONV2.
%   The function will often be faster than CONV2 or FILTER2 (in some
%   cases much faster) and will produce the same results as CONV2 to
%   within a small tolerance.
%
%   Y = CONVOLVE2(... , TOL) where TOL is a number in the range 0.0 to
%   1.0 computes the convolution using a reduced-rank approximation to
%   M, provided this will speed up the computation. TOL limits the
%   relative sum-squared error in the effective mask; that is, if the
%   effective mask is E, the error is controlled such that
%
%       sum(sum( (M-E) .* (M-E) ))
%       --------------------------    <=  TOL
%            sum(sum( M .* M ))
%
%   See also CONV2, FILTER2.

% Copyright David Young, Feb 2002, revised Jan 2005, Jan 2009, Apr 2011

% Deal with optional arguments
error(nargchk(2,4,nargin));
if nargin < 3
    shape = 'full';    % shape default as for CONV2
    tol = 0;
elseif nargin < 4
    if isnumeric(shape)
        tol = shape;
        shape = 'full';
    else
        tol = 0;
    end
end;

% Set up to do the wrap & reflect operations, not handled by conv2
if ismember(shape, {'wrap' 'reflect'})
    x = extendarr(x, m, shape);
    shape = 'valid';
end

% do the convolution itself
y = doconv(x, m, shape, tol);
end

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

function y = doconv(x, m, shape, tol)
% Carry out convolution
[mx, nx] = size(x);
[mm, nm] = size(m);

% If the mask is bigger than the input, or it is 1-D already,
% just let CONV2 handle it.
if mm > mx || nm > nx || mm == 1 || nm == 1
    y = conv2(x, m, shape);
else
    % Get svd of mask
    if mm < nm; m = m'; end        % svd(..,0) wants m > n
    [u,s,v] = svd(m, 0);
    s = diag(s);
    rank = trank(m, s, tol);
    if rank*(mm+nm) < mm*nm         % take advantage of low rank
        if mm < nm;  t = u; u = v; v = t; end  % reverse earlier transpose
        vp = v';
        % For some reason, CONV2(H,C,X) is very slow, so use the normal call
        y = conv2(conv2(x, u(:,1)*s(1), shape), vp(1,:), shape);
        for r = 2:rank
            y = y + conv2(conv2(x, u(:,r)*s(r), shape), vp(r,:), shape);
        end
    else
        if mm < nm; m = m'; end     % reverse earlier transpose
        y = conv2(x, m, shape);
    end
end
end

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

function r = trank(m, s, tol)
% Approximate rank function - returns rank of matrix that fits given
% matrix to within given relative rms error. Expects original matrix
% and vector of singular values.
if tol < 0 || tol > 1
    error('Tolerance must be in range 0 to 1');
end
if tol == 0             % return estimate of actual rank
    tol = length(m) * max(s) * eps;
    r = sum(s > tol);
else
    ss = s .* s;
    t = (1 - tol) * sum(ss);
    r = 0;
    sm = 0;
    while sm < t
        r = r + 1;
        sm = sm + ss(r);
    end
end
end

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

function y = extendarr(x, m, shape)
% Extend x so as to wrap around on both axes, sufficient to allow a
% "valid" convolution with m to return the cyclical convolution.
% We assume mask origin near centre of mask for compatibility with
% "same" option.

[mx, nx] = size(x);
[mm, nm] = size(m);

mo = floor((1+mm)/2); no = floor((1+nm)/2);  % reflected mask origin
ml = mo-1;            nl = no-1;             % mask left/above origin
mr = mm-mo;           nr = nm-no;            % mask right/below origin

if strcmp(shape, 'wrap')
    y = exindex(x, 1-ml:mx+mr, 1-nl:nx+nr, 'circular');
else
    y = exindex(x, 1-ml:mx+mr, 1-nl:nx+nr, 'symmetric');
end

end


text:
function expdirs = makeMovies(rootdir,varargin)

[doforce,dosoftlink,~,rotatesideview] = ...
  myparse(varargin,'doforce',false,...
  'dosoftlink',false,'rotatefrontview',0,'rotatesideview',0);
% function makeMovies(rootdir)
% makes a jaaba folder for all the avi's nested in the rootdir.

expdirs = {};

dd = dir(rootdir);
for ndx =1:numel(dd)
  if strcmp(dd(ndx).name(1),'.'), continue; end
  curd = fullfile(rootdir,dd(ndx).name);
  if isdir(curd)

    if exist([curd '.avi'],'file') && exist(fullfile(curd,'movie.avi'),'file'),
      continue;
    else
      expdirs1 = makeMovies(curd);
      expdirs = [expdirs,expdirs1]; %#ok<AGROW>
    end

  else

    [~,fname,ext] = fileparts(dd(ndx).name);
    if strcmpi(ext,'.avi')

      if ismember(dd(ndx).name,{'movie.avi','movie_sde.avi','movie_frt.avi'}),
        fprintf('Not creating directory for %s, %s is a reserved name.\n',fullfile(rootdir,dd(ndx).name),dd(ndx).name);
        continue;
      end

      m = regexp(dd(ndx).name,'_front_','once');
      if ~isempty(m),
        fprintf('%s is a front-facing movie, not creating a directory for it.\n',fullfile(rootdir,dd(ndx).name));
        continue;
      end

      curf  = fullfile(rootdir,fname);
      if ~exist(curf,'dir')
        mkdir(curf);
      end
%       scurd = regexprep(curd,' ','\\ ');
%       scurf = regexprep(curf,' ','\\ ');
      if exist(fullfile(curf,'movie.avi'),'file') && doforce,
        delete(fullfile(curf,'movie.avi'));
      end
      if ~exist(fullfile(curf,'movie.avi'),'file'),
        try
          if rotatesideview ~= 0,
            rotatemov(curd,fullfile(curf,'movie.avi'),rotatesideview);
          else
            if isunix && ~ismac && nargin > 1 && dosoftlink,
              fprintf('Soft-linking %s to %s...\n',curd,fullfile(curf,'movie.avi'));
              [~,n,e] = fileparts(curd);
              % use relative links so that maybe this works when mounting from windows/mac?
              n = [n,e];
              syscmd = sprintf('ln -s ''../%s'' ''%s/movie.avi''',n,curf);
              unix(syscmd);
            else
              fprintf('Copying %s to %s...\n',curd,fullfile(curf,'movie.avi'));
              copyfile(curd,fullfile(curf,'movie.avi'));
            end
          end
        catch ME,
          fprintf('Could not copy video file for %s (%s)\n',curf,ME.message);
          continue;
        end
      else
        fprintf('%s exists, not re-copying it.\n',fullfile(curf,'movie.avi'));
      end
      if ~exist(fullfile(curf,'trx.mat'),'file')
        try
          fprintf('Generating trx file %s...\n',fullfile(curf,'trx.mat'));
          [~,nframes,~,~] = get_readframe_fcn(fullfile(curf,'movie.avi'));
          T.trx = genTrack(nframes,[640 480]);
          save(fullfile(curf,'trx.mat'),'-struct','T');
        catch ME,
          fprintf('Could not create trx file for %s (%s)\n',curf,ME.message);
          continue;
        end
      else
        fprintf('Trx file exists for %s, not regenerating\n',curf);
      end
      expdirs{end+1} = curf; %#ok<AGROW>
    end

  end

end

author: kristinbranson

repo: JAABA


text:
function [qp, QP_vp] = vpose2qpose(vp)

% VPOSE2QPOSE  Vector-specified to quaternion-specified pose conversion.
%
%   QP = VPOSE2QPOSE(VP) returns a full 7-pose QP=[P;Q] from a full 6-pose
%   VP=[P;V], where P is 3D opsition and Q and V are 3D orientations.
%
%   [QP,QP_vp] = VPOSE2QPOSE(...) returns also the Jacobian matrix
%
%   See also QPOSE2EPOSE, EPOSE2QPOSE, EULERANGLES, QUATERNION, FRAME.

%   Copyright 2015 Joan Sola @ IRI-UPC_CSIC.

[q, Q_v] = v2q(vp(4:6));

qp(1:3,1) = vp(1:3);
qp(4:7,1) = q;

% Get Jacobians
if nargout > 1
    QP_vp(1:3,1:3) = eye(3);
    QP_vp(4:7,4:6) = Q_v;
end

% ========== End of function - Start GPL license ==========

%   # START GPL LICENSE

%---------------------------------------------------------------------
%
%   This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
%   SLAMTB 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.
%
%   SLAMTB 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 SLAMTB.  If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------

%   SLAMTB is Copyright:
%   Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
%   Copyright (c) 2010-2013, Joan Sola,
%   Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
%   SLAMTB is Copyright 2009
%   by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
%   @ LAAS-CNRS.
%   See on top of this file for its particular copyright.

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb


text:
classdef SetRPYSteeringModelActionOptimVar < AbstractOptimizationVariable
    %SetRPYSteeringModelActionOptimVar Summary of this class goes here
    %   Detailed explanation goes here

    properties
        varObj = RollPitchYawPolySteeringModel.getDefaultSteeringModel()

        lb(1,10) double
        ub(1,10) double

        varRollConst(1,1) logical = false;
        varRollLin(1,1) logical   = false;
        varRollAccel(1,1) logical = false;

        varPitchConst(1,1) logical = false;
        varPitchLin(1,1) logical   = false;
        varPitchAccel(1,1) logical = false;

        varYawConst(1,1) logical = false;
        varYawLin(1,1) logical   = false;
        varYawAccel(1,1) logical = false;

        varTimeOffset(1,1) logical = false;
    end

    methods
        function obj = SetRPYSteeringModelActionOptimVar(varObj)
            obj.varObj = varObj;
            obj.varObj.optVar = obj;

            obj.id = rand();
        end

        function x = getXsForVariable(obj)
            x = NaN(1,10);

            if(obj.varRollConst)
                x(1) = obj.varObj.rollModel.constTerm;
            end
            if(obj.varRollLin)
                x(2) = obj.varObj.rollModel.linearTerm;
            end
            if(obj.varRollAccel)
                x(3) = obj.varObj.rollModel.accelTerm;
            end

            if(obj.varPitchConst)
                x(4) = obj.varObj.pitchModel.constTerm;
            end
            if(obj.varPitchLin)
                x(5) = obj.varObj.pitchModel.linearTerm;
            end
            if(obj.varPitchAccel)
                x(6) = obj.varObj.pitchModel.accelTerm;
            end

            if(obj.varYawConst)
                x(7) = obj.varObj.yawModel.constTerm;
            end
            if(obj.varYawLin)
                x(8) = obj.varObj.yawModel.linearTerm;
            end
            if(obj.varYawAccel)
                x(9) = obj.varObj.yawModel.accelTerm;
            end

            if(obj.varTimeOffset)
                x(10) = obj.varObj.yawModel.tOffset; %this applies for all angle models
            end

            x(isnan(x)) = [];
        end

        function [lb, ub] = getBndsForVariable(obj)
            useTf = obj.getUseTfForVariable();

            lb = obj.lb(useTf);
            ub = obj.ub(useTf);
        end

        function [lb, ub] = getAllBndsForVariable(obj)
            lb = obj.lb;
            ub = obj.lb;
        end

        function setBndsForVariable(obj, lb, ub)
            if(length(lb) == 10 && length(ub) == 10)
                obj.lb = lb;
                obj.ub = ub;
            else
                useTf = obj.getUseTfForVariable();

                obj.lb(useTf) = lb;
                obj.ub(useTf) = ub;
            end
        end

        function useTf = getUseTfForVariable(obj)
            useTf = [obj.varRollConst obj.varRollLin obj.varRollAccel, ...
                     obj.varPitchConst obj.varPitchLin obj.varPitchAccel, ...
                     obj.varYawConst obj.varYawLin obj.varYawAccel, ...
                     obj.varTimeOffset];

            useTf = logical(useTf);
        end

        function setUseTfForVariable(obj, useTf)
            obj.varRollConst = useTf(1);
            obj.varRollLin = useTf(2);
            obj.varRollAccel = useTf(3);

            obj.varPitchConst = useTf(4);
            obj.varPitchLin = useTf(5);
            obj.varPitchAccel = useTf(6);

            obj.varYawConst = useTf(7);
            obj.varYawLin = useTf(8);
            obj.varYawAccel = useTf(9);

            obj.varTimeOffset = useTf(10);
        end

        function updateObjWithVarValue(obj, x)
            ind = 1;

            if(obj.varRollConst)
                obj.varObj.rollModel.constTerm = x(ind);
                ind = ind + 1;
            end
            if(obj.varRollLin)
                obj.varObj.rollModel.linearTerm = x(ind);
                ind = ind + 1;
            end
            if(obj.varRollAccel)
                obj.varObj.rollModel.accelTerm = x(ind);
                ind = ind + 1;
            end

            if(obj.varPitchConst)
                obj.varObj.pitchModel.constTerm = x(ind);
                ind = ind + 1;
            end
            if(obj.varPitchLin)
                obj.varObj.pitchModel.linearTerm = x(ind);
                ind = ind + 1;
            end
            if(obj.varPitchAccel)
                obj.varObj.pitchModel.accelTerm = x(ind);
                ind = ind + 1;
            end

            if(obj.varYawConst)
                obj.varObj.yawModel.constTerm = x(ind);
                ind = ind + 1;
            end
            if(obj.varYawLin)
                obj.varObj.yawModel.linearTerm = x(ind);
                ind = ind + 1;
            end
            if(obj.varYawAccel)
                obj.varObj.yawModel.accelTerm = x(ind);
                ind = ind + 1;
            end

            if(obj.varTimeOffset)
                obj.varObj.yawModel.tOffset = x(ind);
                obj.varObj.pitchModel.tOffset = x(ind);
                obj.varObj.rollModel.tOffset = x(ind);
                ind = ind + 1; %#ok<NASGU>
            end
        end

        function nameStrs = getStrNamesOfVars(obj, evtNum, varLocType)
           if(evtNum > 0)
                subStr = sprintf('Event %i',evtNum);
            else
                subStr = varLocType;
            end

            nameStrs = {sprintf('%s Roll Angle Constant', subStr), ...
                        sprintf('%s Roll Angle Rate', subStr), ...
                        sprintf('%s Roll Angle Acceleration', subStr), ...
                        sprintf('%s Pitch Constant', subStr), ...
                        sprintf('%s Pitch Rate', subStr), ...
                        sprintf('%s Pitch Acceleration', subStr), ...
                        sprintf('%s Yaw Slip Constant', subStr), ...
                        sprintf('%s Yaw Slip Rate', subStr), ...
                        sprintf('%s Yaw Slip Acceleration', subStr), ...
                        sprintf('%s Steering Time Offset', subStr)};

            nameStrs = nameStrs(obj.getUseTfForVariable());
        end

        function varsStoredInRad = getVarsStoredInRad(obj)
            varsStoredInRad = [true true true  true true true  true true true  false];
        end
    end
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
%% Equation: Poisson Equation Discretized by $BDM_1$ Element in 2D
% We explain the assembling of the matrix equation for the lowest order BDM element
% discretization of Poisson equation.
%
% [u,sigma] = PoissonBDM1(node,elem,bdEdge,f,g_D,varargin)
%
% Created by Ming Wang at Jan 2. 2011.
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

%% Data Structure
%   [elem2dof,dofSign,edge] = dofRT0(elem);
%
% will construct local to global index map; see ifem dofBDM1doc for
% details.
%
%% Local Bases
% Suppose [i,j] is the k-th edge. The hierarchic basis along with
% their div are given by
%
% $$ \phi_k = \lambda_i rot \lambda_j - \lambda_j rot \lambda_i,\quad
%    \psi_k = \lambda_i rot \lambda_j + \lambda_j rot \lambda_i. $$
%
% $$ div \phi_k = 2 \nabla \lambda_i \cdot rot \lambda_j, \quad div \psi_k = 0.$$
%
% Inside one triangular, the 6 bases functions along with their div
% corresponding to 3 local edges [2 3; 3 1; 1 2] are:
%
% $$ \phi_1 = \lambda_2 rot \lambda_3 - \lambda_3 rot \lambda_2,\quad
%    \psi_1 = \lambda_2 rot \lambda_3 + \lambda_3 rot \lambda_2,\quad
%    div\phi_1 = 2 \nabla \lambda_2 \cdot rot \lambda_3, \quad div \psi_1 = 0. $$
%
% $$ \phi_2 = \lambda_3 rot \lambda_1 - \lambda_1 rot \lambda_3,\quad
%    \psi_2 = \lambda_3 rot \lambda_1 + \lambda_1 rot \lambda_3,\quad
%    div\phi_2 = 2 \nabla \lambda_3 \cdot rot \lambda_1, \quad div \psi_2 = 0. $$
%
% $$ \phi_3 = \lambda_1 rot \lambda_2 - \lambda_2 rot \lambda_1,\quad
%    \psi_3 = \lambda_1 rot \lambda_2 + \lambda_2 rot \lambda_1,\quad
%    div\phi_3 = 2 \nabla \lambda_1 \cdot rot \lambda_2, \quad div \psi_3 = 0. $$
%
% Locally, we order the local bases in the following way:
%
% $$\{\phi_1,~\,\phi_2,~\,\phi_3,~\,\psi_1,~\,\psi_2,~\, \psi_3.\}$$
%
% Note that $RT_0 \subset BDM_1$, and $\{ \phi_1,~\,\phi_2,~\,\phi_3 \}$ is the
% local bases for $RT_0$.
%
% Because of the different oritentation of local and global faces, from
% local bases to the global one, the direction should be corrected. That is
%
%    phiGlobal(elem2dof(t,1),:) = phi(t,1)*dofSign(t,1);

%% Mass Matrix
% We use the integral formula
%
% $$ \int_T
% \lambda_1^{\alpha_1}\lambda_2^{\alpha_2}\lambda_3^{\alpha_3}
% dx = \frac{\alpha_1!\alpha_2!\alpha_3!2!}{(\sum _{i=1}^3\alpha_i
% + 2)!}\;|T|,$$
%
% to get
%
% $$ \int _T\lambda_i\lambda_j dx = (1+(i==j))|T|/12. $$
%
% For two local bases $\phi_i$ and $\phi_j$ corresponding to the ith and
% jth local edges, suppose i = [i1 i2], j = [j1 j2].
% $$\int_T \phi_i \phi_j dx = \int_T (
%  \lambda_{i1} rot \lambda_{i2}\cdot\lambda_{j1} rot \lambda_{j2}
% -\lambda_{i2} rot \lambda_{i1}\cdot\lambda_{j1} rot \lambda_{j2}
% -\lambda_{i1} rot \lambda_{i2}\cdot\lambda_{j2} rot \lambda_{j1}
% +\lambda_{i2} rot \lambda_{i1}\cdot\lambda_{j2} rot \lambda_{j1})dx
% $$
%
% $\int_T \psi_i \psi_j dx$ and $\int_T \psi_i \phi_j dx$ can be computed similarly.
%
%% Matrix for Differential Operator
% Note that $\nabla \cdot \psi = 0$, We only need to record $\nabla \cdot \phi_i$ and
% then the computation $\int _T \nabla
% \cdot \phi_i dx$ is straightforward. Just remember to correct the direction.

%% Right hand side
% We use 5-points quadrature which is exact for cubic polynomials. In the
% barycentric coordinate, the 5-points are
%
% $$ p_1 = [2/3, 1/6, 1/6], \quad  w_1 = 1/3 $$
%
% $$ p_2 = [1/6, 2/3, 1/6], \quad  w_2 = 1/3 $$
%
% $$ p_3 = [1/6, 1/6, 2/3], \quad  w_3 = 1/3 $$
%
%%
% Note that the two for loops are nested in such a way that the point pxy
% and the evulation Jp is just computed once.
%
% The local to global assembling is computed using accumarray
%
%   b = accumarray(elem2dof(:),bt(:),[Ndof 1]);

repo: Aero-matlab


text:
% This script demonstrates how to use the frequency response function.

% Initialization
clear all; close all; clc;
% We prepare the Blackman filter.
% Number of signal samples
N = 10;
% FFT length
L = 1024;
% Blackman window coefficients
w = 0.42 - 0.5*cos(2*pi*(0:N-1)/N) + 0.08 * cos (4*pi*(0:N-1)/N);
% Alternatively w = blackman(N);
% Gain normalization
w = w / sum(w);
% Spectrum of Blackman window
Wf = fft(w, L);
f = (0:L-1)/L;
% Plot the filter
options.title = 'Blackman window';
options.ylabel = 'w(n)';
options.xstep = 1;
spx.graphics.plot.discrete_signal(w, options);
% Plot the frequency response of the Blackman window
options.decibels = true;
spx.graphics.plot.frequency_response(Wf, options);

author: indigits

repo: sparse-plex


text:
function unique_num = point_unique_count ( m, n, a )

%*****************************************************************************80
%
%% POINT_UNIQUE_COUNT counts the unique points.
%
%  Discussion:
%
%    The input data is an M x N array A, representing the M-dimensional
%    coordinates of N points.
%
%    The algorithm relies on the fact that, in a sorted list, points that
%    are exactly equal must occur consecutively.
%
%    The output is the number of unique points in the list.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 July 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows.
%
%    Input, integer N, the number of columns.
%
%    Input, real A(M,N), the array of N columns of data.
%
%    Output, integer UNIQUE_NUM, the number of unique points.
%
  if ( n <= 0 )
    unique_num = 0;
    return
  end
%
%  Implicitly sort the array.
%
  indx = r8col_sort_heap_index_a ( m, n, a );
%
%  Two points are considered equal only if they exactly match.
%  In that case, equal points can only occur as consecutive items
%  in the sorted list.   This makes counting easy.
%
  unique_num = 1;
  unique_index = indx(1);

  for j = 2 : n

    if ( any ( a(1:m,unique_index) ~= a(1:m,indx(j)) ) )
      unique_num = unique_num + 1;
      unique_index = indx(j);
    end

  end

  return
end


text:
        function polyobj = coarsen_polygon(polyobj,iboubox)
            % Coarsen a polygon using a brute-force vertex reordering algorithm.
            idx = find(isnan(polyobj(:,1)));
            C = mat2cell(polyobj,diff([0;idx]),2);
            new = cell(length(C),1);
            % for each segment
            for iii = 1 : length(C)
                j = 0 ; k = 0;
                [in] = inpoly(C{iii},iboubox(1:end-1,:));
                % Initialise for speed
                new{iii} = zeros(length(C{iii}),2);
                while j < length(C{iii})-1
                    j = j + 1 ;
                    if in(j) % point is in domain keep it
                        k = k + 1;
                        new{iii}(k,:) = C{iii}(j,:);
                    else % pt is out of domain
                        bd = min([j+200,length(in)-1]) ;
                        exte = min(200,bd - j);
                        if sum(in(j:bd))==0 % if next hundred points are out, then we can decimate
                            k = k + 1 ;
                            new{iii}(k,:) = C{iii}(j,:);
                            k = k + 1 ;
                            new{iii}(k,:) = C{iii}(j+exte,:);
                            j = j + exte ;
                        else % otherwise keep
                            k = k + 1 ;
                            new{iii}(k,:) = C{iii}(j,:);
                        end

                    end
                end
                new{iii}(k+1,:) = [NaN NaN] ;
                new{iii}(k+2:end,:) = [];
            end
            polyobj = cell2mat(new);
        end

author: CHLNDDEV


text:
function [Rff,Rfp,Rpf,Rpp] = seg_R(R)
%UNTITLED7 Summary of this function goes here
%   Detailed explanation goes here
m = length(R)/10;
unkns = 4*(m-1);
Rff = R(1:end-unkns,1:end-unkns);
Rfp = R(1:end-unkns,end-unkns+1:end);
Rpf = R(end-unkns+1:end,1:end-unkns);
Rpp = R(end-unkns+1:end,end-unkns+1:end);
end

author: yorgoon

repo: minimum-snap-geometric-control


text:
function g = p06_g ( n, x )

%*****************************************************************************80
%
%% P06_G evaluates the gradient for problem 6.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 October 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of variables.
%
%    Input, real X(N), the values of the variables.
%
%    Output, real G(N), the gradient of the objective function.
%
  g = zeros ( n, 1 );

  f1 = 0.0;
  for i = 1 : n
    f1 = f1 + i * ( x(i) - 1.0 );
  end

  for i = 1 : n
    df1dxi = i;
    df2dxi = 2.0 * ( x(i) - 1.0 );
    g(i) = ( 2.0 * f1 + 4.0 * f1^3 ) * df1dxi + df2dxi;
  end

  return
end


text:
function [transParameters,nu,lambda]=igarch_transform(parameters,p,q,errorType,constant)
% IGARCH(P,Q) parameter transformation.  Used to map parameters from a IGARCH
% process to the positive unit simplex. Used in the estimation of IGARCH.
%
% USAGE:
%   [TRANSPARAMETERS,NU,LAMBDA]=igarch_transform(PARAMETERS,P,Q,ERRORTYPE,CONSTANT)
%
% INPUTS:
%   PARAMETERS       - Column parameter vector
%   P                - Positive, scalar integer representing the number of
%                      symmetric innovations
%   Q                - Non-negative, scalar integer representing the number
%                      of lags of conditional variance (0 for ARCH)
%   ERRORTYPE       - One of:
%                        1 - Gaussian Innovations
%                        2 - T-distributed errors
%                        3 - Generalized Error Distribution
%                        4 - Skewed T distribution
%   CONSTANT         - 1 if model includes a constant, 0 otherwise
%
% OUTPUTS:
%   TRANSPARAMETERS - A CONSTANT+p+q-1 column vector of transformed parameters corresponding to
%                      [omega,alpha(1),...,alpha(p) beta1 ... beta(q-1)]'
%                      where the final beta has been excluded
%   NU               - Distribution kurtosis parameter, empty if not applicable
%   LAMBDA           - Distribution asymmetry parameter, empty if not applicable
%
% COMMENTS:
%   Input parameters must satisfy:
%    (1) omega > 0
%    (2) alpha(i) >= 0 for i = 1,2,...,p
%    (3) beta(i)  >= 0 for i = 1,2,...,q
%    (4) sum(alpha(i) + beta(j)) = 1 for i = 1,2,...p and j = 1,2,...q
%    (5) nu>2 of Students T and nu>1 for GED
%    (6) -.99<lambda<.99 for Skewed T
%
% See also IGARCH

% Copyright: Kevin Sheppard
% kevin.sheppard@economics.ox.ac.uk
% Revision: 3    Date: 9/1/2005

%Constraints are omega>0
%nu>2.01 or 1.01
%-.99<lambda<.99
% alpha>0
% gamma>-alpha(i)
% beta>0
% sum(alpha)+0.5sum(gamma)+sum(beta)<1

nu=[];
lambda=[];

%Handle nu, >2.01 in the case of a T, 1.01<nu<50 in the case of a GED
%T uses square, ged uses a logistic
if errorType==2 || errorType==4
    nu=parameters(p+q+constant);
    nu=sqrt(nu-2.01);
elseif errorType==3
    nu=parameters(p+q+constant);
    temp=(nu-1)/49;
    nu=log(temp/(1-temp));
end

%Lambda must be between -.99 and .99.  Use a logistic
if errorType==4
    lambda=parameters(p+q+constant+1);
    temp=(lambda+0.995)/1.99;
    lambda=log(temp/(1-temp));
end

%Use log transform for omega
if constant
    omega=parameters(1);
    tomega=log(omega);
else
    tomega = [];
end

%Parse the parameters
alpha=parameters(constant+1:p+constant);
beta=parameters(constant+p+1:constant+p+q-1);

%Upper bound to keep it a bit away from 1
UB=.999998;

%Check that the parameters satisfy the necessary constraints
if isempty(beta)
    sumbeta = 0;
else
    sumbeta = sum(beta);
end
if  any(alpha<0) || any(beta<0) || (sum(alpha)+sumbeta)>=UB
    error('These do not conform to the necessary set of restrictions to be transformed.')
end

%Finally, must be certain that none of the parameters are exactly zero, and
%that the alpha2+gamma2>0
alpha(alpha==0)=1e-8;
beta(beta==0)=1e-8;

%Finally, up the upper bound a tiny bit
UB=UB+1e-8*(p+q);

%Set the scale
scale=UB;
%Initialze the transformed alpha
talpha=alpha;
for i=1:p
    %Scale the alpha
    talpha(i)=alpha(i)./scale;
    %Use an inverse logistic
    talpha(i)=log(talpha(i)./(1-talpha(i)));
    %Update the scale
    scale=scale-alpha(i);
end

if q>1
    %Initialize the beta
    tbeta=beta;
    %Iterate over betas
    for i=1:(q-1)
        %Scale the betas
        tbeta(i)=tbeta(i)./scale;
        %Use an inverse logistic
        tbeta(i)=log(tbeta(i)./(1-tbeta(i)));
        %Update the scale
        scale=scale-beta(i);
    end
else
    tbeta = [];
end

%Regroup the parameters
transParameters=[tomega;talpha;tbeta];

author: bashtage

repo: mfe-toolbox


text:
function val = ctrGet(ctr,param,varargin)
% Retrieve data from ConTrack structure
%
%  val = ctrGet(ctr,param,varargin)
%
% Read the parameters of a ctr structure.
% Access this structure should go through this routine and through
%   ctrSet.
%
% Parameters:
%
%
%

if notDefined('ctr'), error('No ConTrack structure defined.'); end
if notDefined('param'), error('No parameter defined'); end

val = [];

switch lower(param)
    case {'version'}
        val = ctr.version;
    case {'name'}
        val = ctr.name;
    case {'type'}
        val = ctr.type;
    case {'image_directory'}
        val = ctr.image_directory;
    case {'tensors_filename'}
        val = ctr.tensors_filename;
    case {'fa_filename'}
        val = ctr.fa_filename;
    case {'pdf_filename'}
        val = ctr.pdf_filename;
    case {'mask_filename'}
        val = ctr.mask_filename;
    case {'xmask_filename'}
        val = ctr.Xmask_filename;
    case {'require_way'}
        val = ctr.require_way;
    case {'compute_fa'}
        val = ctr.compute_fa;
    case {'sampler_type'}
        val = ctr.sampler_type;
    case {'desired_samples'}
        val = ctr.desired_samples;
    case {'burnin'}
        val = ctr.burnin;
    case {'max_nodes'}
        val = ctr.max_nodes;
    case {'min_nodes'}
        val = ctr.min_nodes;
    case {'step_size'}
        val = ctr.step_size;
    case {'skip_samples'}
        val = ctr.skip_samples;
    case {'roi'}
        if length(varargin) ~= 2, error('Incomplete ctrGet for ROI'); end
        arg1 = varargin{1};
        arg2 = varargin{2};
        switch lower(arg2)
            case {'coords'}
                val = ctr.roi{arg1}.coords;
            case {'valid_cortex'}
                val = ctr.roi{arg1}.valid_cortex;
            case {'seed_region'}
                val = ctr.roi{arg1}.seed_region;
        end
    case {'translate'}
        val = ctr.translate;
    case {'isr'}
        val = ctr.isr;
    case {'esr'}
        val = ctr.esr;
    case {'temp_swap'}
        val = ctr.temp_swap;
    case {'inv_temp'}
        val = ctr.inv_temp;
    case {'start_path_tries'}
        val = ctr.start_path_tries;
    case {'save_out_spacing'}
        val = ctr.save_out_spacing;
    case {'fa_absorb'}
        val = ctr.fa_absorb;
    case {'abs_normal'}
        val = ctr.abs_normal;
    case {'abs_penalty'}
        val = ctr.abs_penalty;
    case {'smooth_std'}
        val = ctr.smooth_std;
    case {'angle_cutoff'}
        val = ctr.angle_cutoff;
    case {'shape_params_vec'}
        val = ctr.shape_params_vec;
end

return;


text:
function plot_recall_voc07()
  % Plot the recall of pascal test set ground truth for all methods.
  %
  % This function requires the proposals to already be saved to disk. It will
  % compute a matching between ground truth and proposals (if the result is not
  % yet found on disk) and then plot recall curves. The plots are saved to
  % figures/.

  testset = load('data/pascal_voc07_test_annotations.mat');
  methods = get_method_configs();
  methods([14 16 19:25]) = [];

  compute_best_candidates(testset, methods);

  plot_legend(methods);
  printpdf('figures/recall_legend.pdf');

  fh = figure;
  plot_overlap_recall_curve({methods.best_voc07_candidates_file}, methods, 100, fh, true, 'none');
  hei = 10;
  wid = 10;
  set(gcf, 'Units','centimeters', 'Position',[0 0 wid hei]);
  set(gcf, 'PaperPositionMode','auto');
  printpdf('figures/recall_100.pdf')

  fh = figure;
  plot_overlap_recall_curve({methods.best_voc07_candidates_file}, methods, 1000, fh, false, 'none');
  hei = 10;
  wid = 10;
  set(gcf, 'Units','centimeters', 'Position',[0 0 wid hei]);
  set(gcf, 'PaperPositionMode','auto');
  printpdf('figures/recall_1000.pdf')

  fh = figure;
  plot_overlap_recall_curve({methods.best_voc07_candidates_file}, methods, 10000, fh, false, 'none');
  hei = 10;
  wid = 10;
  set(gcf, 'Units','centimeters', 'Position',[0 0 wid hei]);
  set(gcf, 'PaperPositionMode','auto');
  printpdf('figures/recall_10000.pdf')

  plot_num_candidates_auc({methods.best_voc07_candidates_file}, methods);
end

function compute_best_candidates(testset, methods)
  num_annotations = numel(testset.pos);
  candidates_thresholds = round(10 .^ (0:0.5:4));
  num_candidates_thresholds = numel(candidates_thresholds);

  for method_idx = 1:numel(methods)
    method = methods(method_idx);
    try
      load(method.best_voc07_candidates_file, 'best_candidates');
      continue
    catch
    end

    % preallocate
    best_candidates = [];
    best_candidates(num_candidates_thresholds).candidates_threshold = [];
    best_candidates(num_candidates_thresholds).best_candidates = [];
    for i = 1:num_candidates_thresholds
      best_candidates(i).candidates_threshold = candidates_thresholds(i);
      best_candidates(i).best_candidates.candidates = zeros(num_annotations, 4);
      best_candidates(i).best_candidates.iou = zeros(num_annotations, 1);
      best_candidates(i).image_statistics(numel(testset.impos)).num_candidates = 0;
    end

    pos_range_start = 1;
    for j = 1:numel(testset.impos)
      tic_toc_print('evalutating %s: %d/%d\n', method.name, j, numel(testset.impos));
      pos_range_end = pos_range_start + size(testset.impos(j).boxes, 1) - 1;
      assert(pos_range_end <= num_annotations);

      tic_toc_print('sampling candidates for image %d/%d\n', j, numel(testset.impos));
      [~,img_id,~] = fileparts(testset.impos(j).im);

      for i = 1:num_candidates_thresholds
        [candidates, scores] = get_candidates(method, img_id, ...
          candidates_thresholds(i));
        if isempty(candidates)
          impos_best_ious = zeros(size(testset.impos(j).boxes, 1), 1);
          impos_best_boxes = zeros(size(testset.impos(j).boxes, 1), 4);
        else
          [impos_best_ious, impos_best_boxes] = closest_candidates(...
            testset.impos(j).boxes, candidates);
        end

        best_candidates(i).best_candidates.candidates(pos_range_start:pos_range_end,:) = impos_best_boxes;
        best_candidates(i).best_candidates.iou(pos_range_start:pos_range_end) = impos_best_ious;
        best_candidates(i).image_statistics(j).num_candidates = size(candidates, 1);
      end

      pos_range_start = pos_range_end + 1;
    end

    save(method.best_voc07_candidates_file, 'best_candidates');
  end
end

author: hosang

repo: detection-proposals


text:
function [y,cl,cu] = checkIpoptConstraints(x, constraint)
    % nested function that commputes the constraints of the NLP problem
    %
    % Parameters:
    %  constraint: a structure of arrays that contains the information
    %  of all constraints

    cl = vertcat(constraint.LowerBound);
    cu = vertcat(constraint.UpperBound);
    % preallocation
    y   = zeros(constraint.Dimension,1);
    for i = 1:constraint.numFuncs
        var = cellfun(@(v)x(v(:)),constraint.DepIndices{i},'UniformOutput',false); % dependent variables

        % calculate constraints
        if isempty(constraint.AuxData{i})
            y(constraint.FuncIndices{i}) = y(constraint.FuncIndices{i}) + feval(constraint.Funcs{i}, var{:});
        else
            y(constraint.FuncIndices{i})  = y(constraint.FuncIndices{i}) + feval(constraint.Funcs{i}, var{:}, constraint.AuxData{i}{:});
        end
    end

end

author: ayonga

repo: frost-dev

save_path: github-repos/MATLAB/ayonga-frost-dev


text:
function q=v_qrdivide(q1,q2)
%V_QRDIVIDE divdes two real quaternions q=[q1,q2]
%
% Inputs:
%
%     q1(4,1), q2(4,1)  Two real quaternions in the form [r, i, j, k]' where i^2=j^2=k^2=ijk=-1
%
% Outputs:
%
%     q(4,1)   Quotient of q1/q2 such that q1=q*q2.
%              Note that q*q2 ~= q2*q since quaternion multiplication does not commute.

%      Copyright (C) Mike Brookes 2000-2008
%      Version: $Id: v_qrdivide.m 10865 2018-09-21 17:22:45Z 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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent a b c d
if isempty(a)
    a=[5 8 9 10 15 13];
    b=[6 7 11 12 14 16];
    c=[1 2 3 4 6 7 11 12 16 14];
    d=[1 2 3 4 5 8 9 10 13 15];
end
if nargin<2
    %    just take the inverse of the only input argument
    q=q1/(q1'*q1);
    q(2:4)=-q(2:4);
else
    %    invert q2 and do a multiply
    q=q2/(q2'*q2);
    q(2:4)=-q(2:4);
    t=q1*q.';
    s=zeros(4,4);
    s(a)=-t(b);
    s(c)=t(d);
    q=sum(s,2);
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function probRuin = calcProbRuin(EquitySAVal)
% A helper function that calculates the probability of ruin given the
% account values.

probRuin = sum(min(EquitySAVal) == 0) / size(EquitySAVal, 2);
end

author: Sable

repo: mcbench-benchmarks


text:
function W = SimGraph_Full(M, sigma)
% SIMGRAPH_FULL Returns full similarity graph
%   Returns adjacency matrix for a full similarity graph where
%   a Gaussian similarity function with parameter sigma is
%   applied.
%
%   'M' - A d-by-n matrix containing n d-dimensional data points
%   'sigma' - Parameter for Gaussian similarity function
%
%   Author: Ingo Buerk
%   Year  : 2011/2012
%   Bachelor Thesis

% Compute distance matrix
W = squareform(pdist(M'));

% Apply Gaussian similarity function
W = simGaussian(W, sigma);

end

author: beckel

repo: nilm-eval

save_path: github-repos/MATLAB/beckel-nilm-eval


text:
function [k, sk, n2] = ratquadKernCompute(kern, x, x2)

% RATQUADKERNCOMPUTE Compute the RATQUAD kernel given the parameters and X.
% FORMAT
% DESC computes the kernel parameters for the rational quadratic
% kernel given inputs associated with rows and columns.
% ARG kern : the kernel structure for which the matrix is computed.
% ARG x : the input matrix associated with the rows of the kernel.
% ARG x2 : the input matrix associated with the columns of the kernel.
% RETURN k : the kernel matrix computed at the given points.
%
% FORMAT
% DESC computes the kernel matrix for the rational quadratic
% kernel given a design matrix of inputs.
% ARG kern : the kernel structure for which the matrix is computed.
% ARG x : input data matrix in the form of a design matrix.
% RETURN k : the kernel matrix computed at the given points.
%
% SEEALSO : ratquadKernParamInit, kernCompute, kernCreate, ratquadKernDiagCompute
%
% COPYRIGHT : Neil D. Lawrence, 2006, 2009

% KERN

wi2 = .5/(kern.lengthScale*kern.lengthScale*kern.alpha);
if nargin < 3
  n2 = dist2(x, x);
else
  n2 = dist2(x, x2);
end
sk = (1+n2*wi2).^-kern.alpha;
k = kern.variance*sk;

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function scores = PascalOverlap(targetBox, testBoxes)
% scores = PascalOverlap(targetBox, testBoxes)
%
% Function obtains the pascal overlap scores between the targetBox and
% all testBoxes
%
% targetBox:            1 x 4 array containing target box
% testBoxes:            N x 4 array containing test boxes
%
% scores:               N x 1 array containing for each testBox the pascal
%                       overlap score.
%
%     Jasper Uijlings - 2013

intersectBoxes = BoxIntersection(targetBox, testBoxes);
overlapI = intersectBoxes(:,1) ~= -1; % Get which boxes overlap

% Intersection size
[nr nc intersectionSize] = BoxSize(intersectBoxes(overlapI,:));

% Union size
[nr nc testBoxSize] = BoxSize(testBoxes(overlapI,:));
[nr nc targetBoxSize] = BoxSize(targetBox);
unionSize = testBoxSize + targetBoxSize - intersectionSize;

scores = zeros(size(testBoxes,1),1);
scores(overlapI) = intersectionSize ./ unionSize;

author: zouchuhang

repo: LayoutNet


text:
function test01 ( input_file_name )

%*****************************************************************************80
%
%% TEST01 tests STLA_CHECK.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 September 2005
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST01\n' );
  fprintf ( 1, '  STLA_CHECK makes some simple checks on a file.\n' );

  fprintf ( 1, '\n' );
  if ( stla_check ( input_file_name ) )
    fprintf ( 1, ...
      '  The file "%s" seems to be a legal ASCII STL file.\n', ...
      input_file_name );
  else
    fprintf ( 1, ...
      '  The file "%s" does NOT seem to be a legal ASCII STL file.\n', ...
      input_file_name );
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function t=timediff(t1,t2)

t=t1.time-t2.time+t1.sec-t2.sec;

return

repo: GINav


text:
function r8sp_print_some ( m, n, nz_num, isym, row, col, a, ilo, jlo, ihi, ...
  jhi, title )

%*****************************************************************************80
%
%% R8SP_PRINT_SOME prints some of a R8SP matrix.
%
%  Discussion:
%
%    This version of R8SP_PRINT_SOME has been specifically modified to allow,
%    and correctly handle, the case in which a single matrix location
%    A(I,J) is referenced more than once by the sparse matrix structure.
%    In such cases, the routine prints out the sum of all the values.
%
%    The R8SP storage format stores the row, column and value of each nonzero
%    entry of a sparse matrix.
%
%    It is possible that a pair of indices (I,J) may occur more than
%    once.  Presumably, in this case, the intent is that the actual value
%    of A(I,J) is the sum of all such entries.  This is not a good thing
%    to do, but I seem to have come across this in MATLAB.
%
%    The R8SP format is used by CSPARSE ("sparse triplet"), DLAP/SLAP
%    ("nonsymmetric SLAP triad"), by MATLAB, and by SPARSEKIT ("COO" format).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 January 2014
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns of the matrix.
%
%    Input, integer NZ_NUM, the number of nonzero elements in the matrix.
%
%    Input, integer ISYM, is 0 if the matrix is not symmetric,
%    and 1 if the matrix is symmetric.  The symmetric case only makes sense
%    if the matrix is also square, that is, M = N.  In this case, only
%    the nonzeroes on the diagonal and in the lower triangle are stored.
%
%    Input, integer ROW(NZ_NUM), COL(NZ_NUM), the row and column indices
%    of the nonzero elements.
%
%    Input, real A(NZ_NUM), the nonzero elements of the matrix.
%
%    Input, integer ILO, JLO, IHI, JHI, the first row and
%    column, and the last row and column to be printed.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );

  incx = 5;
%
%  Print the columns of the matrix, in strips of 5.
%
  for j2lo = jlo: incx: jhi

    j2hi = j2lo + incx - 1;
    j2hi = min ( j2hi, n );
    j2hi = min ( j2hi, jhi );

    inc = j2hi + 1 - j2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col: ' );

    for j = j2lo : j2hi
      fprintf ( 1, '%7d       ', j );
    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row\n' );
    fprintf ( 1, '  ---\n' );
%
%  Determine the range of the rows in this strip.
%
    i2lo = max ( ilo, 1 );
    i2hi = min ( ihi, m );

    for i = i2lo : i2hi
%
%  Print out (up to) 5 entries in row I, that lie in the current strip.
%
      nonzero = 0;

      aij(1:inc) = 0.0;

      for k = 1 : nz_num

        if ( i == row(k) && j2lo <= col(k) && col(k) <= j2hi )

          j2 = col(k) - j2lo + 1;

          if ( a(k) ~= 0.0 )
            nonzero = 1;
            aij(j2) = aij(j2) + a(k);
          end

        elseif ( isym == 1 && m == n && ...
          i == col(k) && j2lo <= row(k) && row(k) <= j2hi )

          j2 = row(k) - j2lo + 1;

          if ( a(k) ~= 0.0 )
            nonzero = 1;
            aij(j2) = aij(j2) + a(k);
          end

        end

      end

      if ( nonzero )
        fprintf ( 1, '%4d', i );
        for j = 1 : inc
          fprintf ( 1, '  %12g', aij(j) );
        end
        fprintf ( 1, '\n' );
      end

    end

  end

  return
end


text:
%Author: Yong Yuan;
%Homepage: yongyuan.name

% load cifar-10 dataset
load cifar-10-batches-mat/data_batch_1.mat;
data1=data;
labels1=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_2.mat;
data2=data;
labels2=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_3.mat;
data3=data;
labels3=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_4.mat;
data4=data;
labels4=labels;
clear data labels;
load cifar-10-batches-mat/data_batch_5.mat;
data5=data;
labels5=labels;
clear data labels;
load cifar-10-batches-mat/test_batch.mat;
data6=data;
labels6=labels;
clear data labels;
database = [data1 labels1; data2 labels2; data3 labels3; data4 labels4; data5 labels5; data6 labels6];
cifar10labels = [labels1; labels2; labels3;labels4; labels5; labels6];

%method = 'show-in-random';
method = 'show-in-class';

switch(method)
    %% sort in class
    case 'show-in-class'
        [sortedLabels, index] = sort(cifar10labels);
        dataInClass = database(index, :);
        clear database;
        numShow = 100;
        numInRow = 10;
        numPerClass = 6000;
        I2 = uint8(zeros(33, 33, 3, numShow)); % 32 and 32 are the size of the output image
        for i=1:numInRow
            randID = randi(numPerClass, numInRow, 1);
            index = randID + (i-1)*numPerClass;
            for j=1:length(index)
                image_r=dataInClass(index(j,:),1:1024);
                image_g=dataInClass(index(j,:),1025:2048);
                image_b=dataInClass(index(j,:), 2049:end-1);
                image_rer = reshape(image_r, 32, 32);
                image_rer(:, end+1) = zeros(length(image_rer), 1);
                image_rer(end+1, :) = zeros(1,length(image_rer));
                image_reg = reshape(image_g, 32, 32);
                image_reg(:, end+1) = zeros(length(image_reg), 1);
                image_reg(end+1, :) = zeros(1,length(image_reg));
                image_reb = reshape(image_b, 32, 32);
                image_reb(:, end+1) = zeros(length(image_reb), 1);
                image_reb(end+1, :) = zeros(1,length(image_reb));
                image(:, :,1) = image_rer';
                image(:, :, 2) = image_reg';
                image(:, :, 3) = image_reb';
                image = uint8(image);
                I2(:, :, :, j+(i-1)*numInRow) = image;
            end
        end
        figure('Color', [1 1 1]); hold on;
        montage(I2(:, :, :, :));

    %% sort in random
    case 'show-in-random'
        numInColum = 100;
        numInRow = 100;
        numImg = 60000;
        I2 = uint8(zeros(32, 32, 3, numInRow*numInColum)); % 32 and 32 are the size of the output image
        randID = randi(numImg, numInRow*numInColum, 1);
        for i=1:numInRow
            for j=1:numInColum
                % sort with random
                image_r=database(randID(j+(i-1)*numInColum,:),1:1024);
                image_g=database(randID(j+(i-1)*numInColum,:),1025:2048);
                image_b=database(randID(j+(i-1)*numInColum,:), 2049:end-1);

                image_rer=reshape(image_r, 32, 32);
                image_reg=reshape(image_g, 32, 32);
                image_reb=reshape(image_b, 32, 32);
                image(:, :,1)=image_rer';
                image(:, :, 2)=image_reg';
                image(:, :, 3)=image_reb';
                image=uint8(image);
                I2(:, :, :, j+(i-1)*numInColum) = image;
            end
        end
        figure('Color', [1 1 1]); hold on;
        montage(I2(:, :, :, :));
end

author: willard-yuan

repo: hashing-baseline-for-image-retrieval


text:
function varargout = fname(varargin)
% Format
% For getting the value
% dat = fname(obj)
%
% For setting the value
% obj = fname(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id$

if nargin==2,
    varargout{1} = asgn(varargin{:});
elseif nargin==1,
    varargout{1} = ref(varargin{:});
else
    error('Wrong number of arguments.');
end;
return;

function dat = ref(obj)
dat = obj.fname;
return;

function obj = asgn(obj,dat)
if ischar(dat)
    obj.fname = deblank(dat(:)');
else
    error('"fname" must be a character string.');
end;
return;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip