text:
function varargout = resultManager(varargin)
% RESULTMANAGER MATLAB code for resultManager.fig
%      RESULTMANAGER, by itself, creates a new RESULTMANAGER or raises the existing
%      singleton*.
%
%      H = RESULTMANAGER returns the handle to a new RESULTMANAGER or the handle to
%      the existing singleton*.
%
%      RESULTMANAGER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RESULTMANAGER.M with the given input arguments.
%
%      RESULTMANAGER('Property','Value',...) creates a new RESULTMANAGER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before resultManager_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to resultManager_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help resultManager
% Last Modified by GUIDE v2.5 13-Jul-2013 16:20:41
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of OLPS: http://OLPS.stevenhoi.org/
% Original authors: Doyen Sahoo
% Contributors: Bin LI, Steven C.H. Hoi
% Change log:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @resultManager_OpeningFcn, ...
                   'gui_OutputFcn',  @resultManager_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before resultManager is made visible.
function resultManager_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to resultManager (see VARARGIN)

    % Read the 6 parameters
    handles.returns_daily = varargin{1};
    handles.returns = cumprod(handles.returns_daily+1 );
    handles.portfolio = varargin{2};
    handles.stats = varargin{3};
    handles.benchmarks = varargin{4};
    handles.benchmarks_daily = varargin{5}-1;
    handles.algorithmName = varargin{6};
    handles.frequency = varargin{7};
    [handles.r handles.c] = size(handles.portfolio);

    % Clear old values
    clearRadio(handles, [] , handles);
    set(handles.day,'String', 1);

    % Initial display
    cumReturns = [handles.benchmarks handles.returns];
    dailyReturns = [handles.benchmarks_daily handles.returns_daily];
    set(handles.rd_cumulativeReturns,'Value', 1);
	plot(handles.mainGraph, cumReturns);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend(handles.mainGraph, 'Uniform BAH', 'Uniform CRP', 'Best Stock', 'Best CRP', handles.algorithmName, 'Location', 'Best');
    grid on;

    % Compute the statsand display the important numbers in table using the
    % library functions
    addpath('./lib');

    % Get final Values
    [r c] = size(cumReturns);
    handles.finalValues = cumReturns(r,:);

    % Get the mean returnfor every day - This is a simple average
    handles.meanReturns = mean(dailyReturns);

    % Get annualised returns
    denominator = 252/handles.frequency;
    Y = r/denominator;
    handles.annualisedReturns = handles.finalValues.^(1/Y)-1;

    % Get standard deviation- a measureof risk
    handles.standardDeviation = std(dailyReturns);

    % Get annualised standard deviation
    handles.annualisedStandardDeviation = handles.standardDeviation * sqrt(denominator);

    % Get sharpe ratios
    handles.sharpeRatios = sharpe(dailyReturns, handles.finalValues,handles.frequency);

    % Get Sortino ratios                                                   %%%%%%%%%%%%%%% DO NOT KNOW HOW TO ANNUALIZE
    handles.sortinoRatios = sortino(dailyReturns, 0);

    % Get Value risks at level 5%
    handles.valueAtRisks = var5(dailyReturns);

    % Get Maximum draw down
    handles.mdds = maxDD_general(cumReturns);

    % Get Calmar ratios
    handles.calmars = calmar(cumReturns, handles.mdds, handles.frequency);

    % Fill up the tables
    tableData = [handles.finalValues; handles.meanReturns; handles.annualisedReturns; handles.standardDeviation; handles.annualisedStandardDeviation; handles.sharpeRatios; handles.calmars; handles.sortinoRatios; handles.valueAtRisks; handles.mdds];
    set(handles.table,'Data',tableData);

    rmpath('./lib');

    guidata(hObject, handles);

