text:
function varargout = lvd_EditLinearTangentModelGUI(varargin)
    % LVD_EDITLINEARTANGENTMODELGUI MATLAB code for lvd_EditLinearTangentModelGUI.fig
    %      LVD_EDITLINEARTANGENTMODELGUI, by itself, creates a new LVD_EDITLINEARTANGENTMODELGUI or raises the existing
    %      singleton*.
    %
    %      H = LVD_EDITLINEARTANGENTMODELGUI returns the handle to a new LVD_EDITLINEARTANGENTMODELGUI or the handle to
    %      the existing singleton*.
    %
    %      LVD_EDITLINEARTANGENTMODELGUI('CALLBACK',hObject,eventData,handles,...) calls the local
    %      function named CALLBACK in LVD_EDITLINEARTANGENTMODELGUI.M with the given input arguments.
    %
    %      LVD_EDITLINEARTANGENTMODELGUI('Property','Value',...) creates a new LVD_EDITLINEARTANGENTMODELGUI or raises the
    %      existing singleton*.  Starting from the left, property value pairs are
    %      applied to the GUI before lvd_EditLinearTangentModelGUI_OpeningFcn gets called.  An
    %      unrecognized property name or invalid value makes property application
    %      stop.  All inputs are passed to lvd_EditLinearTangentModelGUI_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_EditLinearTangentModelGUI

    % Last Modified by GUIDE v2.5 23-Apr-2021 16:29:22

    % Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct('gui_Name',       mfilename, ...
        'gui_Singleton',  gui_Singleton, ...
        'gui_OpeningFcn', @lvd_EditLinearTangentModelGUI_OpeningFcn, ...
        'gui_OutputFcn',  @lvd_EditLinearTangentModelGUI_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_EditLinearTangentModelGUI is made visible.
function lvd_EditLinearTangentModelGUI_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_EditLinearTangentModelGUI (see VARARGIN)

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

    centerUIFigure(hObject);

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

    setappdata(hObject,'plotDur',1.0);

    populateGUI(handles, linearTangentModel);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, linearTangentModel)
    handles.aText.String = fullAccNum2Str(linearTangentModel.a);
    handles.aOptCheckbox.Value = double(linearTangentModel.varA);
    handles.aLbText.String = fullAccNum2Str(linearTangentModel.aLb);
    handles.aUbText.String = fullAccNum2Str(linearTangentModel.aUb);
    aOptCheckbox_Callback(handles.aOptCheckbox, [], handles);

    handles.aDotText.String = fullAccNum2Str(linearTangentModel.a_dot);
    handles.aDotOptCheckbox.Value = double(linearTangentModel.varADot);
    handles.aDotLbText.String = fullAccNum2Str(linearTangentModel.aDotLb);
    handles.aDotUbText.String = fullAccNum2Str(linearTangentModel.aDotUb);
    aDotOptCheckbox_Callback(handles.aDotOptCheckbox, [], handles);

    handles.bText.String = fullAccNum2Str(linearTangentModel.b);
    handles.bOptCheckbox.Value = double(linearTangentModel.varB);
    handles.bLbText.String = fullAccNum2Str(linearTangentModel.bLb);
    handles.bUbText.String = fullAccNum2Str(linearTangentModel.bUb);
    bOptCheckbox_Callback(handles.bOptCheckbox, [], handles);

    handles.bDotText.String = fullAccNum2Str(linearTangentModel.b_dot);
    handles.bDotOptCheckbox.Value = double(linearTangentModel.varBDot);
    handles.bDotLbText.String = fullAccNum2Str(linearTangentModel.bDotLb);
    handles.bDotUbText.String = fullAccNum2Str(linearTangentModel.bDotUb);
    bDotOptCheckbox_Callback(handles.bDotOptCheckbox, [], handles);

    % --- Outputs from this function are returned to the command line.
function varargout = lvd_EditLinearTangentModelGUI_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
        varargout{1} = true;
        close(handles.lvd_EditLinearTangentModelGUI);
    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 = {};
    if(isempty(errMsg))
        uiresume(handles.lvd_EditLinearTangentModelGUI);
    else
        msgbox(errMsg,'Errors were found while editing plugins.','error');
    end

function aText_Callback(hObject, eventdata, handles)
    % hObject    handle to aText (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 aText as text
    %        str2double(get(hObject,'String')) returns contents of aText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'A Term';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.a = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.a);

        msgbox(errMsg,'Invalid A Term','error');
    end

    % --- Executes during object creation, after setting all properties.