% Choose default command line output for resultManager
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes resultManager wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = resultManager_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on button press in watchAnimation.
function watchAnimation_Callback(hObject, eventdata, handles)
% hObject    handle to watchAnimation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

    window =  str2double(get(handles.windowAnimation,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);

    try
        animation(handles.portfolio, window);
    catch exception
        disp('Animation closed before completion');
    end

function windowAnimation_Callback(hObject, eventdata, handles)
% hObject    handle to windowAnimation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of windowAnimation as text
%        str2double(get(hObject,'String')) returns contents of windowAnimation as a double

% --- Executes during object creation, after setting all properties.
function windowAnimation_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowAnimation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in rd_portfolioConcentration.
function rd_portfolioConcentration_Callback(hObject, eventdata, handles)
% hObject    handle to rd_portfolioConcentration (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

    clearRadio(handles, [] , handles);
    set(handles.rd_portfolioConcentration,'Value', 1);

    portfolio = handles.portfolio;
    expected = mean(portfolio);
    deviation = std(portfolio);

    errorbar(handles.mainGraph, expected, deviation, 'xr');

    xlim(handles.mainGraph, [0 handles.c+1]);

% Hint: get(hObject,'Value') returns toggle state of rd_portfolioConcentration

% --- Executes on button press in rd_stepByStep.
function rd_stepByStep_Callback(hObject, eventdata, handles)
% hObject    handle to rd_stepByStep (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_stepByStep,'Value', 1);
    [r c] = size(handles.portfolio);
    bar(handles.portfolio(1,:));
    set(handles.day,'String', 1);
    xlim(handles.mainGraph, [0 handles.c+1]);
    ylim(handles.mainGraph, [-0.1 1.1]);
    grid on;
% Hint: get(hObject,'Value') returns toggle state of rd_stepByStep

% --- Executes on button press in previous.
function previous_Callback(hObject, eventdata, handles)
% hObject    handle to previous (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    [r c] = size(handles.portfolio);
    day = str2double(get(handles.day,'string'));
    if get(handles.rd_stepByStep,'Value') == 1 && day <= r && (day-1) >= 1
        bar(handles.portfolio(day-1,:));
        set(handles.day,'String', (day-1));
        xlim(handles.mainGraph, [0 handles.c+1]);
        ylim(handles.mainGraph, [-0.1 1.1]);
        grid on;
    end

% --- Executes on button press in next.
function next_Callback(hObject, eventdata, handles)
% hObject    handle to next (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

    [r c] = size(handles.portfolio);
    day = str2double(get(handles.day,'string'));
    if get(handles.rd_stepByStep,'Value') == 1 && day >= 1 && (day+1) <= r
        bar(handles.portfolio(day+1,:));
        set(handles.day,'String', (day+1));
        xlim(handles.mainGraph, [0 handles.c+1]);
        ylim(handles.mainGraph, [-0.1 1.1]);
        grid on;
    end

% --- Executes on button press in go.
function go_Callback(hObject, eventdata, handles)
% hObject    handle to go (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

    % Reads the day number in the inputbox and changes barchart to
    % represent that day - 2 conditions - day must lie in range, step by
    % step is selected
    [r c] = size(handles.portfolio);
    day = str2double(get(handles.day,'string'));
    if get(handles.rd_stepByStep,'Value') == 1 && day >= 1 && day <= r
        bar(handles.portfolio(day,:));
        xlim(handles.mainGraph, [0 handles.c+1]);
        ylim(handles.mainGraph, [-0.1 1.1]);
        grid on;
    end

% Hint: get(hObject,'Value') returns toggle state of rd_animation

% --- Executes on button press in rd_sharpe.
function rd_sharpe_Callback(hObject, eventdata, handles)
% hObject    handle to rd_sharpe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_sharpe,'Value', 1);

    window = str2double(get(handles.windowSharpe,'string'));

    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);

    addpath('./lib');

    [r c] = size(handles.returns_daily);
    sharpeRatios = zeros(r,1);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        sharpeRatios(i) = sharpe(handles.returns_daily(start:finish), handles.returns(finish)/handles.returns(start), handles.frequency);
    end

    rmpath('./lib');

    plot(handles.mainGraph, sharpeRatios);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend('Sharpe Ratio', 'Location', 'Best');

% Hint: get(hObject,'Value') returns toggle state of rd_sharpe

function windowSharpe_Callback(hObject, eventdata, handles)
% hObject    handle to windowSharpe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of windowSharpe as text
%        str2double(get(hObject,'String')) returns contents of windowSharpe as a double

% --- Executes during object creation, after setting all properties.
function windowSharpe_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowSharpe (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in rd_calmar.
function rd_calmar_Callback(hObject, eventdata, handles)
% hObject    handle to rd_calmar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_calmar,'Value', 1);

    window = str2double(get(handles.windowCalmar,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);

    addpath('./lib');

    [r c] = size(handles.returns_daily);
    calmarRatios = zeros(r,1);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        mdd = maxDD(handles.returns(start:finish));
        calmarRatios(i) = calmar(handles.returns(start:finish), mdd, handles.frequency);
    end

    rmpath('./lib');

    plot(handles.mainGraph, calmarRatios);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend('Calmar Ratio', 'Location', 'Best');

% Hint: get(hObject,'Value') returns toggle state of rd_calmar

% --- Executes on button press in rd_var.
function rd_var_Callback(hObject, eventdata, handles)
% hObject    handle to rd_var (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_var,'Value', 1);

    window = str2double(get(handles.windowVar,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);

    addpath('./lib');

    [r c] = size(handles.returns_daily);
    vars = zeros(r,1);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        vars(i) = var5(handles.returns_daily(start:finish));
    end

    rmpath('./lib');

    plot(handles.mainGraph, vars);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend('Value At Risk 5%', 'Location', 'Best');

% Hint: get(hObject,'Value') returns toggle state of rd_var

function windowCalmar_Callback(hObject, eventdata, handles)
% hObject    handle to windowCalmar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of windowCalmar as text
%        str2double(get(hObject,'String')) returns contents of windowCalmar as a double

% --- Executes during object creation, after setting all properties.
function windowCalmar_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowCalmar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in rd_mdd.
function rd_mdd_Callback(hObject, eventdata, handles)
% hObject    handle to rd_mdd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_mdd,'Value', 1);

    window = str2double(get(handles.windowMDD,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);

    addpath('./lib');

    [r c] = size(handles.returns_daily);
    mdds = zeros(r,1);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        mdds(i) = maxDD(handles.returns(start:finish));
    end

    rmpath('./lib');

    plot(handles.mainGraph, mdds);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend('Maximum Draw Down', 'Location', 'Best');

% Hint: get(hObject,'Value') returns toggle state of rd_mdd

% --- Executes on button press in rd_sortino.
function rd_sortino_Callback(hObject, eventdata, handles)
% hObject    handle to rd_sortino (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_sortino,'Value', 1);

    window = str2double(get(handles.windowSortino,'string'));
    if isnan(window) || window < 2
        errorMessage('Window size must be a number greater than or equal to 2');
        return;
    end
    window = round(window);

    addpath('./lib');

    [r c] = size(handles.returns_daily);
    sortinos = zeros(r,1);
    for i = 50:1:r
        start = max(i-window+1, 1);
        finish = i;
        sortinos(i) = sortino(handles.returns_daily(start:finish),0);
    end

    rmpath('./lib');

    plot(handles.mainGraph, sortinos);
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend('Sortino Ratio', 'Location', 'Best');

% Hint: get(hObject,'Value') returns toggle state of rd_sortino

function windowSortino_Callback(hObject, eventdata, handles)
% hObject    handle to windowSortino (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of windowSortino as text
%        str2double(get(hObject,'String')) returns contents of windowSortino as a double

% --- Executes during object creation, after setting all properties.
function windowSortino_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowSortino (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in rd_cumulativeReturns.
function rd_cumulativeReturns_Callback(hObject, eventdata, handles)
% hObject    handle to rd_cumulativeReturns (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_cumulativeReturns,'Value', 1);
    logCheck = get(handles.logPlot, 'Value');
    if logCheck == 1
        semilogy([ handles.benchmarks handles.returns]);
    else
        plot([ handles.benchmarks handles.returns]);
    end
    xlim(handles.mainGraph, [0 handles.r+1]);
    legend(handles.mainGraph ,'Uniform BAH', 'Uniform CRP', 'Best Stock', 'Best CRP', handles.algorithmName, 'Location', 'Best');
    grid on;
% Hint: get(hObject,'Value') returns toggle state of rd_cumulativeReturns

% --- Executes on button press in rd_dailyReturns.
function rd_dailyReturns_Callback(hObject, eventdata, handles)
% hObject    handle to rd_dailyReturns (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    clearRadio(handles, [] , handles);
    set(handles.rd_dailyReturns,'Value', 1);
    bar(handles.mainGraph, handles.returns_daily);
    xlim(handles.mainGraph, [0 handles.r+1]);
% Hint: get(hObject,'Value') returns toggle state of rd_dailyReturns

function clearRadio(hObject, eventdata, handles)
% The function is a helper function to uncheck all radio buttons

    set(handles.rd_cumulativeReturns,'Value', 0);
    set(handles.rd_dailyReturns,'Value', 0);
    set(handles.rd_sharpe,'Value', 0);
    set(handles.rd_calmar,'Value', 0);
    set(handles.rd_sortino,'Value', 0);
    set(handles.rd_var,'Value', 0);
    set(handles.rd_mdd,'Value', 0);
    set(handles.rd_portfolioConcentration,'Value', 0);
    set(handles.rd_stepByStep,'Value', 0);

function day_Callback(hObject, eventdata, handles)
% hObject    handle to day (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of day as text
%        str2double(get(hObject,'String')) returns contents of day as a double

% --- Executes during object creation, after setting all properties.
function day_CreateFcn(hObject, eventdata, handles)
% hObject    handle to day (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in logPlot.
function logPlot_Callback(hObject, eventdata, handles)
% hObject    handle to logPlot (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of logPlot

    % Check if user wants to see cumulative returns
    selected  = get(handles.rd_cumulativeReturns,'Value');

    % only if user wants to see the cumulative returns
    if selected == 1
        logCheck = get(handles.logPlot,'Value');

        if logCheck == 1
            semilogy([ handles.benchmarks handles.returns]);
        else
            plot([ handles.benchmarks handles.returns]);
        end
        xlim(handles.mainGraph, [0 handles.r+1]);
        legend(handles.mainGraph ,'Uniform BAH', 'Uniform CRP', 'Best Stock', 'Best CRP', handles.algorithmName, 'Location', 'Best');
        grid on;
    end

function windowVar_Callback(hObject, eventdata, handles)
% hObject    handle to windowVar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of windowVar as text
%        str2double(get(hObject,'String')) returns contents of windowVar as a double

% --- Executes during object creation, after setting all properties.
function windowVar_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowVar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function windowMDD_Callback(hObject, eventdata, handles)
% hObject    handle to windowMDD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of windowMDD as text
%        str2double(get(hObject,'String')) returns contents of windowMDD as a double

% --- Executes during object creation, after setting all properties.
function windowMDD_CreateFcn(hObject, eventdata, handles)
% hObject    handle to windowMDD (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

author: OLPS

repo: OLPS

save_path: github-repos/MATLAB/OLPS-OLPS


text:
function [ x, w ] = rule06 ( n )

%*****************************************************************************80
%
%% RULE06 returns the rule of degree 6.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 July 2014
%
%  Author:
%
%    Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.
%    This MATLAB version by John Burkardt.
%
%  Reference:
%
%    Hong Xiao, Zydrunas Gimbutas,
%    A numerical algorithm for the construction of efficient quadrature
%    rules in two and higher dimensions,
%    Computers and Mathematics with Applications,
%    Volume 59, 2010, pages 663-676.
%
%  Parameters:
%
%    Input, integer N, the number of nodes.
%
%    Output, real X(2,N), the coordinates of the nodes.
%
%    Output, real W(N), the weights.
%
  xs = [ ...
    0.4595981103653579E-16, ...
    0.9258200997725515E+00, ...
    0.6742045114073804E-16, ...
   -0.9258200997725515E+00, ...
   -0.3805544332083157E+00, ...
    0.3805544332083157E+00, ...
    0.3805544332083157E+00, ...
   -0.3805544332083157E+00, ...
   -0.8059797829185990E+00, ...
    0.8059797829185988E+00, ...
    0.8059797829185990E+00, ...
   -0.8059797829185988E+00 ];
  ys = [ ...
   -0.9258200997725515E+00, ...
   -0.1073032005210112E-16, ...
    0.9258200997725515E+00, ...
    0.1241105822293750E-15, ...
   -0.3805544332083157E+00, ...
   -0.3805544332083157E+00, ...
    0.3805544332083157E+00, ...
    0.3805544332083157E+00, ...
   -0.8059797829185988E+00, ...
   -0.8059797829185990E+00, ...
    0.8059797829185988E+00, ...
    0.8059797829185990E+00 ];
  ws = [ ...
    0.1711023816204485E+00, ...
    0.1711023816204485E+00, ...
    0.1711023816204485E+00, ...
    0.1711023816204485E+00, ...
    0.3681147816131979E+00, ...
    0.3681147816131979E+00, ...
    0.3681147816131979E+00, ...
    0.3681147816131979E+00, ...
    0.1678896179529011E+00, ...
    0.1678896179529011E+00, ...
    0.1678896179529011E+00, ...
    0.1678896179529011E+00 ];

  x(1,1:n) = xs(1:n);
  x(2,1:n) = ys(1:n);
  w(1:n) = ws(1:n);

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function a = daub10_inverse ( n )

%*****************************************************************************80
%
%% DAUB10_INVERSE returns the inverse of the DAUB10 matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 July 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Output, real A(N,N), the matrix.
%
  a = ( daub10 ( n ) )';

  return
end


text:
function [p,s]=v_permutes(n)
%V_PERMUTES All N! permutations of 1:N + signatures [P,S]=(N)
% The output P is a matrix of size (N!,N) where each row
% contains a permutation of the numbers 1:N. The rows are in
% lexically sorted order.
%
% To permute the elements of an arbitrary vector V use
% V(PERMUTES(LENGTH(V))).

% PERMUTES(N) is the same as SORTROWS(PERMS(1:N)) but much faster.

% Thanks to Peter J Acklam for several improvements.

%      Copyright (c) 1998 Mike Brookes,  mike.brookes@ic.ac.uk
%      Version: $Id: v_permutes.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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

p=1;
m=1;
if n>1
  for a=2:n
    q=zeros(a*m,a);
    r=2:a+1;
       ix=1:m;
    for b=1:a
       q(ix,1)=b;
      q(ix,2:a)=r(p);
      r(b)=b;
      ix=ix+m;
    end
    m=m*a;
    p=q;
  end
end
if nargout>1 s=1-2*rem(fix((1:m)'/2),2); end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function [m, ssmp] = cellmean(x, dim)

% [M] = CELLMEAN(X, DIM) computes the mean, across all cells in x along
% the dimension dim.
%
% X should be an linear cell-array of matrices for which the size in at
% least one of the dimensions should be the same for all cells

nx = size(x);
if ~iscell(x) || length(nx)>2 || all(nx>1),
  error('incorrect input for cellmean');
end

if nargin==1,
  scx1 = cellfun('size', x, 1);
  scx2 = cellfun('size', x, 2);
  if     all(scx2==scx2(1)), dim = 2; %let second dimension prevail
  elseif all(scx1==scx1(1)), dim = 1;
  else   error('no dimension to compute mean for');
  end
end

nx   = max(nx);
nsmp = cellfun(@nansum, isfinite(x), repmat({dim},1,nx), 'UniformOutput', 0);
ssmp = cellfun(@nansum,          x,  repmat({dim},1,nx), 'UniformOutput', 0);
m    = nansum(cell2mat(ssmp), dim)./nansum(nsmp);

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
% fir1 bandpass filter implementation for rc files
% Base on  firfilt2 (Hajime Hirase - 1998)
% Modification Lynn Hazan dec 2004: any offset can be used instead than an hard code offset of 2048 for 12 bit recordings
% (subtracts offset before filtering and adds offset before writing)
% function
% firfilter(inname,outname,numchannel,sampl,lowband,highband,forder,gain,offset)
% or
% firfilter(inname,outname,numchannel,offset)
% in the latter case,
%  sampl = 20000; % sampling rate (in Hz)
%  lowband = 800; % low pass
%  highband = 8000; % high pass
%  gain = 1; % post-filter gain
%  offset = 0; % offset
% is assumed

function firfilter(inname,outname,numchannel,sampl,lowband,highband,forder,gain,offset)

if nargin<3
    error('function firfilter(inname,outname,numchannel,sampl,lowband,highband,forder,gain,offset)');
end

% make input arguments numbers for compiler
numchannel = str2num(numchannel);
if nargin <4, sampl = 20000; else sampl = str2num(sampl); end
if nargin <5, lowband = 800; else lowband = str2num(lowband); end
if nargin <6, highband = 8000; else highband = str2num(highband); end
if nargin <7, forder = 50; else forder = str2num(forder); end
if nargin<8 gain = 1; else gain = str2num(gain); end;
if nargin<9 offset = 0; else offset = str2num(offset); end;

forder = ceil(forder/2)*2; %make sure filter order is even
buffersize = 4096; % buffer size ... the larger the faster, as long as
                   % (real) memory can cover it.

% specify input and output file

datafile = fopen(inname,'r');
filtfile = fopen(outname,'w');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% changing something below this line will result in changing the
% algorithm (i.e. not the parameter)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% %
% calculate the convolution function (passbands are normalized to
% the Nyquist frequency

b = fir1(forder,[lowband/sampl*2,highband/sampl*2]);

% overlap buffer length;
overlap = forder;
overlap1 = overlap+1;
overlap11 = overlap-1;

% initial overlap buffer ... which is actually the mirror image
% of the initial portion ... make sure that you 'rewind' the file

overlapbuffer = fread(datafile,[numchannel,overlap/2],'int16');
overlapbuffer = overlapbuffer-offset;
frewind(datafile);
overlapbuffer = transpose(fliplr(overlapbuffer));

[datasegment,count] = fread(datafile,[numchannel,buffersize],'int16');
datasegment = datasegment - offset;
datasegment2 = [overlapbuffer;datasegment'];
filtered_data = gain*filter(b,1,datasegment2);
count2 = fwrite(filtfile,filtered_data(overlap1:size(filtered_data,1),:)'+offset,'int16');
  overlapbuffer = datasegment2(size(datasegment2,1)-overlap11:size(datasegment2,1),:);
% disp([count,count2]);

% do the rest
while ~feof(datafile),
  fseek(datafile,-2*numchannel*overlap,0);
  datasegment = fread(datafile,[numchannel,buffersize],'int16')'-offset;
  filtered_data = gain*filter(b,1,datasegment)+offset;
  fwrite(filtfile,filtered_data(overlap1:end,:)','int16');
end

% add the last unprocessed portion

overlapbuffer = datasegment(size(datasegment,1)-overlap11: ...
			       size(datasegment,1),:);
datasegment2 = [overlapbuffer;flipud(overlapbuffer)];
filtered_data = gain*filter(b,1,datasegment2);
fwrite(filtfile,filtered_data(overlap1:overlap1+overlap/2-1,:)'+offset,'int16');

fclose(datafile);
fclose(filtfile);

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
% the basic RIM quantifier: Q(r)=r^alpha
function re=weight1(n,m) % n-length of weighting vector, m - is alpha
re=[];
for h=1:n
    re=[re ((h/n).^m-((h-1)/n).^m)];
end
end

author: Sable

repo: mcbench-benchmarks


text:
function varargout = lvd_EditAlignedConstrainedCoordSysGUI(varargin)
% LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI MATLAB code for lvd_EditAlignedConstrainedCoordSysGUI.fig
%      LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI, by itself, creates a new LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI or raises the existing
%      singleton*.
%
%      H = LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI returns the handle to a new LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI or the handle to
%      the existing singleton*.
%
%      LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI.M with the given input arguments.
%
%      LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI('Property','Value',...) creates a new LVD_EDITALIGNEDCONSTRAINEDCOORDSYSGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before lvd_EditAlignedConstrainedCoordSysGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to lvd_EditAlignedConstrainedCoordSysGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help lvd_EditAlignedConstrainedCoordSysGUI

% Last Modified by GUIDE v2.5 11-Jan-2021 15:22:06

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @lvd_EditAlignedConstrainedCoordSysGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @lvd_EditAlignedConstrainedCoordSysGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before lvd_EditAlignedConstrainedCoordSysGUI is made visible.
function lvd_EditAlignedConstrainedCoordSysGUI_OpeningFcn(hObject, eventdata, handles, varargin)
    % This function has no output args, see OutputFcn.
    % hObject    handle to figure
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    % varargin   command line arguments to lvd_EditAlignedConstrainedCoordSysGUI (see VARARGIN)

    % Choose default command line output for lvd_EditAlignedConstrainedCoordSysGUI
    handles.output = hObject;

    centerUIFigure(hObject);

    coordsys = varargin{1};
    setappdata(hObject, 'coordsys', coordsys);

    lvdData = varargin{2};
    setappdata(hObject, 'lvdData', lvdData);

	populateGUI(handles, lvdData, coordsys);

    % Update handles structure
    guidata(hObject, handles);

    % UIWAIT makes lvd_EditAlignedConstrainedCoordSysGUI wait for user response (see UIRESUME)
    uiwait(handles.lvd_EditAlignedConstrainedCoordSysGUI);

function populateGUI(handles, lvdData, coordsys)
    set(handles.coordSysNameText,'String',coordsys.getName());

    vectorsListBoxStr = lvdData.geometry.vectors.getListboxStr();

    handles.aVectorCombo.String = vectorsListBoxStr;
    handles.aVectorCombo.Value = lvdData.geometry.vectors.getIndsForVectors(coordsys.aVector);

    handles.cVectorCombo.String = vectorsListBoxStr;
    handles.cVectorCombo.Value = lvdData.geometry.vectors.getIndsForVectors(coordsys.cVector);

    axesListBoxStr = AlignedConstrainedCoordSysAxesEnum.getListBoxStr();

    handles.alignedVectAxisCombo.String = axesListBoxStr;
    handles.alignedVectAxisCombo.Value = AlignedConstrainedCoordSysAxesEnum.getIndForName(coordsys.aVectorAxis.name);

    handles.constrainedVectAxisCombo.String = axesListBoxStr;
    handles.constrainedVectAxisCombo.Value = AlignedConstrainedCoordSysAxesEnum.getIndForName(coordsys.cVectorAxis.name);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditAlignedConstrainedCoordSysGUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
    if(isempty(handles))
        varargout{1} = false;
    else
        lvdData = getappdata(hObject, 'lvdData');
        coordsys = getappdata(hObject, 'coordsys');

        coordsys.setName(handles.coordSysNameText.String);

        coordsys.aVector = lvdData.geometry.vectors.getVectorAtInd(handles.aVectorCombo.Value);
        coordsys.cVector = lvdData.geometry.vectors.getVectorAtInd(handles.cVectorCombo.Value);

        str = handles.alignedVectAxisCombo.String{handles.alignedVectAxisCombo.Value};
        coordsys.aVectorAxis = AlignedConstrainedCoordSysAxesEnum.getEnumForListboxStr(str);

        str = handles.constrainedVectAxisCombo.String{handles.constrainedVectAxisCombo.Value};
        coordsys.cVectorAxis = AlignedConstrainedCoordSysAxesEnum.getEnumForListboxStr(str);

        varargout{1} = true;
        close(handles.lvd_EditAlignedConstrainedCoordSysGUI);
    end

% --- Executes on button press in saveAndCloseButton.
function saveAndCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveAndCloseButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    errMsg = validateInputs(handles);

    if(isempty(errMsg))
        uiresume(handles.lvd_EditAlignedConstrainedCoordSysGUI);
    else
        msgbox(errMsg,'Invalid Vector Inputs','error');
    end

function errMsg = validateInputs(handles)
    errMsg = {};
    lvdData = getappdata(handles.lvd_EditAlignedConstrainedCoordSysGUI, 'lvdData');

    aVector = lvdData.geometry.vectors.getVectorAtInd(handles.aVectorCombo.Value);
    cVector = lvdData.geometry.vectors.getVectorAtInd(handles.cVectorCombo.Value);
    if(aVector == cVector)
        errMsg{end+1} = 'The aligned vector and constrained vector must be different.';
    end

    str = handles.alignedVectAxisCombo.String{handles.alignedVectAxisCombo.Value};
    aVectorAxis = AlignedConstrainedCoordSysAxesEnum.getEnumForListboxStr(str);

    str = handles.constrainedVectAxisCombo.String{handles.constrainedVectAxisCombo.Value};
    cVectorAxis = AlignedConstrainedCoordSysAxesEnum.getEnumForListboxStr(str);
    if(aVectorAxis == cVectorAxis || ...
       strcmpi(aVectorAxis.baseAxis, cVectorAxis.baseAxis))
        errMsg{end+1} = 'The aligned vector axis and constrained vector axis must be different and not opposite.';
    end

    if(isempty(strtrim(handles.coordSysNameText.String)))
        errMsg{end+1} = 'Coordinate system name must contain more than white space and must not be empty.';
    end

% --- Executes on button press in cancelButton.
function cancelButton_Callback(hObject, eventdata, handles)
% hObject    handle to cancelButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    close(handles.lvd_EditAlignedConstrainedCoordSysGUI);

function coordSysNameText_Callback(hObject, eventdata, handles)
% hObject    handle to coordSysNameText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of coordSysNameText as text
%        str2double(get(hObject,'String')) returns contents of coordSysNameText as a double

% --- Executes during object creation, after setting all properties.
function coordSysNameText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to coordSysNameText see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on key press with focus on lvd_EditAlignedConstrainedCoordSysGUI or any of its controls.
function lvd_EditAlignedConstrainedCoordSysGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to lvd_EditAlignedConstrainedCoordSysGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'return'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'enter'
            saveAndCloseButton_Callback(handles.saveAndCloseButton, [], handles);
        case 'escape'
            close(handles.lvd_EditAlignedConstrainedCoordSysGUI);
    end

% --- Executes on selection change in aVectorCombo.
function aVectorCombo_Callback(hObject, eventdata, handles)
% hObject    handle to aVectorCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns aVectorCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from aVectorCombo

% --- Executes during object creation, after setting all properties.
function aVectorCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to aVectorCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in cVectorCombo.
function cVectorCombo_Callback(hObject, eventdata, handles)
% hObject    handle to cVectorCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns cVectorCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from cVectorCombo

% --- Executes during object creation, after setting all properties.
function cVectorCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to cVectorCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in alignedVectAxisCombo.
function alignedVectAxisCombo_Callback(hObject, eventdata, handles)
% hObject    handle to alignedVectAxisCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns alignedVectAxisCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from alignedVectAxisCombo

% --- Executes during object creation, after setting all properties.
function alignedVectAxisCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to alignedVectAxisCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in constrainedVectAxisCombo.
function constrainedVectAxisCombo_Callback(hObject, eventdata, handles)
% hObject    handle to constrainedVectAxisCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns constrainedVectAxisCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from constrainedVectAxisCombo

% --- Executes during object creation, after setting all properties.
function constrainedVectAxisCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to constrainedVectAxisCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function y = utl_get_argument(x,name)
% Get an argument (by name) of an expression that involves name-value pairs.
% Value = utl_get_argument(Expression,Name)
%
% In:
%   Expression : an expression with name-value arguments, for example a node of a
%                filter graph
%
%   Name : name of the argument to extract
%
% Out:
%   Value : value of the desired argument
%
% See also:
%   utl_find_filter
%
% Examples:
%   % first get a filter node from a model
%   ica_node = utl_find_filter(lastmodel,'flt_ica')
%   % then extract its 'variant' argument, which is the ICA variant used
%   variant = utl_get_argument(ica_node,'variant')
%
%                                       Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                       2012-01-12

if ~isfield(x,'parts')
    error('The given object is not an expression.'); end
match = find(strcmp(x.parts,name),1,'last');
if isempty(match)
    if ~iscellstr(x.parts(1:2:end))
        error('The given expression does not have name-value pairs as arguments.');
    else
        error('The given name is not an argument of the function: %s',hlp_tostring(name));
    end
end
y = x.parts{match+1};

repo: REST


text:
function modelKEGG = transformModel2KEGG(model,Dictionary)
% Replaces `model.mets` with `model.metKEGGID`. If no KEGGID
% defined, the empty cell will be replaced with metabolite abreviation.
%
% USAGE:
%
%    modelKEGG = transformModel2KEGG(model, Dictionary)
%
% INPUTS:
%    model:         COBRA model structure
%    Dictionary:    consists of:
%
%                     * CompAbr = Dictionary(:, 1): List of compounds abreviation (non-compartelized)
%                     * KEGGID = Dictionary(:, 2): List of KEGGIDs for compounds in `CompAbr`
%
% OUTPUT:
%    modelKEGG:     KEGG model structure
%
% .. Author: - 11-09-07 IT

if (nargin == 2)
    modelKEGG = mapKEGGID2Model(model, Dictionary);
elseif(nargin == 1)
    error('missing data');
    %modelKEGG = model;
end

modelKEGG.metsAbr = modelKEGG.mets;
modelKEGG.mets = modelKEGG.metKEGGID;

for i = 1: length(modelKEGG.metsAbr)
    if (isempty(modelKEGG.mets{i}))
        modelKEGG.mets(i)=modelKEGG.metsAbr(i);
    end
end

author: opencobra

repo: cobratoolbox


text:
function [ a, ipvt, info ] = dchdc ( a, lda, p, ipvt, job )

%*****************************************************************************80
%
%% DCHDC computes the Cholesky decomposition of a positive definite matrix.
%
%  Discussion:
%
%    A pivoting option allows the user to estimate the condition of a
%    positive definite matrix or determine the rank of a positive
%    semidefinite matrix.
%
%    For positive definite matrices, INFO = P is the normal return.
%
%    For pivoting with positive semidefinite matrices, INFO will
%    in general be less than P.  However, INFO may be greater than
%    the rank of A, since rounding error can cause an otherwise zero
%    element to be positive.  Indefinite systems will always cause
%    INFO to be less than P.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 June 2005
%
%  Author:
%
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Dongarra, Moler, Bunch and Stewart,
%    LINPACK User's Guide,
%    SIAM, (Society for Industrial and Applied Mathematics),
%    3600 University City Science Center,
%    Philadelphia, PA, 19104-2688.
%    ISBN 0-89871-172-X
%
%  Parameters:
%
%    Input, real A(LDA,P), the matrix whose decomposition is to
%    be computed.  Only the upper half of A need be stored.
%    The lower part of the array a is not referenced.
%
%    Input, integer LDA, the leading dimension of the array A.
%
%    Input, integer P, the order of the matrix.
%
%    Input, integer IPVT(P), integers that control the selection
%    of the pivot elements, if pivoting has been requested.
%    Each diagonal element A(K,K) is placed in one of three classes
%    according to the value of IPVT(K).
%
%      > 0, then X(K) is an initial element.
%      = 0, then X(K) is a free element.
%      < 0, then X(K) is a final element.
%
%    Before the decomposition is computed, initial elements are moved by
%    symmetric row and column interchanges to the beginning of the array A
%    and final elements to the end.  Both initial and final elements are
%    frozen in place during the computation and only free elements are moved.
%    At the K-th stage of the reduction, if A(K,K) is occupied by a free
%    element, it is interchanged with the largest free element A(L,L) with
%    K <= L.  IPVT is not referenced if JOB is 0.
%
%    Input, integer JOB, initiates column pivoting.
%    0, no pivoting is done.
%    nonzero, pivoting is done.
%
%    Output, real A(LDA,P), contains in its upper half the Cholesky factor
%    of the input matrix, as it has been permuted by pivoting.
%
%    Output, integer IPVT(N); IPVT(J) contains the index of the diagonal element
%    of A that was moved into the J-th position, if pivoting was requested.
%
%    Output, integer INFO, contains the index of the last positive diagonal
%    element of the Cholesky factor.
%
  pl = 1;
  pu = 0;
  info = p;

  if ( job ~= 0 )
%
%  Pivoting has been requested.
%  Rearrange the the elements according to IPVT.
%
    for k = 1 : p

      swapk = 0 < ipvt(k);

      negk = ipvt(k) < 0;

      if ( negk )
        ipvt(k) = -k;
      else
        ipvt(k) = k;
      end

      if ( swapk )

        if ( k ~= pl )

          temp(1:pl-1) = a(1:pl-1,k);
          a(1:pl-1,k) = a(1:pl-1,pl);
          a(1:pl-1,pl) = temp(1:pl-1);

          temp = a(k,k);
          a(k,k) = a(pl,pl);
          a(pl,pl) = temp;

          for j = pl+1 : p

            if ( j < k )
              temp = a(pl,j);
              a(pl,j) = a(j,k);
              a(j,k) = temp;
            elseif ( k < j )
              temp = a(k,j);
              a(k,j) = a(pl,j);
              a(pl,j) = temp;
            end

          end

          ipvt(k) = ipvt(pl);
          ipvt(pl) = k;

        end

        pl = pl + 1;

      end

    end

    pu = p;

    for k = p : -1 : pl

      if ( ipvt(k) < 0 )

        ipvt(k) = -ipvt(k);

        if ( pu ~= k )

          temp(1:k-1) = a(1:k-1,k);
          a(1:k-1,k) = a(1:k-1,pu);
          a(1:k-1,pu) = temp(1:k-1);

          temp = a(k,k);
          a(k,k) = a(pu,pu);
          a(pu,pu) = temp;

          for j = k+1 : p

            if ( j < pu )
              temp = a(k,j);
              a(k,j) = a(j,pu);
              a(j,pu) = temp;
            elseif ( pu < j )
              temp = a(k,j);
              a(k,j) = a(pu,j);
              a(pu,j) = temp;
            end

          end

          jt = ipvt(k);
          ipvt(k) = ipvt(pu);
          ipvt(pu) = jt;

        end

        pu = pu - 1;

      end

    end

  end

  for k = 1 : p
%
%  Reduction loop.
%
    maxdia = a(k,k);
    maxl = k;
%
%  Determine the pivot element.
%
    if ( pl <= k & k < pu )

      for l = k+1 : pu
        if ( maxdia < a(l,l) )
          maxdia = a(l,l);
          maxl = l;
        end
      end

    end
%
%  Quit if the pivot element is not positive.
%
    if ( maxdia <= 0.0 )
      info = k - 1;
      return
    end
%
%  Start the pivoting and update IPVT.
%
    if ( k ~= maxl )

      temp(1:k-1) = a(1:k-1,k);
      a(1:k-1,k) = a(1:k-1,maxl);
      a(1:k-1,maxl) = temp(1:k-1);

      a(maxl,maxl) = a(k,k);
      a(k,k) = maxdia;
      jp = ipvt(maxl);
      ipvt(maxl) = ipvt(k);
      ipvt(k) = jp;

    end
%
%  Reduction step.
%  Pivoting is contained across the rows.
%
    work(k) = sqrt ( a(k,k) );
    a(k,k) = work(k);

    for j = k+1 : p

      if ( k ~= maxl )

        if ( j < maxl )
          temp = a(k,j);
          a(k,j) = a(j,maxl);
          a(j,maxl) = temp;
        elseif ( maxl < j )
          temp = a(k,j);
          a(k,j) = a(maxl,j);
          a(maxl,j) = temp;
        end

      end

      a(k,j) = a(k,j) / work(k);
      work(j) = a(k,j);
      temp = -a(k,j);
      a(k+1:k+j-k,j) = a(k+1:k+j-k,j) + temp * work(k+1:k+j-k)';

    end

  end

  return
end


text:
function [OutputError] = PIVlab_capture_basler_save(basler_vid,nr_of_images,ImagePath,frame_nr_display)

hgui=getappdata(0,'hgui');

OutputError=0;

basler_frames_to_capture = nr_of_images*2;

if getappdata(hgui,'cancel_capture') ~=1 %capture was not cancelled --> save images from RAM to disk
	basler_data = getdata(basler_vid,basler_frames_to_capture); %ruft alle Frames in RAM ab. Frame 1,2,3 sind müll
	cntr=0;
	for image_save_number=1:2:size(basler_data,4)
		imgA_path=fullfile(ImagePath,['PIVlab_' sprintf('%4.4d',cntr) '_A.tif']);
		imgB_path=fullfile(ImagePath,['PIVlab_' sprintf('%4.4d',cntr) '_B.tif']);
		imwrite(basler_data(:,:,:,image_save_number),imgA_path,'compression','none'); %tif file saving seems to be the fastest method for saving data...
		imwrite(basler_data(:,:,:,image_save_number+1),imgB_path,'compression','none');
		cntr=cntr+1;
		set(frame_nr_display,'String',['Saving images to disk: Image pair ' num2str(cntr) ' of ' num2str(size(basler_data,4)/2)]);
		drawnow limitrate;
	end
end

author: Shrediquette

repo: PIVlab

save_path: github-repos/MATLAB/Shrediquette-PIVlab


text:
function mesh_write_emse(p)

% mesh_write_emse - Save mesh to EMSE (.wfr) file
%
% USEAGE: mesh_write_emse(p)
%
% Write a .wfr file, in minor revision 3 format (ascii),
% for each mesh in p.mesh.data.  If any cells of
% p.mesh.data.meshtype are empty, these cells will
% be skipped.
%
% See the EMSE website at http://www.sourcesignal.com
% for more information on file formats.
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:58 $

% Licence:  GNU GPL, no implied or express warranties
% History:  06/2002 Darren.Weber_at_radiology.ucsf.edu
%                 - created function from mesh_emse2matlab
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fprintf('\nMESH_WRITE_EMSE...\n');

if ~exist('p','var'),
  error('...no input p struct.\n');
elseif isempty(p),
  error('...input p struct is empty.\n');
elseif isempty(p.mesh.data),
  error('...input p struct has no mesh data.\n');
end

[path,name,ext] = fileparts(strcat(p.mesh.path,filesep,p.mesh.file));
file = fullfile(path,[name ext]);

fprintf('...writing EMSE meshes to:\n\t%s\n',fullfile(path,name));

tic;

Meshes = p.mesh.data.meshtype;

for i=1:size(Meshes,2),

  if Meshes{i},
    write_emse(file,p.mesh.data.vertices{i},p.mesh.data.faces{i},Meshes{i});
  end

end

t=toc; fprintf('...done (%5.2f sec).\n\n',t);

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function write_emse(file,vertex,face,meshtype)

[path,name,ext] = fileparts(file);
ext = '.wfr';

name = strcat(name,'_',meshtype);

file = fullfile(path,[name ext]);

fid = fopen(file,'w','ieee-le');

if(fid == -1),
  fprintf('...could not open file: %s',file);
  return;
else

  fprintf('...writing tesselation: %s\n',[name ext]);

  % Write prolog
  fprintf(fid,'3\t4000\n');
  fprintf(fid,'3\n');

  % Write mesh type
  type = lower(meshtype);
  switch type,
    case 'unknown',     fprintf(fid,  '0\n');
    case 'scalp',       fprintf(fid, '40\n');
    case 'outer skull', fprintf(fid, '80\n');
    case 'outer_skull', fprintf(fid, '80\n');
    case 'inner skull', fprintf(fid,'100\n');
    case 'inner_skull', fprintf(fid,'100\n');
    case 'cortex',      fprintf(fid,'200\n');
    case 'pial',        fprintf(fid,'200\n'); % cortex variant
    case 'white',       fprintf(fid,'200\n'); % cortex variant
    case 'smoothwm',    fprintf(fid,'200\n'); % cortex variant
    otherwise,          fprintf(fid,  '0\n');
      fprintf('\n...WARNING, unknown meshtype!\n\n');
  end

  % EMSE Voxel Coordinates
  % Voxel coordinates measure location in terms of the voxels inherent in
  % the given volumetric set. The origin is the bottom (inferior) axial
  % slice, the posterior row and in the rightmost column. This coordinate
  % system is right-handed (although, internally, the origin is in the
  % anterior row, and thus is left-handed; this representation is not
  % available to the user). The order of the displayed coordinates is
  % (slice#, row#, column#).
  %
  % EMSE MRI Coordinates
  % MRI coordinates share the same origin as internal voxel coordinates,
  % but differ from the latter in two ways: first, the coordinates
  % are measured in millimeters, not voxels. Secondly, the origin is that
  % of the internal representation; that is, the inferior slice, anterior
  % row and rightmost column. As mentioned above, this internal representation
  % is left-handed. To correct for this, the row axis is numbered in the
  % opposite direction, making the displayed coordinate system right-handed.
  % The order of the displayed coordinates is (x, y, z).

  % Given a point P(x,y,z) in head frame (the activation point on the
  % cortical mesh) and you want to find the corresponding voxel in the
  % vmi file.  Symbolically you have P(head) and you want to find P(voxel).
  %
  % 1.  The registration file contains the matrix HeadToImage,
  %     so P(MRI-mm) = HeadToImage*P(head), where P(MRI-mm) is the
  %     point in MRI coordinates.
  % 2.  From the voxel size, you can find P(MRI-voxel), which
  %     is the MRI coordinates expressed in voxels
  % 3.  Use the offset between the MRI coordinate frame and
  %     the Image coordinate frame to find P(voxel).
  %
  %Demetrios Voreades, Ph.D.
  %Applications Engineer, Source Signal Imaging
  %

  % Rotate -90 degrees around Z, given that emse coordinates
  % have +X through Nasion and +Y through left ear.
  fprintf('...rotating coordinate axes so +X anterior, +Y left, +Z superior\n');
  vertex = rz(vertex,-90,'degrees');

  % Write vertex data
  for v = 1:size(vertex,1),
    fprintf(fid,'v\t%12.8f\t%12.8f\t%12.8f\n',vertex(v,1),vertex(v,2),vertex(v,3));
  end

  % matlab vertex indices start at one,
  % not zero, so we subtract one from matlab values
  face = face - 1;
  for t = 1:size(face,1),
    fprintf(fid,'t\t%d\t%d\t%d\t\n',face(t,1),face(t,2),face(t,3));
  end

  fclose(fid);

end

return

author: PatternRecognition

repo: OpenBMI


text:
addpath Codes1D
addpath Codes2D
addpath Codes3D
addpath ServiceRoutines
addpath CFD1D
addpath CFD2D
addpath Grid/
addpath Grid/CFD
addpath Grid/3D
addpath Grid/CNS2D
addpath Grid/Euler2D
addpath Grid/Maxwell2D
addpath Grid/Other

cpt = cputime;

EulerDriver1D
figure; plot(x,Ener); drawnow; pause(.1);

PoissonCDriver1D
figure; plot(x,u); drawnow; pause(.1);

AdvecDriver1D
figure; plot(x,u); drawnow; pause(.1);

BurgersDriver1D
figure; plot(x,u); drawnow; pause(.1);

HeatDriver1D
figure; plot(x,u); drawnow; pause(.1);

MaxwellDriver1D
figure; plot(x,E); drawnow; pause(.1);

CurvedCNSDriver2D
figure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1);

CurvedPoissonIPDGDriver2D
figure; PlotField2D(N, x, y, u); drawnow; pause(.1);

CurvedEulerDriver2D
figure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1);

MaxwellCurvedDriver2D
figure; PlotField2D(N, x, y, Ez); drawnow; pause(.1);

CurvedINSDriver2D
figure; PlotField2D(N, x, y, PR); drawnow; pause(.1);

MaxwellDriver2D
figure; PlotField2D(N, x, y, Ez); drawnow; pause(.1);

EulerDriver2D
figure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1);

MaxwellHNonConDriver2D
figure; PlotField2D(N, x, y, Ez); drawnow; pause(.1);

EulerShockDriver2D
figure; PlotField2D(N, x, y, Q(:,:,4)); drawnow; pause(.1);

PoissonDriver2D
figure; PlotField2D(N, x, y, u); drawnow; pause(.1);

MaxwellPNonConDriver2D

AdvecDriver3D
figure; PlotContour3D(N, u, linspace(0, 1, 5)); drawnow; pause(.1);

MaxwellDriver3D
figure; PlotContour3D(3*N, Ez, linspace(-1, 1, 10)); drawnow; pause(.1);

PoissonIPDGDriver3D
figure; PlotContour3D(3*N, u, linspace(.1, 1, 10)); drawnow; pause(.1);
hold on
PlotSlice3D(2*N, u, 'x', .4);
hold off

alldemostook = cputime-cpt

repo: Aero-matlab


text:
function [beta_median beta_std beta_lbound beta_ubound sigma_median]=olsestimates(betahat,sigmahat,X,k,q,cband)

% function [beta_median beta_std beta_lbound beta_ubound sigma_median]=olsestimates(betahat,sigmahat,X,k,q,cband)
% estimates the posterior mean, standard deviation and confidence interval for the VAR coefficients of an OLS VAR model
% inputs:  - vector 'betahat': OLS VAR coefficientsm in vectorised form (defined in 1.1.15)
%          - matrix 'sigmahat': OLS VAR variance-covariance matrix of residuals (defined in 1.1.10)
%          - matrix 'X': matrix of regressors for the VAR model (defined in 1.1.8)
%          - integer 'k': number of coefficients to estimate for each equation in the BVAR model (defined p 7 of technical guide)
%          - integer 'q': total number of coefficients to estimate for the BVAR model (defined p 7 of technical guide)
%          - scalar 'cband': confidence level for VAR coefficients
% outputs: - vector 'beta_median': median value of the posterior distribution of beta
%          - vector 'beta_std': standard deviation of the posterior distribution of beta
%          - vector 'beta_lbound': lower bound of the credibility interval of beta
%          - vector 'beta_ubound': upper bound of the credibility interval of beta
%          - vector 'sigma_median': median value of the posterior distribution of sigma (vectorised)

% compute the point estimate of beta
beta_median=betahat;
% compute estimates for the variance of each coefficient
% first obtain omeagahat, the (OLS) variance-covariance matrix for betahat, from (a.9.1)
omegahat=kron(sigmahat,(X'*X)\speye(k));
% consider only the diagonal (variance terms), and take the square root of each element
beta_std=diag(omegahat).^0.5;
% build the confidence intervals
for ii=1:q
beta_lbound(ii,:)=norminv((1-cband)/2,beta_median(ii,1),beta_std(ii,1));
beta_ubound(ii,:)=norminv(1-(1-cband)/2,beta_median(ii,1),beta_std(ii,1));
end

sigma_median=sigmahat;

author: european-central-bank

repo: BEAR-toolbox


text:
function [v,psnrall] = gapwnnm_int_fwise( y, opt )
%GAPWNNM_INT_FWISE Integrated GAP and WNNM for snapshot compressive
%imaging.
%   Note integrated version of GAP-WNNM instead of embedded for
%   acceleration of WNNM with less block-match process for multiple
%   iterations.
%   See also GAPDENOISE.
if nargin<2
    opt = [];
end
% [0] default parameter configuration, to be specified
A  = @(x) M_func(x);
At = @(z) Mt_func(z);
if isfield(opt,'Mfunc'),  A  = @(x) opt.Mfunc(x);  end
if isfield(opt,'Mtfunc'), At = @(z) opt.Mtfunc(z); end
% Phisum   = ;
% v0       = At(y); % start point (initialization of iteration)
lambda   = 1;     % correction coefficiency
maxiter  = 300;     % maximum number of iteration
acc      = 1;       % enable acceleration
sigma    = 10/255;  % noise deviation
flag_iqa = true;    % flag of showing image quality assessments
save_iter_image = false; % flag of saving all the images of the iteration
                         %  process (true only necessary)
                         %  require assigned directory opt.iter_image_dir

if isfield(opt,'Phisum'),     Phisum = opt.Phisum;   end
if isfield(opt,'v0'),             v0 = opt.v0;       end
if isfield(opt,'lambda'),   lambda   = opt.lambda;   end
if isfield(opt,'maxiter'),   maxiter = opt.maxiter;  end
if isfield(opt,'acc'),           acc = opt.acc;      end
if isfield(opt,'sigma'),       sigma = opt.sigma;    end
if isfield(opt,'flag_iqa'), flag_iqa = opt.flag_iqa; end
if isfield(opt,'save_iter_image'), save_iter_image = opt.save_iter_image; end

if ~exist('v0','var') || isempty(v0)
    v0 = At(y); % start point (initialization of iteration)
end
y1 = zeros(size(y),'like',y);
psnrall = []; % return empty with no ground truth
% ssimall = []; % return empty with no ground truth
% [1] start iteration
v = v0; % initialization
% opt.sigma = sigma;
k = 1; % current number of iteration
nonlocalarr = uint32.empty;
vindarr     = uint8.empty;
for isig = 1:length(maxiter)
    opt.sigma = sigma(isig);
    for iter = 1:maxiter(isig)
        for ii = 1:1
            % [1.1] Euclidean projection
            yb = A(v);
            if acc % enable acceleration
                y1 = y1+(y-yb);
                v = v+lambda*(At((y1-yb)./Phisum)); % v=v+lambda*(At*A)^-1*At*dy
            else
                v = v+lambda*(At((y-yb)./Phisum));
            end
        end
        % [1.2] Denoising to match the video prior
        % WNNM video denoising (MATLAB-style matrix version)
        % v = wnnm_vdenoise(v,[],opt); % opt.sigma
        noisyv = v;
        para = vdefparaconf(opt); % default parameter configuration
        para.lambda = para.vlambda; % resolve the conflict of the parameter name

        [nrow,ncol,nframe] = size(noisyv); % grayscale video (color todo)
        % [1] pre-calculation of the indexes of the neighbors within the search
        %     window
        [neighborindarr,neighbornumarr,selfindarr] = neighborind([nrow ncol],para);

        % [2] WNNM denoisng for several iterations
        estv = noisyv;
        for iit = 1:para.iternum
            % correction between adjacent iterations
            if ~para.adaptboost %
                estv = estv + para.delta*(noisyv-estv);
            else % adaptive boosting for WNNM-based denoising
                Eestv = mean(abs(estv(:)).^2);
                Enoise  = para.abeta*abs(para.nsigma^2-var(noisyv(:)-estv(:)));
                rho = sqrt(Eestv)/(sqrt(Eestv)+sqrt(max(Eestv-Enoise,0)));
                fprintf('    Iteration % 2d, rho = %.3f.\n',iit,rho);
                estv = estv + (1-rho)*(noisyv-estv);
            end

            blockmatch_period = para.blockmatch_period;
            % inner loop to reuse the block-matching results
                if mod(k,blockmatch_period) == 1 % block matching periodically
                    nonlocalarr = uint32.empty;
                    parfor (iframe = 1:nframe,nframe) % maximum nframe parpool for optimal
                        estim = estv(:,:,iframe);
                        noisyim = noisyv(:,:,iframe);
                        % [2.1] video to patches
                        [rawpatchmat,~] = im2patch(estim,noisyim,para);
                        % [2.2] calculate the patches with non-local similarity for each
                        %       key patch
                        curnonlocalarr = blockmatch(rawpatchmat,...
                            neighborindarr,neighbornumarr,selfindarr,para);
                        nonlocalarr(:,:,iframe) = curnonlocalarr;
                    end
                end
            % frame-wise denosing using parfor instead of for to get accelerated
            % performance, requiring Parallel Computing Toolbox.

            parfor (iframe = 1:nframe,nframe) % maximum nframe parpool for optimal
            % for iframe = 1:nframe % maximum nframe parpool for optimal
                estim = estv(:,:,iframe);
                noisyim = noisyv(:,:,iframe);
                % [2.1] video to patches
                [rawpatchmat,nsigmamat] = im2patch(estim,noisyim,para);
                if iit==1 % initial noise level of each patch
                    nsigmamat = para.nsigma*ones(size(nsigmamat));
                end
                curnonlocalarr = nonlocalarr(:,:,iframe);
                % [2.3] patch estimation by means of WNNM
                [estpatchmat,frqpatchmat] = patchestimate(curnonlocalarr,...
                    rawpatchmat,nsigmamat,selfindarr,para);
                % [2.4] aggregate overlapped patches to the whole image
                curim = patch2im(estpatchmat,frqpatchmat,size(noisyim),...
                    para.patchsize);

                estv(:,:,iframe) = curim;
            end

            if mod(iit-1,para.innerloop)==0
                % % [2.2] calculate the patches with non-local similarity for
                % %       each key patch
                % [nonlocalarr,vindarr] = vblockmatch(cframe,rawpatchmat,...
                %     neighborindarr,neighbornumarr,selfindarr,para);
                % less non-local patches with lower noise level
                para.patchnum = para.patchnum-10;
            end
            % [1.4] save and show intermediate results of psnr and ssim
            if flag_iqa && isfield(opt,'orig') && (~isempty(opt.orig))
                psnrall(k) = psnr(double(estv),double(opt.orig)); % record all psnr
                % ssimall(k) = ssim(double(estv),opt.orig); % record all ssim
                if (mod(k,5)==0)
                    fprintf('  GAP-%s iteration % 4d, sigma %.1f, PSNR %2.2f dB.\n',...
                        upper(opt.denoiser),k,opt.sigma*255,psnrall(k));
                end
                if save_iter_image % save all the images of the iteration process
                    MAXB = opt.MAXB;
                    % save each frame in the assigned directory
                    nim = size(estv,ndims(estv)); % number of frames in the video
                    for iim = 1:nim
                        im = estv(:,:,iim);
                        impsnr = psnr(im,opt.orig(:,:,iim));
                        imssim = ssim(im,opt.orig(:,:,iim));
                        if k == 1 % mkdir for the first iteration
                            subdir = sprintf('%s/frame%02d',opt.iter_image_dir,iim); % frame-wise
                            if ~exist(subdir,'dir')
                                mkdir(subdir);
                            end
                        end
                        imwrite(uint8(im*MAXB),sprintf('%s/frame%02d/frame%02d_iter%03d_sigma%.1f_psnr%2.2f_ssim%.4f.png',...
                            opt.iter_image_dir,iim,iim,k,opt.sigma*MAXB,impsnr,imssim));
                    end
                end
            end
            k = k+1;
        end % WNNM loop [iternum]
        v = estv;
        % % [1.3] update noise standard deviation
        % nsigma = eta*sqrt(abs(sigma^2-var(v(:)-v0(:))));
        % opt.sigma = nsigma;

    end % GAP loop [maxiter]
end % sigma loop [length(sigma)]

end

repo: DeSCI


text:
% Reference performance
accTestRef = 0.893333;
allowedError = 0.001;
method = 'SVORIM';

% Create the algorithm object
algorithmObj = SVORIM();

% Clear parameter struct
clear param;

% Parameter C (Cost)
param.C = 10;

% Parameter k (kernel width)
param.k = 1;

% Run the algorithm
info = algorithmObj.fitpredict(train,test,param);

trainCM = confusionmat(info.predictedTrain,train.targets);
testCM = confusionmat(info.predictedTest,test.targets);

accTrain = CCR.calculateMetric(trainCM);
accTest  = CCR.calculateMetric(testCM);

% Report accuracy
fprintf('Performing test for %s\n', method);
fprintf('Accuracy Train %f, Accuracy Test %f\n',accTrain,accTest);

if abs(accTestRef-accTest)<allowedError
    fprintf('Test accuracy matches reference accuracy\n');
else
    warning('Test accuracy does NOT match reference accuracy');
end

author: ayrna

repo: orca

save_path: github-repos/MATLAB/ayrna-orca


text:
function [Jul1,Jul2]=UTC2GPS(Jul1,Jul2)
%%UTC2TCG Convert from universal coordinated time (UTC) given as a two-
%         part pseudo-Julian date to the timescale used by the Global
%         Positioning System (GPS), represented as a two-part Julian date.
%
%INPUTS: Jul1, Jul2 Two parts of a pseudo-Julian date given in UTC. 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.
%
%OUTPUTS: Jul1, Jul2 The time as a Julian date in GPS Time.
%
%The UTC date is only pseudo-Julian, because there is not a fixed number
%of seconds in a Julian day. The convention used in the IAU standard is
%that the Julian day matches the UTC day regardless of whether the UTC day
%is 86399, 86400 or 86401 SI seconds (depending on the presence of leap
%seconds).
%
%UTC began at 1960 January 1.0 (JD 2436934.5) and this function should not
%be called with an earlier date.
%
%Many temporal coordinate systems standards are compared in [1].
%
%REFERENCES:
%[1] D. F. Crouse, "An Overview of Major Terrestrial, Celestial, and
%    Temporal Coordinate Systems for Target Tracking," Formal Report, Naval
%    Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016, 173
%    pages.
%
%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

[Jul1,Jul2]=UTC2TAI(Jul1,Jul2);
[Jul1,Jul2]=TAI2GPS(Jul1,Jul2);
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:
% ENMF: Exact NMF (Gillis and Glineur, 2012)
% process_video('NMF', 'ENMF', 'dataset/demo.avi', 'output/demo_ENMF.avi');
rank = 1;
[H,W] = ExactNMF(M,rank,100);
L = (W' * H')';
S = M - L;

author: andrewssobral

repo: lrslibrary


text:
%%

e = tensor;
E.name = elasticity;

%% Young's Modulus

x = xvector;
Y = YoungsModulus(E,x)

%%

plot(E,'PlotType','YoungsModulus')

%% Linear Compressibility

linearCompressibility(E,x)

%%

plot(E,'PlotType','linearCompressibility')

%% Christoffel Tensor

C = ChristoffelTensor(E,x)

%% Elastic Wave Velocity

[vp,vs1,vs2,pp,ps1,ps2] = velocity(E,x,1)

%%

plot(E,'PlotType','vp')
plot(E,'PlotType','vs1')
plot(E,'PlotType','vs2')

author: mtex-toolbox

repo: mtex

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


text:
function test_failed = test_libltfat_dgt_fb(varargin)
test_failed = 0;

fprintf(' ===============  %s ================ \n',upper(mfilename));

definput.flags.complexity={'double','single'};
[flags]=ltfatarghelper({},definput,varargin);
dataPtr = [flags.complexity, 'Ptr'];

[~,~,enuminfo]=libltfatprotofile;
phaseconv = enuminfo.ltfat_phaseconvention;

fftwflags = struct('FFTW_MEASURE',0,'FFTW_ESTIMATE',64,'FFTW_PATIENT',32,'FFTW_DESTROY_INPUT',1,...
    'FFTW_UNALIGNED',2,'FFTW_EXHAUSTIVE',8,'FFTW_PRESERVE_INPUT',16);

Larr  = [350 350   9   1];
glarr = [ 20  10   9   1];
aarr  = [ 10  10   9   1];
Marr  = [ 35  35   3   1];
Warr  = [  1   3   3   1];

for do_complex = 0:1
    complexstring = '';
    if do_complex, complexstring = 'complex'; end

    for idx = 1:numel(Larr)
        L = Larr(idx);
        W = Warr(idx);
        a = aarr(idx);
        M = Marr(idx);
        gl = glarr(idx);

        N = L/a;

        if do_complex
            g = randn(gl,1,flags.complexity) + 1i*randn(gl,1,flags.complexity);
            f = randn(L,W,flags.complexity) + 1i*randn(L,W,flags.complexity);
            gin = complex2interleaved(g);
            fin = complex2interleaved(f);
        else
            g = randn(gl,1,flags.complexity);
            f = randn(L,W,flags.complexity);
            gin = g; fin = f;
        end

        fPtr = libpointer(dataPtr,fin);
        gPtr = libpointer(dataPtr,gin);
        c = cast(randn(M,N,W)+1i*randn(M,N,W),flags.complexity);
        cout = complex2interleaved(c);
        coutPtr = libpointer(dataPtr,cout);

        truec = dgt(f,g,a,M);

        funname = makelibraryname('dgt_fb',flags.complexity,do_complex);
        status = calllib('libltfat',funname,fPtr,gPtr,L,gl,W,a,M,phaseconv.LTFAT_FREQINV,coutPtr);

        res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');
        [test_failed,fail]=ltfatdiditfail(res+status,test_failed);
        fprintf(['DGT FREQINV    L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);

        truec = dgt(f,g,a,M,'timeinv');
        status = calllib('libltfat',funname,fPtr,gPtr,L,gl,W,a,M,phaseconv.LTFAT_TIMEINV,coutPtr);

        res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');
        [test_failed,fail]=ltfatdiditfail(res+status,test_failed);
        fprintf(['DGT TIMEINV    L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);

        % With plan
        c = cast(randn(M,N,W)+1i*randn(M,N,W),flags.complexity);
        cout = complex2interleaved(c);
        coutPtr = libpointer(dataPtr,cout);

        plan = libpointer();
        funname = makelibraryname('dgt_fb_init',flags.complexity,do_complex);
        statusInit = calllib('libltfat',funname,gPtr,gl,a,M,phaseconv.LTFAT_FREQINV,fftwflags.FFTW_MEASURE,plan);

        funname = makelibraryname('dgt_fb_execute',flags.complexity,do_complex);
        statusExecute = calllib('libltfat',funname,plan, fPtr,L,W,coutPtr);

        funname = makelibraryname('dgt_fb_done',flags.complexity,do_complex);
        statusDone = calllib('libltfat',funname,plan);

        truec = dgt(f,g,a,M);
        res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');
        [test_failed,fail]=ltfatdiditfail(res+statusInit,test_failed);
        fprintf(['DGT FREQINV WP L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);

        %%%%%%
        c = cast(randn(M,N,W)+1i*randn(M,N,W),flags.complexity);
        cout = complex2interleaved(c);
        coutPtr = libpointer(dataPtr,cout);

        plan = libpointer();
        funname = makelibraryname('dgt_fb_init',flags.complexity,do_complex);
        statusInit = calllib('libltfat',funname,gPtr,gl,a,M,phaseconv.LTFAT_TIMEINV,fftwflags.FFTW_MEASURE,plan);

        funname = makelibraryname('dgt_fb_execute',flags.complexity,do_complex);
        statusExecute = calllib('libltfat',funname,plan, fPtr,L,W,coutPtr);

        funname = makelibraryname('dgt_fb_done',flags.complexity,do_complex);
        statusDone = calllib('libltfat',funname,plan);

        truec = dgt(f,g,a,M,'timeinv');
        res = norm(reshape(truec,M,N*W) - interleaved2complex(coutPtr.Value),'fro');
        [test_failed,fail]=ltfatdiditfail(res+statusInit,test_failed);
        fprintf(['DGT TIMEINV WP L:%3i, gl:%3i, W:%3i, a:%3i, M:%3i %s %s %s %s\n'],L,gl,W,a,M,complexstring,flags.complexity,ltfatstatusstring(status),fail);
    end
end

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
% Reference performance
% We have to expected values depending of the OS
% (see https://github.com/ayrna/orca/issues/19)
if ispc
    accTestRef = 0.920000;
else
    accTestRef = 0.960000;
end
allowedError = 0.001;
method = 'SVMOP';

% Create the algorithm object
algorithmObj = SVMOP();

% Clear parameter struct
clear param;

% Parameter C (Cost)
param.C = 10;

% Parameter k (kernel width)
param.k = 10;

% Run the algorithm
info = algorithmObj.fitpredict(train,test,param);

trainCM = confusionmat(info.predictedTrain,train.targets);
testCM = confusionmat(info.predictedTest,test.targets);

accTrain = CCR.calculateMetric(trainCM);
accTest  = CCR.calculateMetric(testCM);

% Report accuracy
fprintf('Performing test for %s\n', method);
fprintf('Accuracy Train %f, Accuracy Test %f\n',accTrain,accTest);

if abs(accTestRef-accTest)<allowedError
    fprintf('Test accuracy matches reference accuracy\n');
else
    warning('Test accuracy does NOT match reference accuracy');
end


text:
Fs=44100;
dt=1/Fs;

T=1/f;

sls=get(handles.sl,'string');
sl=str2num(sls); % signal length

xl=get(handles.axes1,'Xlim');
yl=get(handles.axes1,'Ylim');
dxl=xl(2)-xl(1);
dyl=yl(2)-yl(1);

xc1=0:dt:sl;
xc=mod(xc1,T); % turn to one period
if iscnt
    yc=interp1([xys(1,:)-dxl xys(1,:) xys(1,:)+dxl],[xys(2,:) xys(2,:) xys(2,:)],xc,mth,'extrap');
else
    yc=interp1(xys(1,:),xys(2,:),xc,mth,'extrap');
end

yc=(yc-mean(yc))/max(abs(yc)); % mormalize, debias


text:
function [ nb, ni, np, p_xy, p_type ] = bud ( pr_bud, pr_bud_angular, ...
  r, nb, ni, np, p_xy, p_type )

%*****************************************************************************80
%
%% BUD carries out the budding process.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 December 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real PR_BUD, the probability that a boundary point will bud.
%
%    Input, real PR_BUD_ANGULAR, the probability that a boundary point bud
%    will be constrained to the boundary.
%
%    Input, real R, the radius of the circle.
%
%    Input, integer NB, the updated number of boundary points.
%
%    Input, integer NI, the updated number of interior points.
%
%    Input, integer NP, the total number of points.
%
%    Input, real P_XY(2,NP), the point coordinates.
%
%    Input, integer P_TYPE(NP),
%    1, the point is constrained to the circle.
%    2, the point is constrainted to the disk.
%
%    Output, integer NB, the updated number of boundary points.
%
%    Output, integer NI, the updated number of interior points.
%
%    Output, integer NP, the updated total number of points.
%
%    Output, real P_XY(2,NP), the point coordinates.
%
%    Output, integer P_TYPE(NP),
%    1, the point is constrained to the circle.
%    2, the point is constrainted to the disk.
%    -1, the point is a new point, constrained to the circle.
%    -2, the point is a new point, constrained to the disk.
%
  r1 = rand ( 1, np );
  r2 = rand ( 1, np );

  b = find ( p_type == 1 & r1 <= pr_bud & r2 <= pr_bud_angular );
  i = find ( p_type == 1 & r1 <= pr_bud & pr_bud_angular < r2 );

  nb_inc = length ( b );
  ni_inc = length ( i );

  b_xy = bud_angular ( nb_inc, p_xy(1:2,b) );
  b_type(1:nb_inc) = -1;

  i_xy = bud_radial ( ni_inc, p_xy(1:2,i) );
  i_type(1:ni_inc) = -2;

  p_xy = [ b_xy, p_xy, i_xy ];
  p_type = [ b_type, p_type, i_type ];

  nb = nb + nb_inc;
  ni = ni + ni_inc;
  np = nb + ni;

% fprintf ( 1, 'BUD: size(P_XY)=%d,%d\n', size(p_xy) );
% fprintf ( 1, '     NB = %d, NI = %d, NP = %d\n', nb, ni, np );

  return
end

repo: jburkardt-m


text:
%%***********************************************************************
%% nzlist: find the combined list of non-zero elements
%%         of Aj, j = 1:k, for each k,
%%         assuming that the Aj's are permuted such that
%%         A1 has the fewest nonzero elements, followed by A2, and so on.
%%
%% [isspA,nzlistA,nzlistAsum,isspAy,nzlistAy] = nzlist(blk,At,par)
%%
%%  isspA(p,k) = 1 if Apk is sparse, 0 if it is dense.
%%  nzlistA = px2 cell array.
%%            nzlistA{p,1}(k) is the starting row index (in C convention)
%%            in the 2-column matrix nzlistA{p,2} that
%%            stores the row and column index of the nonzero elements
%%            of Apk.
%%            nzlistA{p,1}(k) = inf if nnz(Apk) exceeds given threshold.
%%  nzlistAsum = px2 cell array.
%%            nzlistA{p,1}(k) is the starting row index (in C convention)
%%            in the 2-column matrix nzlistA{p,2} that
%%            stores the row and column index of the nonzero elements
%%            of Apk that are not already present
%%            in the combined list from Ap1+...Ap,k-1.
%%  nzlistAy = px1 cell array.
%%            nzlistAy{p} is a 2-column matrix that stores the
%%            row and column index of the nonzero elements of
%%            Ap,1+.... Ap,m.
%%            nzlistAy{p} = inf  if the number of nonzero elements
%%            exceeds a given threshold.
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

  function [isspA,nzlistA,nzlistAsum,isspAy,nzlistAy] = nzlist(blk,At,par)

  spdensity   = par.spdensity;
  smallblkdim = par.smallblkdim;
  m = par.numcolAt;
%%
  numblk = size(blk,1);
  isspA = zeros(numblk,m);
  nzlistA = cell(numblk,2);  nzlistAsum = cell(numblk,2);
  isspAy = zeros(numblk,1);  nzlistAy = cell(numblk,1);
%%
  for p = 1:size(blk,1)
     pblk = blk(p,:);
     if strcmp(pblk{1},'s') & ((max(pblk{2}) > smallblkdim) | (length(pblk{2}) <= 10))
        numblk = length(pblk{2});
        n = sum(pblk{2});
        n2 = sum(pblk{2}.*pblk{2});
        if (numblk == 1)
           nztol = spdensity*n;
           nztol2 = spdensity*n2/2;
        else
           nztol = spdensity*n/2;
           nztol2 = spdensity*n2/4;
        end
        nzlist1 = zeros(1,m+1); nzlist2 = [];
        nzlist3 = zeros(1,m+1); nzlist4 = []; breakyes = zeros(1,2);
        Asum = sparse(n,n);
%%
        m1 = size(At{p,1},2);
        for k = 1:m1
           Ak = mexsmat(blk,At,1,p,k);
           nnzAk = nnz(Ak);
           isspA(p,k) = (nnzAk < spdensity*n2) | (numblk > 1);
           if ~all(breakyes)
              [I,J] = find(abs(Ak) > 0);
              %%
              %% nonzero elements of Ak.
              %%
   	      if (breakyes(1) == 0);
                 if (nnzAk <= nztol)
                    idx = find(I<=J);
                    nzlist1(k+1) = nzlist1(k)+length(idx);
                    nzlist2 = [nzlist2; [I(idx), J(idx)] ];
                 else
                    nzlist1(k+1:m+1) = inf*ones(1,m-k+1);
                    breakyes(1) = 1;
                 end
              end
              %%
	      %% nonzero elements of |A1|+...+|Ak|.
              %%
	      if (breakyes(2) == 0)
                 nztmp = zeros(length(I),1);
                 for t = 1:length(I);
                    i=I(t); j=J(t); nztmp(t)=Asum(i,j);
                 end
                 %% find new nonzero positions when Ak is added to Asum.
                 idx = find(nztmp == 0);
                 nzlist3(k+1) = nzlist3(k) + length(idx);
                 if (nzlist3(k+1) < nztol2);
                    nzlist4 = [ nzlist4; [I(idx), J(idx)] ];
                 else
                    nzlist3(k+1:m+1) = inf*ones(1,m-k+1);
                    breakyes(2) = 1;
                 end
                 Asum = Asum+abs(Ak);
              end
           end
        end
	if (numblk == 1)
   	   isspAy(p,1) = (nzlist1(m+1) < inf) | (nzlist3(m+1) < inf);
        else
   	   isspAy(p,1) = 1;
        end
	nzlistA{p,1} = nzlist1;    nzlistA{p,2} = nzlist2;
    	nzlistAsum{p,1} = nzlist3; nzlistAsum{p,2} = nzlist4;
        %%
        %% nonzero elements of (A1*y1+...Am*ym).
        %%
        if (nzlist3(m+1) < inf);
           if (length(pblk) > 2)
              m2 = length(pblk{3});
              len = sum(pblk{3});
              DD = spconvert([At{p,3}(:,2:4); len, len, 0]);
              Asum = Asum + abs(At{p,2}*DD*At{p,2}');
           end
           [I,J] = find(Asum > 0);
           if (length(I) < nztol2)
              nzlistAy{p} = [I, J];
           else
              nzlistAy{p} = inf;
           end
        else
           nzlistAy{p} = inf;
        end
     end
  end
%%***********************************************************************

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


text:
function [handle, image, region] = vot(format)
% vot Initialize communication and obtain communication structure
%
% This function is used to initialize communication with the toolkit.
%
% The resulting handle is a structure provides several functions for
% further interaction:
% - frame(handle): Get new frame from the sequence.
% - report(handle, region): Report region for current frame and advance.
% - quit(handle): Closes the communication and saves the data.
%
% Input:
% - format (string): Desired region input format.
%
% Output:
% - handle (structure): Updated communication handle structure.
% - image (string): Path to the first image file.
% - region (vector): Initial region encoded as a rectangle or as a polygon.

    if nargin < 1
       format = 'rectangle';
    end

    [handle, image, region] = tracker_initialize(format);
    handle.frame = @tracker_frame;
    handle.report = @tracker_report;
    handle.quit = @tracker_quit;

end

function [handle, image, region] = tracker_initialize(format)
% tracker_initialize Initialize communication structure
%
% This function is used to initialize communication with the toolkit.
%
% Input:
% - format (string): Desired region input format.
%
% Output:
% - handle (structure): Updated communication handle structure.
% - image (string): Path to the first image file.
% - region (vector): Initial region encoded as a rectangle or as a polygon.

    if ~ismember(format,  {'rectangle', 'polygon'})
        error('VOT: Illegal region format.');
    end;

    if ~isempty(getenv('TRAX'))
        % In case TraX can be used, we include the path to the server mex function.
        if ~isempty(getenv('TRAX_MEX'))
            addpath(getenv('TRAX_MEX'));
        end;
        traxserver('setup', format, 'path');

        [image, region] = traxserver('wait');

        handle = struct('trax', true);

        if isempty(image) || isempty(region)
            tracker_quit(handle);
            return;
        end;

        traxserver('status', region);

        return;
    end;

    handle.trax = false;

    % read the image file paths
    fid = fopen('images.txt','r');
    images = textscan(fid, '%s', 'delimiter', '\n');
    fclose(fid);
    handle.images = images{1};

    % read the region
    region = dlmread('region.txt');
    region = region(:);
    handle.format = format;
    handle.index = 2;
    handle.regions = cell(numel(handle.images), 1);

    if numel(region) == 4
        format = 'rectangle';
    elseif numel(region) >= 6 && mod(numel(region), 2) == 0
        format = 'polygon';
    else
        error('VOT: Illegal format of the input region.');
    end;

    switch handle.format
        case 'rectangle'
            if strcmp(format, 'polygon')
                x = region(1:2:end);
                y = region(2:2:end);
                region = [min(x), min(y), max(x) - min(x), max(y) - min(y)];
            end;
        case 'polygon'
            if strcmp(format, 'rectangle')
                x = [region(1), region(1), region(1) + region(3), ...
                     region(1) + region(3), region(1)];
                y = [region(2), region(2) + region(4), region(2) + ...
                     region(4), region(2), region(2)];
                region = zeros(8, 1);
                region(1:2:7) = x;
                region(2:2:8) = y;
            end;
    end;

    handle.position = 2;

    handle.regions{1} = region;
    image = handle.images{1};

end

function [handle, image] = tracker_frame(handle)
% tracker_frame Get new frame from the sequence
%
% This function is used to get new frame from the current sequence
%
% Input:
% - handle (structure): Communication handle structure.
%
% Output:
% - handle (structure): Updated communication handle structure.
% - image (string): Path to image file.

    if ~isstruct(handle)
        error('VOT: Handle should be a structure.');
    end;

    if handle.trax
        [image, region] = traxserver('wait');

        if isempty(image) || ~isempty(region)
            handle.quit(handle);
        end;

        return;
    end;

    if handle.position > numel(handle.images)
        image = [];
        return;
    end;

    image = handle.images{handle.position};

end

function handle = tracker_report(handle, region)
% tracker_report Report region for current frame and advance
%
% This function stores the region for the current frame and advances
% the internal counter to the next frame.
%
% Input:
% - handle (structure): Communication handle structure.
% - region (vector): Predicted region as a rectangle or a polygon.
%
% Output:
% - handle (structure): Updated communication handle structure.

    if isempty(region)
        region = 0;
    end;

    if ~isstruct(handle)
        error('VOT: Handle should be a structure.');
    end;

    if handle.trax
        traxserver('status', region);
        return;
    end;

    if handle.position > numel(handle.images)
        return;
    end;

    handle.regions{handle.position} = region;

    handle.position = handle.position + 1;
end

function tracker_quit(handle)
% tracker_quit Closes the communication and saves the data
%
% This function closes the communication with the toolkit and
% saves the remaining data.
%
% Input:
% - handle (structure): Communication handle structure.
%

    if ~isstruct(handle)
        error('VOT: Handle should be a structure.');
    end;

    if handle.trax
        traxserver('quit');
        return;
    end;

    if iscell(handle.regions)

        fid = fopen('output.txt', 'w');

        for i = 1:numel(handle.regions)
            region = handle.regions{i};

            if numel(region) == 1
                fprintf(fid, '%f\n', region);
            elseif numel(region) == 4
                fprintf(fid, '%f,%f,%f,%f\n', region(1), region(2), region(3), region(4));
            elseif numel(region) >= 6 && mod(numel(region), 2) == 0
                fprintf(fid, '%f,', region(1:end-1));
                fprintf(fid, '%f\n', region(end));
            else
                error('VOT: Illegal result format');
            end;

        end;

        fclose(fid);

        quit();
    else
        error('VOT: Unable to write results.');
    end

end

author: flyers

repo: drone-tracking