function aText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to aText (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 aOptCheckbox.
function aOptCheckbox_Callback(hObject, eventdata, handles)
    % hObject    handle to aOptCheckbox (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 aOptCheckbox
    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');
    linearTangentModel.varA = logical(hObject.Value);

    if(hObject.Value)
        handles.aLbText.Enable = 'on';
        handles.aUbText.Enable = 'on';
    else
        handles.aLbText.Enable = 'off';
        handles.aUbText.Enable = 'off';
    end

function aLbText_Callback(hObject, eventdata, handles)
    % hObject    handle to aLbText (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 aLbText as text
    %        str2double(get(hObject,'String')) returns contents of aLbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'A Term Lower Bound';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.aLb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.aLb);

        msgbox(errMsg,'Invalid A Term Lower Bound','error');
    end

    % --- Executes during object creation, after setting all properties.
function aLbText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to aLbText (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 aUbText_Callback(hObject, eventdata, handles)
    % hObject    handle to aUbText (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 aUbText as text
    %        str2double(get(hObject,'String')) returns contents of aUbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'A Term Upper Bound';
    lb = linearTangentModel.aLb;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.aUb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.aUb);

        msgbox(errMsg,'Invalid A Term Upper Bound','error');
    end

    % --- Executes during object creation, after setting all properties.
function aUbText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to aUbText (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 aDotText_Callback(hObject, eventdata, handles)
    % hObject    handle to aDotText (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 aDotText as text
    %        str2double(get(hObject,'String')) returns contents of aDotText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'A Dot';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.a_dot = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.a_dot);

        msgbox(errMsg,'Invalid A Dot','error');
    end

    % --- Executes during object creation, after setting all properties.
function aDotText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to aDotText (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 aDotOptCheckbox.
function aDotOptCheckbox_Callback(hObject, eventdata, handles)
    % hObject    handle to aDotOptCheckbox (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 aDotOptCheckbox
    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');
    linearTangentModel.varADot = logical(hObject.Value);

    if(hObject.Value)
        handles.aDotLbText.Enable = 'on';
        handles.aDotUbText.Enable = 'on';
    else
        handles.aDotLbText.Enable = 'off';
        handles.aDotUbText.Enable = 'off';
    end

function aDotLbText_Callback(hObject, eventdata, handles)
    % hObject    handle to aDotLbText (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 aDotLbText as text
    %        str2double(get(hObject,'String')) returns contents of aDotLbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'A Dot Lower Bound';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.aDotLb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.aDotLb);

        msgbox(errMsg,'Invalid A Dot Lower Bound','error');
    end

    % --- Executes during object creation, after setting all properties.
function aDotLbText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to aDotLbText (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 aDotUbText_Callback(hObject, eventdata, handles)
    % hObject    handle to aDotUbText (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 aDotUbText as text
    %        str2double(get(hObject,'String')) returns contents of aDotUbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'A Dot Upper Bound';
    lb = linearTangentModel.aDotLb;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.aDotUb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.aDotUb);

        msgbox(errMsg,'Invalid A Dot Upper Bound','error');
    end

    % --- Executes during object creation, after setting all properties.
function aDotUbText_CreateFcn(hObject, eventdata, handles)
    % hObject    handle to aDotUbText (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 plotLinearTangentButton.
function plotLinearTangentButton_Callback(hObject, eventdata, handles)
% hObject    handle to plotLinearTangentButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');
    duration = str2double(handles.durationToPlot.String);

    t0 = linearTangentModel.getT0();
    t = linspace(t0,t0+duration,500);
    y = NaN(1,length(t));

    for(i=1:length(t))
        y(i) = linearTangentModel.getValueAtTime(t(i));
    end

    y = rad2deg(y);

    hAx = axes(figure());
    plot(hAx, t, y);
    grid(hAx,'minor');
    xlabel('DT [sec]');
    ylabel('Polynomial Value [deg]');

function durationToPlot_Callback(hObject, eventdata, handles)
% hObject    handle to durationToPlot (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 durationToPlot as text
%        str2double(get(hObject,'String')) returns contents of durationToPlot as a double
    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'Duration to Plot';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(not(isempty(errMsg)))
        oldPlotDur = getappdata(handles.lvd_EditLinearTangentModelGUI,'plotDur');
        handles.durationToPlot.String = fullAccNum2Str(oldPlotDur);

        msgbox(errMsg,'Invalid Plotting Duration','error');
    end

% --- Executes during object creation, after setting all properties.
function durationToPlot_CreateFcn(hObject, eventdata, handles)
% hObject    handle to durationToPlot (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 bText_Callback(hObject, eventdata, handles)
% hObject    handle to bText (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 bText as text
%        str2double(get(hObject,'String')) returns contents of bText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'B Term';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.b = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.b);

        msgbox(errMsg,'Invalid B Term','error');
    end

% --- Executes during object creation, after setting all properties.
function bText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bText (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 bOptCheckbox.
function bOptCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to bOptCheckbox (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 bOptCheckbox
    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');
    linearTangentModel.varB = logical(hObject.Value);

    if(hObject.Value)
        handles.bLbText.Enable = 'on';
        handles.bUbText.Enable = 'on';
    else
        handles.bLbText.Enable = 'off';
        handles.bUbText.Enable = 'off';
    end

function bLbText_Callback(hObject, eventdata, handles)
% hObject    handle to bLbText (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 bLbText as text
%        str2double(get(hObject,'String')) returns contents of bLbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'B Term Lower Bound';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.bLb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.bLb);

        msgbox(errMsg,'Invalid B Term Lower Bound','error');
    end

% --- Executes during object creation, after setting all properties.
function bLbText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bLbText (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 bUbText_Callback(hObject, eventdata, handles)
% hObject    handle to bUbText (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 bUbText as text
%        str2double(get(hObject,'String')) returns contents of bUbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'B Term Upper Bound';
    lb = linearTangentModel.bLb;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.bUb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.bUb);

        msgbox(errMsg,'Invalid B Term Upper Bound','error');
    end

% --- Executes during object creation, after setting all properties.
function bUbText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bUbText (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 bDotText_Callback(hObject, eventdata, handles)
% hObject    handle to bDotText (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 bDotText as text
%        str2double(get(hObject,'String')) returns contents of bDotText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'B Dot Term';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.b_dot = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.b_dot);

        msgbox(errMsg,'Invalid B Dot Term','error');
    end

% --- Executes during object creation, after setting all properties.
function bDotText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bDotText (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 bDotOptCheckbox.
function bDotOptCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to bDotOptCheckbox (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 bDotOptCheckbox
    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');
    linearTangentModel.varBDot = logical(hObject.Value);

    if(hObject.Value)
        handles.bDotLbText.Enable = 'on';
        handles.bDotUbText.Enable = 'on';
    else
        handles.bDotLbText.Enable = 'off';
        handles.bDotUbText.Enable = 'off';
    end

function bDotLbText_Callback(hObject, eventdata, handles)
% hObject    handle to bDotLbText (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 bDotLbText as text
%        str2double(get(hObject,'String')) returns contents of bDotLbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'B Dot Term Lower Bound';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.bDotLb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.bDot);

        msgbox(errMsg,'Invalid B Dot Term Lower Bound','error');
    end

% --- Executes during object creation, after setting all properties.
function bDotLbText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bDotLbText (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 bDotUbText_Callback(hObject, eventdata, handles)
% hObject    handle to bDotUbText (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 bDotUbText as text
%        str2double(get(hObject,'String')) returns contents of bDotUbText as a double
    newInput = get(hObject,'String');
    newInput = attemptStrEval(newInput);
    set(hObject,'String', newInput);

    linearTangentModel = getappdata(handles.lvd_EditLinearTangentModelGUI,'linearTangentModel');

    errMsg = {};

    value = str2double(get(hObject,'String'));
    enteredStr = get(hObject,'String');
    numberName = 'B Dot Term Upper Bound';
    lb = linearTangentModel.bDotLb;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(value, numberName, lb, ub, isInt, errMsg, enteredStr);

    if(isempty(errMsg))
        linearTangentModel.bDotUb = value;
    else
        hObject.String = fullAccNum2Str(linearTangentModel.bDotUb);

        msgbox(errMsg,'Invalid B Dot Term Upper Bound','error');
    end

% --- Executes during object creation, after setting all properties.
function bDotUbText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to bDotUbText (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: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function timespvals(options, n, d)
% TIMESPVALS   Measure the performance of SPVALS
%    TIMESPVALS(OPTIONS)  Script file to test the performance of the
%    sparse grid interpolation routine SPVALS by measuring the
%    required time to compute the hierarchical surpluses. By default,
%    the Clenshaw-Curtis grid is used. Other grid types can be
%    selected using the SPSET method.
%
%    TIMESPVALS(OPTIONS, D)  argument D contains the dimension that
%    the performance should be measured and graphed for, N
%
% Note: This demo takes a couple of minutes to run.
%
%    See also SPSET, SPVALS, TESTFUNCTIONS.

% Author : Andreas Klimke, Universitaet Stuttgart
% Version: 1.6
% Date   : May 31, 2006

% ------------------------------------------------------------
% Sparse Grid Interpolation Toolbox
% Copyright (c) 2006 W. Andreas Klimke, Universitaet Stuttgart
% Copyright (c) 2007-2008 W. A. Klimke. All Rights Reserved.
% See LICENSE.txt for license.
% email: klimkeas@ians.uni-stuttgart.de
% web  : http://www.ians.uni-stuttgart.de/spinterp
% ------------------------------------------------------------

if nargin < 1, options = []; end
if nargin < 2, n = []; d = []; end

sparseIndices = spget(options, 'SparseIndices', 'auto');
gridtype = spget(options, 'GridType', 'Clenshaw-Curtis');
enableDCT = spget(options, 'EnableDCT', 'on');

plotasymptotic = 0;

% Set the problem dimensions and the maximum discretization levels
% for each dimension.
switch lower(gridtype)
 case 'clenshaw-curtis'
  if isempty(d)
    d = [1,2,4,8,16];
    n = [17,13,10,6,4];
  end
  if strcmpi(sparseIndices, 'off')
    plotasymptotic = 1;
  end
 case 'noboundary'
  if isempty(d)
    d = [1,2,4,8,16];
    n = [15,11,8,5,4];
  end
 case 'maximum'
	if isempty(d)
    d = [1,2,4,8];
    n = [16,12,7,2];
  end
 case 'chebyshev'
  if isempty(d)
    d = [1,2,4,8,16];
    if strcmpi(enableFFT, 'on')
      n = [17,13,10,6,4];
    else
      n = [15,13,10,6,4];
    end
  end
 otherwise
	error('Unknown grid type.');
end

ndims = length(n);
markers = ['s', '.', 'd', '+', 'o', 'x', '*', 'v', '^'];

%  Compute random constants w and c for Gerz' test functions.
w = rand(d(end),1);
c = rand(d(end),1);
sumc = sum(c,1);
sumw = sum(w,1);
c = 1.5.*c/sumc;
w = w/sumw;

time = NaN*ones(ndims,n(1)+1);
npoints = zeros(ndims,n(1)+1);

for m = 1:ndims
	disp(['Current dim: ' num2str(d(m))]);
	z = [];
	for l = 0:n(m)
		disp(['Current level n = ' num2str(l) '...']);
		options = spset('MinDepth',l,'MaxDepth',l,'Vectorized','on', ...
										'GridType', gridtype, 'EnableDCT', enableDCT, ...
										'SparseIndices', sparseIndices, 'PrevResults', z);
		z = spvals('testfunctions',d(m),[],options,1,c(1:d(m)),w(1: ...
																									d(m)));
		t = z.surplusCompTime;
		disp(['Computing sparse grid points and evaluating function took ' ...
					num2str(z.fevalTime) ' [s].']);
		time(m,l+1) = t;
		disp(['Computing hierarchical surpluses took ' num2str(t) ' [s].']);
		disp(' ');
		npoints(m,l+1) = z.nPoints;
	end
end

% Plot results
h = loglog(npoints(:,2:end)', time(:,2:end)', 'LineWidth', 1);
axis tight;
for k = 1:ndims
	set(h(k), 'Marker', markers(k));
	hold on;
end
axis manual;

% Plot assymtotic curves for two cases
if plotasymptotic
	for nd = [1 ndims]
		asymptotic = zeros(n(nd),1);
		for k = 0:n(nd)
			levelseq = double(spgetseq(k,d(nd))');
			seqpoints = prod((levelseq <= 1) .* 2.^levelseq + ...
											 (levelseq > 1) .* 2.^(levelseq-1));

			asymptotic(k+1) = sum((prod(levelseq+1)-1).*seqpoints)*min(n(nd),d(nd));
			if k > 0
				asymptotic(k+1) = asymptotic(k+1) + asymptotic(k);
			end
		end
		const = 1./asymptotic(end).*time(nd,n(nd)+1);
		plot(npoints(nd,1:n(nd)+1),asymptotic.*const,'k--');
	end
end

% Add legend and axis labels
hold off;
title(['Time to compute hierarchical surpluses for ' gridtype ' grid']);
ylabel('time [s]');
xlabel('number of nodes N');
s = {};
for k = 1:ndims
  s{k} = ['d = ' num2str(d(k))];
end

if plotasymptotic
	s{ndims+1} = 'asymptotic';
end
legend(s,2);

author: johannesgerer

repo: jburkardt-m


text:
function write_gdf(filename, hdr, data);
% WRITE_GDF(filename, header, data)
% Writes a GDF file from the given header (only label, Fs, nChans are of interest)
% and the data (unmodified). Digital and physical limits are derived from the data
% via min and max operators. The GDF file will contain N records of 1 sample each,
% where N is the number of columns in 'data'.

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

[nChans,N] = size(data);
if hdr.nChans ~= nChans
  error 'Data dimension does not match header information';
end
fSample = real(hdr.Fs(1)); % make sure this is a scalar + real

labels = char(zeros(nChans, 16));
% labels
for n=1:nChans
  ln = length(hdr.label{n});
  if ln > 16
    fprintf(1, 'Warning: truncating label %s to %s\n', hdr.label{n}, hdr.label{n}(1:16));
    ln = 16;
  end
  labels(n,1:ln) = hdr.label{n}(1:ln);
end

if ~isreal(data)
  error 'Cannot write complex-valued data.';
end

switch class(data)
  case 'int8'
    gdfType = 1;
  case 'uint8'
    gdfType = 2;
  case 'int16'
    gdfType = 3;
  case 'uint16'
    gdfType = 4;
  case 'int32'
    gdfType = 5;
  case 'uint32'
    gdfType = 6;
  case 'int64'
    gdfType = 7;
  case 'uint64'
    gdfType = 8;
  case 'single'
    gdfType = 16;
  case 'double'
    gdfType = 17;
  otherwise
    error 'Unrecognized data type';
end

% TODO: check if this makes sense
% will be terrible for appending data...
digMin = double(min(data,[],2));
digMax = double(max(data,[],2));
physMin = digMin;
physMax = digMax;

%struct GDF_Header {
%	char version[8];
%	char patient[66];
% uint8_t reserved[10];
%	uint8_t smokingAlcoholDrugMedication;
%	uint8_t weight;
%	uint8_t height;
%	uint8_t genderHandedVisualHeart;
%	char recordingId[64];
%	uint32_t recordingLocation[4];
%	uint32_t recordingTime[2];
%	uint32_t birthday[2];
%	uint16_t headerLengthInBlocks;
%	uint8_t patientClass[6];
%	uint64_t equipmentId;
%	uint8_t reserved2[6];
%	uint16_t headsize[3];
%	float posRefElec[3];
%	float posGroundElec[3];
%	int64_t numDataRecords;
%	uint32_t durDataRecord[2];
%	uint16_t numChannels;
%	uint16_t reserved3;

fid = fopen(filename, 'wb', 'ieee-le');
% first write fixed part
fprintf(fid, 'GDF 2.20'); %version
fwrite(fid, zeros(1,66), 'int8'); % patient
fwrite(fid, zeros(1,10+4), 'uint8'); % reserved + smoking/weight/height/gender
fwrite(fid, zeros(1,64), 'int8');    % recording ID
fwrite(fid, zeros(1,4), 'uint32');   % recording location
secSince2000 = etime(clock, [2000 1 1 0 0 0]);
fwrite(fid, secSince2000, 'uint32'); % recording time in seconds since 2000/1/1
fwrite(fid, 0, 'int32'); % fractional part ignored

fwrite(fid, zeros(1,2), 'uint32'); % birthday
hdrLengthInBlocks = nChans + 1; % 256 bytes = 1 block per channel + 256 bytes for fixed header
fwrite(fid, hdrLengthInBlocks, 'uint16');
fwrite(fid, zeros(1,6), 'uint8'); % patient class
fwrite(fid, 0, 'uint64'); % equipment ID
fwrite(fid, zeros(1,6), 'uint8'); % reserved2
fwrite(fid, zeros(1,3), 'uint16'); % headsize
fwrite(fid, zeros(1,6), 'single'); % posRefElec + posGroundElec

fwrite(fid, N, 'int64'); % numDataRecords = #samples
[num,den] = rat(1.0/fSample); % sample rate as rational number
fwrite(fid, num, 'uint32');   % nominator
fwrite(fid, den, 'uint32');   % denominator
fwrite(fid, nChans, 'uint16'); % number of channel
fwrite(fid, zeros(1,1), 'uint16'); % reserved3

% now variable part of header, 256 bytes per channel
fwrite(fid, labels', 'char*1');
fwrite(fid, zeros(80,nChans), 'uint8'); % Types
fwrite(fid, zeros(6,nChans), 'uint8'); % PhysDim
fwrite(fid, zeros(1,nChans), 'uint16'); % PhysDimCode

fwrite(fid, physMin, 'double'); % physical minimum
fwrite(fid, physMax, 'double'); % physical maximum
fwrite(fid, digMin, 'double');  % digital minimum
fwrite(fid, digMax, 'double');  % digital maximum
fwrite(fid, zeros(68,nChans), 'uint8'); % pre-filter information
fwrite(fid, zeros(nChans, 3), 'single'); % lowpass, highpass, notch
fwrite(fid, ones(1, nChans), 'int32'); % samples per record = 1
fwrite(fid, gdfType*ones(1, nChans), 'uint32'); % gdf data type
fwrite(fid, zeros(nChans, 3), 'single'); % sensor position
fwrite(fid, zeros(nChans, 20), 'uint8'); % sensor description

fwrite(fid, data, class(data));
fclose(fid);

author: PatternRecognition

repo: OpenBMI


text:
function imgLogLuv = float2LogLuv(img)
%
%       imgLogLuv=float2LogLuv(img)
%
%
%        Input:
%           -img: a HDR image in RGB
%
%        Output:
%           -imgLogLuv: the HDR image in the 32-bit LogLuv format
%
%     Copyright (C) 2011  Francesco Banterle
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
%

%is it a three color channels image?
check3Color(img);

%Conversion from RGB to XYZ
imgXYZ = ConvertRGBtoXYZ(img, 0);

imgLogLuv = zeros(size(img));

%Encoding luminance Y
Le = floor(256*(log2(imgXYZ(:,:,2))+64));
imgLogLuv(:,:,1) = ClampImg(Le,0,65535);

%CIE (u,v) chromaticity values
norm = (imgXYZ(:,:,1)+imgXYZ(:,:,2)+imgXYZ(:,:,3));
x = imgXYZ(:,:,1)./ norm;
y = imgXYZ(:,:,2)./ norm;

%Encoding chromaticity
norm_uv = (-2*x+12*y+3);
u_prime = 4*x./norm_uv;
v_prime = 9*y./norm_uv;

Ue = floor(410*u_prime);
imgLogLuv(:,:,2) = ClampImg(Ue,0,255);

Ve = floor(410*v_prime);
imgLogLuv(:,:,3) = ClampImg(Ve,0,255);

end

author: banterle


text:
function res = ne(p,q)
%NE           Implements  p ~= q  for polynomials
%
%Result 1 iff p and q are mathematically not identical
%

% written  08/28/00     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
%

  p = removevars(permvars(polynom(p),'lex'));
  q = removevars(permvars(polynom(q),'lex'));
  res = ~( isequal(p.e,q.e) & isequal(p.c,q.c) & isequal(p.v,q.v) );

repo: OpenMAS


text:
function trxGraphicParams=cookTrxGraphicParams(trxGraphicParamsRaw)

trxGraphicParams=cookMarkerParams(trxGraphicParamsRaw);
if isfield(trxGraphicParamsRaw,'colormap') && ~isempty(trxGraphicParamsRaw.colormap)
  trxGraphicParams.colormap = trxGraphicParamsRaw.colormap;
else
  trxGraphicParams.colormap = 'jet';
end
if isfield(trxGraphicParamsRaw,'colormap_multiplier') && ~isempty(trxGraphicParamsRaw.colormap_multiplier)
  trxGraphicParams.colormap_multiplier = trxGraphicParamsRaw.colormap_multiplier;
else
  trxGraphicParams.colormap_multiplier = 0.7;
end

if isfield(trxGraphicParamsRaw,'assignment') && ~isempty(trxGraphicParamsRaw.assignment)
  trxGraphicParams.assignment = trxGraphicParamsRaw.assignment;
else
  trxGraphicParams.assignment = 'random';
end

end

author: kristinbranson

repo: JAABA


text:
function score = readHTKmlf(file_name)

FID = fopen(file_name,'r');

mask = {'sil','sp','one','two','three','four','five','six','seven','eight'...
    'nine','oh','zero'};

cnt = 1;
tmp = textscan(FID,'%s',1);
while 1
    tmp = textscan(FID,'%s',1);
    if(isempty(tmp{1})) % if it is the end of the file
        textscan(FID,'%s',1);
        break;
    end
    utt_name = tmp{1}{1}(4:length(tmp{1}{1})-5);
    score.name{cnt} = utt_name;
    score.(utt_name) = struct;

    for i=1:13  % initialize the model count
        model_cnt.(mask{i}) = 0;
    end
    while 1
        tmp = textscan(FID,'%d %d %s %f %s',1);
        if(isempty(tmp{1})) %if it is the end of a model
            textscan(FID,'%s',1);
            break;
        end

        idx1 = findstr(tmp{3}{1},'[');
        idx2 = findstr(tmp{3}{1},']');
        state = str2num( tmp{3}{1}(idx1+1:idx2-1) );
        if state==2 % if it is the start of a model
            % if there is multiple identical model, number them as model1,
            % model2,...
            model = tmp{3}{1}(1:idx1-1);
            model_cnt.(model) = model_cnt.(model) + 1;
            model = sprintf('%s%d',model,model_cnt.(model));
        end
        state = str2num( tmp{3}{1}(idx1+1:idx2-1) );    %state number
        score.(utt_name).(model)(state-1,1) = double(tmp{1})/10^5;  %start frame
        score.(utt_name).(model)(state-1,2) = double(tmp{2})/10^5;  %stop frame
        score.(utt_name).(model)(state-1,3) = tmp{4};   % state likelihood
    end
    cnt = cnt + 1;
end
fclose(FID);

author: singaxiong

repo: SignalGraph


text:
function xPol=Cart2DState2PolarState(xCart,systemType)
%%CART2DSSTATE2POLARSTATE Transform a 2D Cartesian state into a state
%                         consisting of position, heading and speed as well
%                         as possibly a turn rate and a linear
%                         acceleration, depending on the choice of
%                         systemType.
%
%INPUTS: xCart A Cartesian state vector consisting of position velocity and
%              possibly acceleration into a state where heading and speed
%              have been separated. xCart has the form
%              [x;y;xdot;ydot;xddot;yddot], where the acceleration terms
%              xddot;yddot can be omitted if the system type is 'ConstVel'.
%   systemType A string constant specifying the desired type of output. In
%              all instances, the heading is measured in terms of radians
%              counterclockwise from the x-axis. Possible values are:
%              'ConstVel'     The target state is [position;heading;speed]
%                             and xCart is [position;velocity]
%              'ConstAccel'   The target state is [position;heading;speed;
%                             speed derivative] and xCart is
%                             [position;velocity;acceleration]
%              'ConstTurn'    The target state is [position;heading;speed;
%                             turn rate] and xCart is
%                             [position;velocity;acceleration]
%              'TurnAndAccel' The target state is [position;heading;speed;
%                             turnrate; speed derivative] and xCart is
%                             [position;velocity;acceleration]
%
%OUTPUTS: xPol The state converted from 2D Cartesian coordinates into the
%              selected 2D coordinate system.
%
%When the system type is 'ConstVel' or 'TurnAndAccel', only a single
%solution is mathematically observable. When the system type is
%'ConstAccel' or 'ConstTurn', the system is overdetermined, but only a
%simple solution is used, not a least squares solution.
%
%The use of 2D states where the heading and speed have been separated is
%discussed in [1] and [2].
%
%The opposite of this function is polar2DState2CartState.
%
%REFERENCES:
%[1] M. Busch and S. Blackman, "Evaluation of IMM filtering for an air
%    defense system application," in Proceedings of SPIE: Signal and Data
%    Processing of Small Targets, vol. 2561, 9 Jul. 1995, pp. 435-447.
%[1] J. L. Gertz, "Multisensor surveillance for improved aircraft
%    tracking," The Lincoln Laboratory Journal, vol. 2, no. 3, pp. 381-396,
%    1989.
%
%July 2014 David F. Crouse, Naval Research Laboratory, Washington D.C.
%%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

%Get position
x=xCart(1);
y=xCart(2);
%Get velocity
xDot=xCart(3);
yDot=xCart(4);

switch(systemType)
    case 'ConstVel' %Given position, heading, and speed.
        xPol=[x;
              y;
              atan2(yDot,xDot);
              sqrt(yDot^2+xDot^2)];
    case 'ConstAccel'%Given position, heading, speed, and linear
                     %acceleration
        %Get acceleration
        xDdot=xCart(5);
        yDdot=xCart(6);

        theta=atan2(yDot,xDot);%Heading
        %Determine the sign of the derivative velocity, ignoring the possible
        %effects of noise...
        vDot=sqrt(yDdot^2+xDdot^2);%Linear acceleration

        diff1=(vDot*cos(theta)-xDdot)^2+(vDot*sin(theta)-yDdot)^2;
        diff2=(-vDot*cos(theta)-xDdot)^2+(-vDot*sin(theta)-yDdot)^2;
        if(diff2<diff1)
            vDot=-vDot;
        end
        xPol=[x;
              y;
              theta;
              sqrt(yDot^2+xDot^2);
              vDot];
    case 'ConstTurn' %Given position, heading, speed, and turn rate.
        %Get acceleration
        xDdot=xCart(5);
        yDdot=xCart(6);

        %Turn rate
        omega=(xDot*yDdot-yDot*xDdot)/(xDot^2+yDot^2);

        if(~isfinite(omega))
            omega=0;
        end

        xPol=[x;
              y;
              atan2(yDot,xDot);
              sqrt(yDot^2+xDot^2);
              omega];
    case 'TurnAndAccel'%Given position, heading, speed, turn rate, and
                       %linear acceleration.
        %Get acceleration
        xDdot=xCart(5);
        yDdot=xCart(6);

        theta=atan2(yDot,xDot);%Heading
        v=sqrt(yDot^2+xDot^2);%Speed
        omega=(yDdot*cos(theta)-xDdot*sin(theta))/v;%Turn rate

        %Deal with slow speed targets.
        if(~isfinite(omega))
            omega=0;
        end

        %Linear acceleration
        vDot=xDdot*cos(theta)+yDdot*sin(theta);

        xPol=[x;
              y;
              theta;
              v;
              omega;
              vDot];
    otherwise
        error('Invalid system type given.')
end

end

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

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
function a = nnEpsilonGreedyExploration(Q, actions, epsilon)

    n_actions = length(actions);

    if(rand() > epsilon)

        [Q_value, a] = max(Q);

    else

        a = randi(n_actions);

    end
end

author: kennydl

repo: Reinforcment-Learning-With-Q-Learning


text:
% Copyright 2019 Jonas Koenemann, Moritz Diehl, University of Freiburg
% Redistribution is permitted under the 3-Clause BSD License terms. Please
% ensure the above copyright notice is visible in any derived work.
%
function assertAlmostEqual(a,b,msg,eps)

  if nargin<=2
    msg = '';
  end

  if nargin<=3
    eps = 1e-4;
  end

  a = a(:);
  b = b(:);
  assert(all(abs(a-b)<=eps), msg);

end

author: OpenOCL

repo: OpenOCL

save_path: github-repos/MATLAB/OpenOCL-OpenOCL


%==============================================================================
% (c) Lars Ruthotto 2010/12/27, see FAIR.2 and FAIRcopyright.m.
% http://www.mic.uni-luebeck.de/people/lars-ruthotto.html
%
% function [t,Yt,LSiter,LS] = ArmijoBacktrackFEM(objFctn,Yc,dY,Jc,dJ,varargin)
%
% Armijo linesearch with additional volume control to guarantee a
% diffeomorphic update of the current iterate.
%
% That is, the Armijo condition  of sufficient descent
%                        objFctn( Yc + t*dY ) <= Jc + t*LSreduction*(dJ*dY)
% is accompanied by the condition
%                        min(vol( Yc + t*dY )) > 0
% which garantees that the nodal grid Yc + t*dY is diffeomorphic.
%
% if min(vol( Yc + t*dY ))>0 && objFctn( Yc + t*dY ) <= Jc + t*LSreduction*(dJ*dY),
%   success!
% endIf
% t=2^-[0:10], else: t=0, no success
%
% Input:
%   objFctn    function handle to the objective function
%   Yc         current vlue of Y
%   dY         search direction
%   Jc         current function value
%   dJ         current gradient
%  varargin    optional parameters, see below
%
% Output:
%  t      steplength
%  Yt      new iterate
%  LSiter    number of steps performed
%  LS      flag for success
%
% see, e.g.,
%  @Book{NocWri1999,
%      author = {J. Nocedal and S. J. Wright},
%       title = {Numerical optimization},
%        year = {1999},
%   publisher = {Springer},
%     address = {New York},
%  }
% and
%  @article{2011-BMR,
%	Author = {Burger M., Modersitzki J., Ruthotto L. },
%	Publisher = {University of Muenster},
%	Title = {A hyperelastic regularization energy for image registration},
%	Year = {2011}
%  }
%
% see also ArmijoBacktrack.m (version for nodal grids)
%==============================================================================

function [t,Yt,LSiter,LS] = ArmijoDiffeomorphicFEM(objFctn,Yc,dY,Jc,dJ,varargin)

if nargin == 0,
  help(mfilename)
  return;
end;

LSMaxIter   = 10;           % max number of trials
LSreduction = 1e-4;         % slope of line
para        = [];

for k=1:2:length(varargin), % overwrites default parameter
  eval([varargin{k},'=varargin{',int2str(k+1),'};']);
end;

t = 1; descent =   dJ * dY;
LS = 0; DIFFEOMORPHIC = 1;
for LSiter =1:LSMaxIter,
  Yt = Yc + t*dY; 			       % compute test value Yt
  V =  volTetraGrid(para.Mesh,Yt,'matrixFree',1);
  DIFFEOMORPHIC = (min(V(:))>0);    % check if update is diffeomorphic
  if DIFFEOMORPHIC,
    Jt = objFctn(Yt);              % evalute objective function
    LS = (Jt<Jc + t*LSreduction*descent); % compare
    if LS, break; end;             % success, return
  end
  t = t/2;                         % reduce t
end;
if LS, return; end;                % we are fine
if not(DIFFEOMORPHIC),
    fprintf(['Line Search failed (No diffeomorphic update could be found)'...
        '- norm(dY)=%1.3e - break \n'],norm(dY));
elseif not(LS)
    fprintf(['Line Search failed (No sufficient descent found) '...
        '- norm(dY)=%1.3e - break\n'],norm(dY));
end
t = 0; Yt = Yc;        % take no action


text:
function centroids = computeCentroids(X, idx, K)
%COMPUTECENTROIDS returns the new centroids by computing the means of the
%data points assigned to each centroid.
%   centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by
%   computing the means of the data points assigned to each centroid. It is
%   given a dataset X where each row is a single data point, a vector
%   idx of centroid assignments (i.e. each entry in range [1..K]) for each
%   example, and K, the number of centroids. You should return a matrix
%   centroids, where each row of centroids is the mean of the data points
%   assigned to it.
%

% Useful variables
[m n] = size(X);

% You need to return the following variables correctly.
centroids = zeros(K, n);

% ====================== YOUR CODE HERE ======================
% Instructions: Go over every centroid and compute mean of all points that
%               belong to it. Concretely, the row vector centroids(i, :)
%               should contain the mean of the data points assigned to
%               centroid i.
%
% Note: You can use a for-loop over the centroids to compute this.
%

for i = 1:K
    centroids(i,:) = (X' * (idx == i)) / sum(idx == i);
end

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

end

author: Ayatans

repo: Machine-Learning-homework


text:
function drawbox(varargin)
% function drawbox(width,height, param, properties)
%                 ([width,height], param, properties)
%
%   param, properties are optional
%

%% Copyright (C) Jongwoo Lim and David Ross.
%% All rights reserved.

%----------------------------------------------------------
% Process the input.
%----------------------------------------------------------
if (length(varargin{1}) == 2)
  w = varargin{1}(1);
  h = varargin{1}(2);
  varargin(1) = [];
else
  [w,h] = deal(varargin{1:2});
  varargin(1:2) = [];
end

if (length(varargin) < 1 || any(length(varargin{1}) ~= 6))
  M = [0,1,0; 0,0,1];
else
  p = varargin{1};
  if (length(varargin) > 1 && strcmp(varargin{2},'geom'))
    p = affparam2mat(p);
    varargin(1:2) = [];
  else
    varargin(1) = [];
  end
  M = [p(1) p(3) p(4); p(2) p(5) p(6)];
end

%----------------------------------------------------------
% Draw the box.
%----------------------------------------------------------

%corners = [ 1,0,0; 1,w,0; 1,w,h; 1,0,h; 1,0,0 ]';
corners = [ 1,-w/2,-h/2; 1,w/2,-h/2; 1,w/2,h/2; 1,-w/2,h/2; 1,-w/2,-h/2 ]';
corners = M * corners;
global result_corners;
global result_rect;
frame_num = 1;
result_corners(:,:,frame_num) = round(corners(:,1:4));
x=result_corners(1,1,frame_num);
y=result_corners(2,1,frame_num);
w=result_corners(1,3,frame_num)-result_corners(1,1,frame_num)+1;
h=result_corners(2,3,frame_num)-result_corners(2,1,frame_num)+1;
result_rect(:,frame_num) = [x y w h];

line(corners(1,:), corners(2,:), varargin{:});
% patch(corners(1,:), corners(2,:), 'y', ...
%       'FaceAlpha',0, 'LineWidth',1.5, varargin{:});

center = mean(corners(:,1:4),2);
hold_was_on = ishold; hold on;
% plot(center(1),center(2),varargin{:});
if (~hold_was_on) hold off; end

author: flyers

repo: drone-tracking


text:
function [C, dC] = gplvm_grad(x, X, sigma)
%GPLVM_GRAD Gradient of the Gaussian Process Latent Variable model
%
%   [C, dC] = gplvm_grad(x, no_dims, sigma)
%
% Computes the gradient of the Gaussian Process Latent Variable model.

% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology

    % Decode solution
    [n, d] = size(X);
    no_dims = numel(x) ./ n;
    Y = reshape(x, [n no_dims]);

    % Compute kernel matrix (in latent space)
    sum_Y = sum(Y .^ 2, 2);
    K = exp(bsxfun(@minus, bsxfun(@minus, 2 * (Y * Y'), sum_Y'), sum_Y) / (2 * sigma ^ 2));

    % Compute gradient with respect to kernel
%     invK = inv(K);
%     dLdK = invK * X * X' * invK - d * invK;
    tmp = (K \ X) * X';
    dLdK = (tmp - d * eye(n)) / K;

    % Compute gradient with respect to coordinates
    dC = zeros(n, no_dims);
    dLdK = K .* dLdK;
    for i=1:n
        dC(i,:) = sum(bsxfun(@times, dLdK(:,i), bsxfun(@minus, Y(i,:), Y)), 1);
    end
    dC = (-1 / sigma ^ 2) * dC(:);

    % Compute log-likelihood
    C = -((d * n) / 2) * log(2 * pi) - (d / 2) * log(det(K) + realmin) - .5 * trace(tmp);

repo: cluster


text:
%run_computeScores_globalModel applies the global model to the whole input images to produce multi-scale confidence heatmaps

% SETUP THESE PATHS TO RUN THE CODE
dataPath = 'data/HollywoodHeads';
resultPath = 'results/HollywoodHeads';

% network to evaluate
netFile = fullfile( 'models', 'global.mat' );

% file to store the scores
resultFile = fullfile( resultPath, 'global', 'globalModel-scores-test.mat' );

if ~exist(fullfile(resultPath, 'global'), 'dir')
    mkdir(fullfile(resultPath, 'global'));
end

% Choose subset of data to compute the scores.
%   To run the evaluation of the global model you need the test test (3).
scoreSubset = 3; % 1 - train subset, 2 - validation, 3 - test; can do [1,2,3] to compute scores on all the subsets

%% setup paths
filePath = fileparts( mfilename('fullpath') );
run( fullfile( fileparts( filePath ), 'setup.m' ) );

%% parameters
opts_cnn = struct;

opts_cnn.dataPath = dataPath;
opts_cnn.dataset.trainingSetFile = fullfile('Splits', 'train.txt');
opts_cnn.dataset.validationSetFile = fullfile('Splits', 'val.txt');
opts_cnn.dataset.testSetFile = fullfile('Splits', 'test.txt');
opts_cnn.dataset.groundTruthLocalPrefix = 'Annotations';
opts_cnn.dataset.imageLocalPrefix = 'JPEGImages';
opts_cnn.dataset.candidateLocalPrefix = 'Candidates';

opts_cnn.expDir =  resultPath;
opts_cnn.batchSize = 32;
opts_cnn.imdbName = 'globalModel';
opts_cnn.scoreMode = 'beforeSoftMax'; % 'beforeSoftMax' or 'afterSoftMax' or 'scoreDifference';

%% load dataset
opts_cnn.imdbPath = fullfile(opts_cnn.expDir, 'imdb.mat');
generateDataFlag = true;
if exist(opts_cnn.imdbPath, 'file')
    fprintf('Reading imdb file %s\n', opts_cnn.imdbPath);
    imdb = load(opts_cnn.imdbPath);
    if isfield(imdb, 'opts') && isequal( imdb.opts, opts_cnn.dataset )
        fprintf('imdb.opts is compatible with the opt_cnn.dataset\n')
    else
        warning('opts_cnn.dataset parameters are not compatible with the provided imdb file. Be careful!');
    end
else
    warning('imdb file is not found. Making it will take some time.');
    fprintf('Generating imdb file %s\n', opts_cnn.imdbPath);
    imdb = cnn_prepareData_localModel( opts_cnn.dataset, 'dataPath', opts_cnn.dataPath );
    imdb.opts = opts_cnn.dataset;
    mkdir(opts_cnn.expDir);
    save(opts_cnn.imdbPath, '-struct', 'imdb', '-v7.3') ;
end

%% load network
net = load( netFile, '-mat');
if ~isfield(net, 'layers') && isfield(net, 'net')
    net = net.net;
end
if ~isfield(net, 'layers')
    error('Could not load the network!');
end
net = vl_simplenn_move(net, 'gpu');

%% select the test set to run evaluation
imageSetToDoPr = false( numel( imdb.images.set ), 1 );
for iSubset = 1 : numel( scoreSubset )
    imageSetToDoPr = imageSetToDoPr | ( imdb.images.set(:) == scoreSubset( iSubset ) );
end
imageSetToDoPr = find( imageSetToDoPr );

%% start the evaluation
opts_cnn.getBatchEvaluation = struct;
opts_cnn.getBatchEvaluation.grid_size = [1 2 4 8];
opts_cnn.getBatchEvaluation.meanImage = net.normalization.averageImage;
opts_cnn.getBatchEvaluation.dataPath = opts_cnn.dataPath;
opts_cnn.getBatchEvaluation.jitterStd = 0;

batchWrapperEvaluation = @(imdb, batch) cnn_getBatch_globalModel(imdb, batch, ...
    opts_cnn.getBatchEvaluation) ;

scores = cnn_computeScores_globalModel( net, imdb, batchWrapperEvaluation, ...
    'imageSet', imageSetToDoPr, ...
    'batchSize', opts_cnn.batchSize, ...
    'scoreMode', opts_cnn.scoreMode);

if ~exist(fileparts(resultFile), 'dir')
    mkdir(fileparts(resultFile));
end
save( resultFile, 'scores', '-v7.3' );

%% save detections for files
detSavePath = fullfile( resultPath, 'global', 'dets');
if ~exist(detSavePath, 'dir')
    mkdir(detSavePath)
end
detSaveFormat = fullfile(detSavePath, '%s.mat');
disp('Saving detection files');
for i=1:length(imageSetToDoPr)
    imgIdx = imageSetToDoPr(i);
    score = scores{imgIdx};
    %load candidate
    [~, im_name, ~] = fileparts(imdb.imageFiles{imgIdx});
    savePath = sprintf(detSaveFormat, im_name);
    save(savePath, 'score');
end

author: aosokin


text:
function G = getGroupSuperNonOverlapColor(I, param)

    N = size(I,1) * size(I, 2);

    g = sparse(N,N);

    imlab = vl_xyz2lab(vl_rgb2xyz(I)) ;
    imlab = single(imlab);
    slicParam = param.superpixel.slicParam;

    groupCount = 0;

    segments = vl_slic(imlab, slicParam(1,1),  slicParam(1,2)) ;
    segments = segments(:);

    for j = 0:segments(N)
        g(:, groupCount+j+1) = segments==j;
    end
    groupCount  = groupCount+ segments(N)+1;

    % croping G
    g =g(:, 1:groupCount);

%     G = [g;g;g];

    groupCount = size(g,2);

    G = sparse( 3*N, 3*groupCount);

    G(1:N, 1:groupCount) = g;
    G(N+1:2*N, groupCount+1:2*groupCount) =g;
    G(2*N+1:3*N, 2*groupCount+1:3*groupCount) =g;
end

author: andrewssobral

repo: lrslibrary


text:
function a = borderband ( n )

%*****************************************************************************80
%
%% BORDERBAND returns the BORDERBAND matrix.
%
%  Formula:
%
%    If ( I = J )
%      A(I,I) = 1
%    else if ( I = N )
%      A(N,J) = 2^(1-J)
%    else if ( J = N )
%      A(I,N) = 2^(1-I)
%    else
%      A(I,J) = 0
%
%  Example:
%
%    N = 5
%
%     1  0   0   0   1
%     0  1   0   0  1/2
%     0  0   1   0  1/4
%     0  0   0   1  1/8
%     1 1/2 1/4 1/8  1
%
%  Properties:
%
%    A is symmetric: A' = A.
%
%    A is border-banded.
%
%    A has N-2 eigenvalues of 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 September 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real A(N,N), the matrix.
%
  a = zeros ( n, n );

  for i = 1 : n

    for j = 1 : n

      if ( i == j )
        a(i,j) = 1.0;
      elseif ( j == n )
        a(i,j) = 2.0^(1-i);
      elseif ( i == n )
        a(i,j) = 2.0^(1-j);
      else
        a(i,j) = 0.0;
      end

    end

  end

  return
end


text:
function [ x, error_norm, iter, flag ] = qmr ( A, x, b, M, max_it, tol )

%*****************************************************************************80
%
%% QMR usess the Quasi Minimal Residual Method with no preconditioning.
%
%  Modified:
%
%    27 March 2006
%
%  Reference:
%
%    Richard Barrett, Michael Berry, Tony Chan, James Demmel,
%      June Donato, Jack Dongarra, Victor Eijkhout, Roidan Pozo,
%      Charles Romine, Henk van der Vorst
%    Templates for the Solution of Linear Systems: Building Blocks for
%      Iterative Methods,
%    SIAM Publications, 1993.
%
%  Parameters:
%
%    Input, real A(N,N), the symmetric positive definite matrix.
%
%    Input, real X(N), the initial guess vector.
%
%    Input, real B(N), the right hand side vector.
%
%    Input, real M(N,N), the preconditioning matrix.  M is not used
%    by this routine, and it is included just so that the calling
%    sequence is similar to the other routines.
%
%    Input, integer MAX_IT, the maximum number of iterations.
%
%    Input, real TOL, an error tolerance.
%
%    Output, real X(N), the solution.
%
%    Output, real ERROR_NORM, the norm of the error.
%
%    Output, integer ITER, the number of iterations performed.
%
%    Output, integer FLAG, the return flag.
%    0 = the solution was found to within the specified tolerance.
%    1 = a satisfactory solution was not found.  The iteration limit
%        was exceeded.
%    -1 = breakdown caused by RHO;
%    -2 = breakdown caused by BETA;
%    -3 = breakdown caused by GAMMA;
%    -4 = breakdown caused by DELTA;
%    -5 = breakdown caused by EP;
%    -6 = breakdown caused by XI;
%
  iter = 0;

  bnrm2 = norm ( b );
  if ( bnrm2 == 0.0 )
    bnrm2 = 1.0;
  end

  r = b - A * x;
  error_norm = norm ( r ) / bnrm2;
  errorhist = [ ];
  errorhist(1) = error_norm;

  if ( error_norm < tol )
    flag = 0;
    return
  end

  flag = 1;

  v_tld = r;
  y = v_tld;
  rho = norm ( y );

  w_tld = r;
  z = w_tld;
  xi = norm ( z );

  gamma = 1.0;
  eta = -1.0;
  theta =  0.0;

  for iter = 1 : max_it

    if ( rho == 0.0 )
      flag = -1;
      break
    end

    if ( xi == 0.0 )
      flag = -6;
      break
    end

    v = v_tld / rho;
    y = y / rho;

    w = w_tld / xi;
    z = z / xi;

    delta = z' * y;

    if ( delta == 0.0 )
      flag = -4;
      break
    end

    y_tld = y;
    z_tld = z;
%
%  Compute the direction vector.
%
    if ( 1 < iter )
      p = y_tld - ( xi * delta / ep ) * p;
      q = z_tld - ( rho * delta / ep ) * q;
    else
      p = y_tld;
      q = z_tld;
    end

    p_tld = A * p;
    ep = q' * p_tld;

    if ( ep == 0.0 )
      flag = -5;
      break
    end

    beta = ep / delta;

    if ( beta == 0.0 )
      flag = -2;
      break
    end

    v_tld = p_tld - beta * v;
    y = v_tld;
    rho_1 = rho;
    rho = norm ( y );

    w_tld = ( A' * q ) - ( beta * w );
    z = w_tld;
    xi = norm ( z );
    gamma_1 = gamma;
    theta_1 = theta;

    theta = rho / ( gamma_1 * beta );
    gamma = 1.0 / sqrt ( 1.0 + theta^2 );

    if ( gamma == 0.0 )
      flag = -3;
      break
    end

    eta = -eta * rho_1 * gamma^2 / ( beta * gamma_1^2 );

    if ( 1 < iter )
      d = eta * p + ( ( theta_1 * gamma )^2 ) * d;
      s = eta * p_tld + ( ( theta_1 * gamma )^2 ) * s;
    else
      d = eta * p;
      s = eta * p_tld;
    end
%
%  Update the approximate solution.
%
    x = x + d;
    r = r - s;

    error_norm = norm ( r ) / bnrm2;
    errorhist(iter+1) = error_norm;

    if ( error_norm <= tol )
      flag = 0;
      break
    end

  end

  error_norm = errorhist;

  return
end


text:
function result = polygon_xy_2d ( n, x, y )

%*****************************************************************************80
%
%% POLYGON_XY_2D integrates the function X*Y over a polygon in 2D.
%
%  Integration region:
%
%    The polygon bounded by the points (X(1:N), Y(1:N)).
%
%  Formula:
%
%    INTEGRAL = (1/24) * SUM ( 1 <= I <= N )
%      ( Y(I)   * ( 3 * X(I)**2 + 2 * X(I) * X(I-1) +     X(I-1)**2 )
%      + Y(I-1) * (     X(I)**2 + 2 * X(I) * X(I-1) + 3 * X(I-1)**2 ) )
%      * ( Y(I) - Y(I-1) )
%
%    where X(0) and Y(0) should be replaced by X(N) and Y(N).
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    S F Bockman,
%    Generalizing the Formula for Areas of Polygons to Moments,
%    American Mathematical Society Monthly,
%    1989, pages 131-132.
%
%  Parameters:
%
%    Input, integer N, the number of vertices of the polygon.
%    N should be at least 3 for a nonzero result.
%
%    Input, real X(N), Y(N), the coordinates of the vertices
%    of the polygon.  These vertices should be given in
%    counter-clockwise order.
%
%    Output, real RESULT, the value of the integral.
%
  result = 0.0E+00;

  if ( n < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'POLYGON_XY_2D - Warning!\n' );
    fprintf ( 1, '  The number of vertices must be at least 3.\n' );
    fprintf ( 1, '  The input value of N = %d\n', n );
    error ( 'POLYGON_XY_2D - Fatal error!' );
  end

  for i = 1 : n

    if ( i == 1 )
      im1 = n;
    else
      im1 = i - 1;
    end

    result = result + ( ...
      y(i) * ( 3.0E+00 * x(i)^2 + 2.0E+00 * x(i) * x(im1) + x(im1)^2 ) ...
      + y(im1) * ( x(i)^2 + 2.0E+00 * x(i) * x(im1) + 3.0E+00 * x(im1)^2 ) ...
      ) * ( y(i) - y(im1) );

  end

  result = result / 24.0E+00;

  return
end


text:
function plotData(X, y)
%PLOTDATA Plots the data points X and y into a new figure
%   PLOTDATA(x,y) plots the data points with + for the positive examples
%   and o for the negative examples. X is assumed to be a Mx2 matrix.

% Create New Figure
figure; hold on;

% ====================== YOUR CODE HERE ======================
% Instructions: Plot the positive and negative examples on a
%               2D plot, using the option 'k+' for the positive
%               examples and 'ko' for the negative examples.
%

% Find Indices of Positive and Negative Examples
pos = find(y==1); neg = find(y == 0);
% Plot Examples
plot(X(pos, 1), X(pos, 2), 'k+', 'LineWidth', 2, 'MarkerSize', 7);
plot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);

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

hold off;

end

repo: machine-learning


text:
function ind = get_index(description,pattern)
M=length(description);
N=length(pattern);
ind=[];
for i=1:M
    for j=1:N
        if strcmp(description{i},pattern{j})
            ind(end+1)=i;
        end
    end
end
end

author: cliffordlab

repo: PhysioNet-Cardiovascular-Signal-Toolbox


text:
function spm_eeg_img2maps(S)
% Make a series of scalp maps from data in an image
% FORMAT  spm_eeg_img2maps(S)
%
% S         - input structure (optional)
% (optional) fields of S:
%    D              - M/EEG dataset containing the sensor locations
%    image          - file name of an image containing M/EEG data in voxel-space
%    window         - start and end of a window in peri-stimulus time [ms]
%    clim           - color limits of the plot
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: spm_eeg_img2maps.m 6669 2016-01-11 15:51:06Z guillaume $

SVNrev = '$Rev: 6669 $';

%-Startup
%--------------------------------------------------------------------------
spm('FnBanner', mfilename, SVNrev);
spm('FigName','Plot scalp maps');

if nargin == 0
    S = [];
end

%% -Input parameters
%--------------------------------------------------------------------------
if ~isfield(S, 'image')
    [S.image, sts] = spm_select(1, 'image', 'Select an M/EEG image (in voxel-space)');
    if ~sts, return; end
end

%-Get MEEG object
%--------------------------------------------------------------------------
try
    D = S.D;
catch
    [D, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');
    if ~sts, D = []; return; end
    S.D = D;
end

D = spm_eeg_load(D);

if ~isfield(S, 'window')
    S.window = spm_input('start and end of window [ms or Hz]', '+1', 'r', '', 2);
end

style = char(spm_input('Plot style','+1','SPM|FT|3D',{'spm','ft','3d'},1));

V = spm_vol(S.image);
Y = spm_read_vols(V);

Nt = size(Y, 3);

begsample = inv(V.mat)*[0 0 S.window(1) 1]';
begsample = begsample(3);

endsample = inv(V.mat)*[0 0 S.window(2) 1]';
endsample = endsample(3);

if any([begsample endsample] < 0) || ...
        any([begsample endsample] > Nt)
    error('The window is out of limits for the image.');
end

[junk begsample] = min(abs(begsample-[1:Nt]));
[junk endsample] = min(abs(endsample-[1:Nt]));

Y = squeeze(mean(Y(: , :, begsample:endsample), 3));

if any(diff(size(Y)))
    error('The image should be square');
else
    n = size(Y, 1);
end

%-Get channel indices and coordinates
%--------------------------------------------------------------------------
modality    = spm_eeg_modality_ui(D, 1, 1);

Cind = D.indchantype(modality, 'GOOD');

Cel = spm_eeg_locate_channels(D, n, Cind);

if isempty(Cind)
    error('No good channels to plot');
end

Y = Y(sub2ind(size(Y), Cel(:, 1), Cel(:, 2)));

%%
% SPM graphics figure
%--------------------------------------------------------------------------
Fgraph  = spm_figure('GetWin','Graphics'); spm_figure('Clear',Fgraph)

switch style
    case 'spm'
        if ~isfield(S, 'clim')
            in.max = max(abs(Y));
            in.min = -in.max;
        else
            in.min = S.clim(1);
            in.max = S.clim(2);
        end

        in.type = modality;
        in.f = Fgraph;
        in.ParentAxes = axes;

        spm_eeg_plotScalpData(Y, D.coor2D(Cind), D.chanlabels(Cind), in);
    case 'ft'

        dummy = [];
        dummy.dimord = 'chan_time';
        dummy.avg = Y;
        dummy.label = D.chanlabels(Cind);
        dummy.time  = 1e-3*mean(S.window);

        cfg = [];
        cfg.parameter = 'avg';
        cfg.comment = 'no';

        switch modality
            case 'EEG'
                cfg.elec = D.sensors('EEG');
            case 'MEG'
                cfg.grad = D.sensors('MEG');
        end
        cfg.zlim = max(abs(Y))*[-1 1];

        ft_topoplotER(cfg, dummy);

    case '3d'
        spm_eeg_headplot(Y, D, axes);
end
%%
%-Cleanup
%--------------------------------------------------------------------------
spm('FigName','Plot scalp maps: done');

author: spm


text:
function [V,D]=spreadeigs(K,coef);
%SPREADEIGS  Eigenpairs of Spreading operator
%   Usage: h=spreadeigs(K,c);
%
%   `spreadeigs(K,c)` computes the *K* largest eigenvalues and eigen-
%   vectors of the spreading operator with symbol *c*.
%
%   See also:  tconv, spreadfun, spreadinv, spreadadj

complainif_argnonotinrange(nargin,2,2,mfilename);

if ndims(coef)>2 || size(coef,1)~=size(coef,2)
    error('Input symbol coef must be a square matrix.');
end;

L=size(coef,1);

% This version explicitly constucts the matrix representation T
% and then applies this matrix as the final step.
coef=fft(coef);

T=zeros(L);
for ii=0:L-1
  for jj=0:L-1
    T(ii+1,jj+1)=coef(ii+1,mod(ii-jj,L)+1);
  end;
end;

if nargout==2
  doV=1;
else
  doV=0;
end;

if doV
  [V,D]=eig(T);
else
  D=eig(T);
end;

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function T1 = uminus(T1)
% unary minus

T1.M = -T1.M;

author: mtex-toolbox

repo: mtex

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


text:
function sim = gaussianKernel(x1, x2, sigma)
%RBFKERNEL returns a radial basis function kernel between x1 and x2
%   sim = gaussianKernel(x1, x2) returns a gaussian kernel between x1 and x2
%   and returns the value in sim

% Ensure that x1 and x2 are column vectors
x1 = x1(:); x2 = x2(:);

% You need to return the following variables correctly.
sim = 0;

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return the similarity between x1
%               and x2 computed using a Gaussian kernel with bandwidth
%               sigma
%
%
diff = x1 - x2;
sqDiff = diff.^2;
sim = exp(-sum(sqDiff)/(2*sigma*sigma));

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

end

author: AvaisP


text:
function z = compute_zeros(x,y)

% compute_zeros - compute the location of zeros
%
% z = compute_zeros(x,y)
%
%   find the roots z of f(z)=0 where f is sampled at y=f(x)
%
%   Copyright (c) 2007 Gabriel Peyre

I = find( y(1:end-1).*y(2:end) < 0);

d = y(I+1)-y(I);
J = find(d==0); d(J) = 1;
z = ( x(I).*y(I+1)-x(I+1).*y(I) )./d;
z(J) = (x(I(J))+x(I(J)+1))/2;

author: gpeyre

repo: matlab-toolboxes


text:
function vectors3d(varargin)
%VECTORS3D Description of functions operating on 3D vectors
%
%   Vectors are represented by their 3 Cartesian coordinates:
%   V = [VX VY VZ];
%
%   List of vectors are represented by N-by-3 arrays, with the coordinates
%   of each vector on a row.
%
%
%   See also
%   vectorNorm3d, normalizeVector3d, crossProduct3d, vectorAngle3d
%   isParallel3d, isPerpendicular3d, createTranslation3d
%   drawVector3d
%

% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2008-10-13,    using Matlab 7.4.0.287 (R2007a)
% Copyright 2008 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
function h = mrvPanel(loc, sz, par, units, varargin);
%
% h = mrvPanel([loc], [sz], [par], [units], [other properties]);
%
% UI tool for mrVista 2.0:
% Add a uipanel (for a group of related controls
% or axes) to a parent figure/other object in the
% specified position,  while maintaining the size of
% the other objects in the figure. Returns a handle
% to the panel.
%
% loc: string specifying where to add the panel. Can be
% 'top', 'bottom', 'left', 'right'. [Default 'right'] The
% panel will cover the entire width (for 'top' or 'bottom')
% or height (for 'left' or 'right') of the object,  and will
% make the figure larger.
%
% sz: number specifying the width or height of the panel,  in the
% panel's units (see below). [Default 0.1,  normalized]
%
% par: parent object. Usually a figure,  but could theoretically
% be another uipanel (nesting panels within panels). [Default gcf]
%
% units: units to specify for the panel. [Default 'normal',  normalized
% to par object] But could be e.g. 'char' for characters
% or 'pixels' for pixels relative to corner of par object.
%
% NOTE: if 'normalized' units are specified,  this is taken
% to mean 'normalized with respect to parent object',
% rather than 'normalized w.r.t. screen': e.g.,  if sz=0.25,
% this means the panel size will be a quarter the size of
% the figure,  not make the figure take up a quarter more
% of the screen.
%
%
% OPTIONAL PROPERTIES:
% There are many other properties of uipanels which may
% be useful to GET/SET; see HELP UIPANEL or DOC UIPANEL
% for more info. You may set these properties when you call
% mrvPanel by specifying them in the optional arguments, in pairs
% of 'PropertyName', [Value], ... See the example below.
%
% EXAMPLES:
%
% h = mrvPanel('below', 2, gcf, 'char');
%
% adds a panel 2 characters high beneatch the current
% figure,  colored white and with a frame titled 'My Panel'.
%
% h2 = mrvPanel('right', .3, gcf, 'char', 'BackgroundColor', 'w', ...
%              'Title', 'My Panel');
%
% adds a panel to the right side of the current figure, at 30% its length,
% colored white and with a frame titled 'My Panel'.
%
% SEE ALSO:
% uipanel,  uicontrol,  uibuttongroup,  mrvShowPanel.
%
% ras,  07/05/05.
% ras,  09/25/06: allows panel properties to be set at creation.

% default arguments
if ~exist('loc', 'var') | isempty(loc),  loc = 'right';               end
if ~exist('sz', 'var') | isempty(sz),  sz = 0.1;                      end
if ~exist('par', 'var') | isempty(par),  par = gcf;                   end
if ~exist('units', 'var') | isempty(units),  units = 'normalized';    end

% check that the location arg makes sense
if ~ismember(lower(loc), {'above' 'below' 'left' 'right'})
    help(mfilename);
    error('Unrecognized location argument.');
end

% get the dimension along which the figure will be
% added (index into position vector):
switch lower(loc)
    case {'above', 'below'},  dim = 4;
    case {'left', 'right'},  dim = 3;
end
corner = dim-2; % index into position vector of corner

% get size of parent object in same units as panel:
exUnits = get(par,  'Units'); % existing units
set(par,  'Units',  units);
exPos = get(par,  'Position'); % existing position in same units as panel
exSize = exPos(dim); % size in same units as panel

% parse 'normalized' units to be w.r.t. figure;
% also,  set it so that the specified size is the
% fraction the figure takes after resizing:
% E.g.,  if sz is 1/2,  make the figure twice as big,
% one half of which is the new panel; NOT make it
% one-and-a-half times as big,  with one third being the
% new panel:
if strncmp(lower(units),  'norm',  4)
    sz = 1 / (1/sz - 1); % makes the specified sz proportion of final size
    sz = sz * exSize;
end

% figure out how much bigger the par will need to be
% to accommodate the new panel
newSize = exSize + sz; % fig size after adding panel

% meanwhile,  the 'panelSize' variable will describe the
% panel's size in normalized units relative to the parent.
% Also set this such that the
panelSize = sz/newSize; % if units were 'norm',  this should = the original
                        % value of sz

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% resize the parent object %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get new size -- make larger
newPos = exPos;
newPos(dim) = newSize;

% for panels in the below or left locations,  move the corner  back,
% so existing objects% stay in the same place on the screen
if ismember(lower(loc), {'left' 'below'})
    newPos(corner) = exPos(corner) - exPos(dim)/(1/panelSize+1);
end

% set the new parent position
set(par, 'Position', newPos);

% check that the new size doesn't push the figure off the
% screen edge -- if so,  move back:
figOffscreenCheck(gcf);

% get all existing child objects of the par object,
% so we can adjust their relative sizes
objs = findobj('Parent',  par,  'Type',  'uicontrol');
objs = [objs; findobj('Parent',  par,  'Type',  'axes')];
objs = [objs; findobj('Parent',  par,  'Type',  'uipanel')];

% existing objects in the parent will need to be shrunk
% along the relevant dimension by an amount corresponding
% to the growth of the par:
for i = 1:length(objs)
    objUnits = get(objs(i),  'Units');
    set(objs(i),  'Units',  'normalized'); % deal in normalized units for now
    objPos = get(objs(i),  'Position');   % pre-shrinking position
    objPos(dim) = objPos(dim) * (1-panelSize);

    % to keep existing panels flush with one another,
    % even after shrinking,  we need to nudge panels back:
    if objPos(corner) > 0
        objPos(corner) = objPos(corner) * (1-panelSize);
    end

    % for these locations,  need to move the corners
    % of existing objects forward as well:
    if ismember(lower(loc),  {'left' 'below'})
        objPos(corner) = objPos(corner) + panelSize;
    end

    set(objs(i),  'Position',  objPos);
    set(objs(i),  'Units',  objUnits); % restore previous unit convention
end

% figure out the position of the new panel
set(par, 'Units', 'normalized');
switch lower(loc)
    case 'above',  pos = [0 exSize/newSize 1 panelSize];
    case 'below',  pos = [0 0 1 panelSize];
    case 'left',  pos = [0 0 panelSize 1];
    case 'right',  pos = [exSize/newSize 0 panelSize 1];
end
set(par, 'Units', exUnits); % restore previous unit convention

% finally,  add the new panel
h = uipanel('Units', 'Normalized', 'Position', pos, ...
            'UserData', lower(loc), 'FontSize', 14, ...
			'BackgroundColor', get(gcf, 'Color'), ...
            'BorderType', 'none', 'Parent', par);
set(h, 'Units', units);

% set properties according to any optional arguments
for i = 1:2:length(varargin)
    set(h, varargin{i}, varargin{i+1});
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function status = tsinfo(filename)

% status = tsinfo(filename)
% display information about signal file 'filename'

trenner = '--------------------------------------------------------------------------------';

if exist(filename)
	sig = signal(filename);
	if isempty(sig)
		status = -1;
		warning(['Error opening file ' filename ]);
		return;
	else
		temp = dir(filename);
		filesize = num2str(temp.bytes);
		[path,Name,ext] = fileparts(filename);
		yunt = unit(yaxis(sig));
		string1 = { ...
		['Filename                        : ' filename] ; ...
		['Filesize                         : ' filesize ' bytes'] ; ...
		['Number of dimensions       : ' num2str(length(dlens(sig)))] ; ...
		['Length in each dimension   : ' num2str(dlens(sig))] ; ...
		['Total samples                  : ' num2str(prod(dlens(sig)))] ; ...
		trenner ; ...
 		['yname                           : ' name(yaxis(sig))] ; ...
		['yunit                              : '  name(yunt)] ; ...
		trenner };
		string2 = {};
% 		siz = size(sig.optparam);
% 		ende = siz(1);
% 		for i=1:ende
% 			string2 = addcomment(string2, [sig.optparam{i}]);
% 		end
%		string2 = addcomment(string2, trenner);
% 		string3 = {};
% 	   for i=1:length(dlens(sig))
% 			xax = xaxis(sig, i);
% 		   string3 = addcomment(string3, ['Dimension : ' num2str(i)]);
% 		   string3 = addcomment(string3, ['Length : ' num2str(dlens(sig, i))]);
% 		   string3 = addcomment(string3, ['xfirst : ' num2str(first(xax))]);
% 		   string3 = addcomment(string3, ['xdelta : ' num2str(delta(xax))]);
% 		   %string3 = addcomment(string3, ['xdelta^(-1) : ' num2str(1/delta(xax))]);
% 		   string3 = addcomment(string3, ['xunit : ' label(xax)]);
% 		   string3 = addcomment(string3, ['xname : ' name(xax)]);
% 		   string3 = addcomment(string3, trenner);
% 	   end
%
% 		string4 = { ['Comment :'] ; ''};
% 		string = addcomment(string3, trenner);
% 		string5 = { trenner; ['History :'] ; ''};
% 		string = cat(1, string1, string2, string3, string4, comment(sig), string5, history(sig));
%
		string = string1;
		handle = figure('Color', [1 1 1], ...
		'Resize','off', ...
		'NumberTitle','off', ...
		'KeyPressFcn','close(gcbf)', ...
		'MenuBar','none', ...
		'Name',['tsinfo on file ' Name]);
		pos = get(handle, 'Position');
		lbox = uicontrol('Parent',handle, ...
		'Units','points', ...
		'Position', [0.8 0.8 440 330], ...
		'BackgroundColor',[1 1 1], ...
		'String', string, ...
		'Style','listbox', ...
		'Tag','InfoListbox', ...
		'Value',1);
	end
else
	warndlg(['Can''t find file ' filename],'Info on File');
	status = -1;
	return;
end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function[varargout]=ridgeinterp(varargin)
% RIDGEINTERP  Interpolate quantity values onto ridge locations.
%
%   RIDGEINTERP is a low-level function called by RIDGEWALK.
%
%   XI=RIDGEINTERP(FS,RQ,IR,JR,X) where RQ is a "ridge quantity" at
%   *radian* frequencies FS, and IR and JR are time and scale indices of
%   ridges, interpolates quantity X along the ridge locations to give XI.
%
%   IR and JR give indices into the first two dimensions of X.  The output
%   XI has the the same number of rows and columns as IR and JR, that is,
%   SIZE(XI,1)=SIZE(IR,1) and SIZE(XI,2)=SIZE(IR,2).  The locations of
%   NANs in IR and JR are duplicated in XI.
%
%   X may have more than one 'page' along its third dimension, in which
%   case each page is interpolated separately, and SIZE(XI,3)=SIZE(X,3).
%
%   RQ is output by ISRIDGEPOINT based on a wavelet transform output by
%   WAVETRANS, and IR and JR are output by RIDGEWALK.
%
%   RIDGEINTERP interpolates transform values between discrete frequency
%   levels to find a more precise value of the transform along the ridges
%   than simply looking up the values of X at rows IR and columns JR.
%
%   XI=RIDGEINTERP(FS,RQ,IR,JR,MU,X) interprets the ridges as belonging
%   to the MU-th derivative of the signal to which the quantity X belongs
%   and applies an appropriate correction factor.
%
%   [XI1,XI2,...,XIN]=RIDGEINTERP(FS,RQ,IR,JR,X1,X2,...,XN) also
%   interpolates the quantities X1,X2,...,XN, all having the same number of
%   rows and columns as IR and JR.
%
%   RIDGEINTERP uses fast quadratic interpolation via QUADINTERP.  In rare
%   cases, quadratic interpolation fails for an individual point and
%   therefore linear interpolation is used instead.
%   __________________________________________________________________
%
%   RIDGEINTERP is a low-level function called by RIDGEWALK.
%
%   See also RIDGEWALK, ISRIDGEPOINT, QUADINTERP.
%
%   Usage:  xi=ridgeinterp(rq,ir,jr,x);
%           [xi1,xi2,xi3]=ridgeinterp(rq,ir,jr,x1,x2,x3);
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2005--2019 J.M. Lilly --- type 'help jlab_license' for details

rq=varargin{1};
ir=varargin{2};
jr=varargin{3};
varargin=varargin(4:end);

if iscell(varargin{end})||isempty(varargin{end})
    derivparams=varargin{end};
    varargin=varargin(1:end-1);
else
    derivparams=[];
end

index=find(~isnan(ir));
if ~isempty(index)
    varargout=ridgeinterp1_quadratic(index,ir,jr,derivparams,rq,varargin);
else
    for i=1:length(varargin)
        varargout{i}=[];
    end
end

function[outargs]=ridgeinterp1_quadratic(index,ir,jr,derivparams,rq,args)
sizeir=size(ir);
vcolon(ir,jr);
vindex(ir,jr,index,1);

indexr=nonnan(sub2ind(size(rq),ir,jr));

%Ridge quantity along the ridges, and at one scale up and down

di=size(rq,1);
dr=rq(indexr);
drp=rq(indexr+di);
drn=rq(indexr-di);

[~,jre]=quadinterp(jr-1,jr,jr+1,abs(drn).^2,abs(dr).^2,abs(drp).^2);

%Rare complete failure of quadratic interpolation associated
%with the ridge quantity changing sign between jrp and jrn, yet
%not having the ridge quantity at jr being between these two values

bool=~( (jr+1>jre) & (jre> jr-1));
jre(bool)=lininterp(jr(bool)-1,jr(bool)+1,drn(bool),drp(bool));

if ~isempty(derivparams)
    ga=derivparams{1};
    be=derivparams{2};
    mu=derivparams{3};

    fact=frac(morsefreq(ga,be-mu),morsefreq(ga,be));

    jro=frac(jr,fact);
    jrp=frac(jr+1,fact);
    jrn=frac(jr-1,fact);

    btop=(ceil(jro)>=(size(rq,2)-1));
    jro(btop)=size(rq,2)-1;
    jrp(btop)=size(rq,2);
    jrn(btop)=size(rq,2)-2;

    bbottom=(floor(jro)<=2);
    jro(bbottom)=2;
    jrp(bbottom)=3;
    jrn(bbottom)=1;

    %The problem here is that I also have to interpolate to find the
    %values of the quantities to be interpolated at the rescaled scale
    %levels, so you have to do another linear interpolation between
    %the floors and the ceilings.  You can't just do the above any
    %more because the rescaled scale levels are no longer jr+/-1.

%     figure,plot(jro)
%     maxmax(jro)
%     minmin(jro)
    indexrf=nonnan(sub2ind(size(rq),ir,floor(jro)));
    indexrc=nonnan(sub2ind(size(rq),ir,ceil(jro)));

    indexrpf=nonnan(sub2ind(size(rq),ir,floor(jrp)));
    indexrpc=nonnan(sub2ind(size(rq),ir,ceil(jrp)));

    indexrnf=nonnan(sub2ind(size(rq),ir,floor(jrn)));
    indexrnc=nonnan(sub2ind(size(rq),ir,ceil(jrn)));
end

for i=1:length(args)
   x=args{i};
   if isreal(x)
        xr=nan*ones(sizeir(1),size(x,3));
   else
        xr=(nan+sqrt(-1)*nan)*ones(sizeir(1),size(x,3));
   end
   for k=1:size(x,3)
        xk=x(:,:,k);
        if isempty(derivparams)
            xro=xk(indexr);
            xrp=xk(indexr+di);
            xrn=xk(indexr-di);
        else
            xro=lininterp(floor(jro),ceil(jro),xk(indexrf),xk(indexrc),jro);
            xrp=lininterp(floor(jrp),ceil(jrp),xk(indexrpf),xk(indexrpc),jrp);
            xrn=lininterp(floor(jrn),ceil(jrn),xk(indexrnf),xk(indexrnc),jrn);
        end

        xrk=quadinterp(jr-1,jr,jr+1,xrn,xro,xrp,jre);
        %Use linear interpolation where quadratic fails
        xrk(bool)=lininterp(jr(bool)-1,jr(bool)+1,xrn(bool),xrp(bool),jre(bool));
        xr(index,k)=xrk;
   end
   %Linearly interpolate between the approximate ridge and the bracketing curve
   outargs{i}=xr;
end

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab


text:
function triangulation_test12 ( )

%*****************************************************************************80
%
%% TEST12 tests TRIANGULATION_ORDER3_ADJ_COUNT, TRIANGULATION_ORDER3_ADJ_SET.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 August 2006
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST12\n' );
  fprintf ( 1, '  For an order3 triangulation:\n' );
  fprintf ( 1, '  TRIANGULATION_ORDER3_ADJ_COUNT counts adjacencies\n' );
  fprintf ( 1, '  TRIANGULATION_ORDER3_ADJ_SET sets adjacencies.\n' );
%
%  Get the sizes.
%
  [ node_num, triangle_num, hole_num ] = ...
    triangulation_order3_example1_size ( );
%
%  Get the data.
%
  [ node_xy, triangle_node, triangle_neighbor ] = ...
    triangulation_order3_example1 ( node_num, triangle_num );
%
%  Get the count of the adjacencies.
%
  [ adj_num, adj_col ] = triangulation_order3_adj_count ( node_num, ...
    triangle_num, triangle_node, triangle_neighbor );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of adjacency entries is %d\n', adj_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Adjacency pointers:\n' );
  fprintf ( 1, '\n' );
  for node = 1 : node_num
    fprintf ( 1, '  %8d  %8d  %8d\n', node, adj_col(node), adj_col(node+1)-1 );
  end
%
%  Get the adjacencies.
%
  adj = triangulation_order3_adj_set ( node_num, ...
    triangle_num, triangle_node, triangle_neighbor, adj_num, adj_col );
%
%  Print the adjacencies.
%
  for node = 1 : node_num

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Nodes adjacent to node %d\n', node );
    fprintf ( 1, '\n' );

    for k = adj_col(node) : adj_col(node+1)-1
      fprintf ( 1, '  %d\n', adj(k) );
    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function[]=noylabels(str)
%NOYLABELS   Remove some or all y-axis tick mark labels.
%
%   NOYLABELS by itself removes all tick mark labels on the current y-axis.
%
%   NOYLABELS MAX removes only the label of the maximum y-tick mark.
%
%   NOYLABELS MIN removes only the label of the minimum y-tick mark.
%
%   NOYLABELS ALL is the same as the default.
%
%   See also NOXLABELS.
%
%   Usage:  noylabels
%           noylabels xmin
%           noylabels ymin
%   _________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2004--2008 J.M. Lilly --- type 'help jlab_license' for details

if nargin==0
    str='all';
end

if strcmpi(str(1:3),'min')
    ylabels=get(gca,'yticklabel');
    ylabels(1,:)=' ';
    set(gca,'yticklabel',ylabels)
elseif strcmpi(str(1:3),'max')
    ylabels=get(gca,'yticklabel');
    ylabels(end,:)=' ';
    set(gca,'yticklabel',ylabels)
elseif strcmpi(str(1:3),'all')
    set(gca,'yticklabel',[])
end


text:
function display( x )
long = ~isequal(get(0,'FormatSpacing'),'compact');
if long, disp( ' ' ); end
disp(x);
if long, disp( ' ' ); end

% Copyright 2010 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

repo: REST


text:
function Write_CNN_to_binary(location_binary, cnn)

    addpath('../../../PDM_helpers/');

    % use little-endian
    cnn_binary_file = fopen(location_binary, 'w', 'l');

    num_layers = size(cnn.layers,2);

    % Get the number of layers
    fwrite(cnn_binary_file, num_layers, 'uint'); % 4 bytes

    for layers=1:num_layers

        % write layer type: 0 - convolutional, 1 - max pooling, 2 -
        % fully connected, 3 - prelu, 4 - sigmoid
        if(strcmp(cnn.layers{layers}.type, 'conv'))

            % write the type (convolutional)
            fwrite(cnn_binary_file, 0, 'uint'); % 4 bytes

            num_in_map = size(cnn.layers{layers}.weights{1},3);

            % write the number of input maps
            fwrite(cnn_binary_file, num_in_map, 'uint'); % 4 bytes

            num_out_kerns = size(cnn.layers{layers}.weights{1},4);

            % write the number of kernels for each output map
            fwrite(cnn_binary_file, num_out_kerns, 'uint'); % 4 bytes

            % Write output map bias terms
            for k2=1:num_out_kerns
                fwrite(cnn_binary_file, cnn.layers{layers}.weights{2}(k2), 'float32'); % 4 bytes
            end

            for k=1:num_in_map
                for k2=1:num_out_kerns
                    % Write out the kernel
                    W = squeeze(cnn.layers{layers}.weights{1}(:,:,k,k2));
                    writeMatrixBin(cnn_binary_file, W, 5);
                end
            end
        elseif(strcmp(cnn.layers{layers}.type, 'fc'))

            % This is the fully connected layer
            fwrite(cnn_binary_file, 2, 'uint'); % 4 bytes

            % the bias term
            writeMatrixBin(cnn_binary_file, cnn.layers{layers}.weights{2}, 5);
            % the weights
            writeMatrixBin(cnn_binary_file, cnn.layers{layers}.weights{1}, 5);

        elseif(strcmp(cnn.layers{layers}.type, 'max_pooling'))
            fwrite(cnn_binary_file, 1, 'uint'); % 4 bytes, indicate max pooling layer
            % params kernel and stride size
            fwrite(cnn_binary_file, cnn.layers{layers}.kernel_size_x, 'uint'); % 4 bytes
            fwrite(cnn_binary_file, cnn.layers{layers}.kernel_size_y, 'uint'); % 4 bytes
            fwrite(cnn_binary_file, cnn.layers{layers}.stride_x, 'uint'); % 4 bytes
            fwrite(cnn_binary_file, cnn.layers{layers}.stride_y, 'uint'); % 4 bytes

        elseif(strcmp(cnn.layers{layers}.type, 'prelu'))
            fwrite(cnn_binary_file, 3, 'uint'); % 4 bytes, indicate a parametric relu layer
            writeMatrixBin(cnn_binary_file, cnn.layers{layers}.weights{1}, 5);
        end
    end

    fclose(cnn_binary_file);

end

author: TadasBaltrusaitis

repo: OpenFace