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

% Last Modified by GUIDE v2.5 17-Jan-2021 11:22:18

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

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

    centerUIFigure(hObject);

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

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

    handles.ksptotMainGUI = varargin{3};

	populateGUI(handles, point);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, point)
    set(handles.pointNameText,'String',point.getName());
    elemSet = point.elemSet;
    setappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet',elemSet);

    handles.refFrameTypeCombo.String = ReferenceFrameEnum.getListBoxStr();
    handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(elemSet.frame.typeEnum.name);
    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', elemSet.frame.getNameStr());

    handles.elementSetCombo.String = ElementSetEnum.getListBoxStr();
    value = ElementSetEnum.getIndForName(elemSet.typeEnum.name);
    handles.elementSetCombo.Value = value;
    elementSetCombo_Callback(handles.elementSetCombo, [], handles);

    handles.utText.String = fullAccNum2Str(elemSet.time);

    elemVector = elemSet.getElementVector();
    handles.orbit1Text.String = fullAccNum2Str(elemVector(1));
    handles.orbit2Text.String = fullAccNum2Str(elemVector(2));
    handles.orbit3Text.String = fullAccNum2Str(elemVector(3));
    handles.orbit4Text.String = fullAccNum2Str(elemVector(4));
    handles.orbit5Text.String = fullAccNum2Str(elemVector(5));
    handles.orbit6Text.String = fullAccNum2Str(elemVector(6));

    handles.pointColorCombo.String = ColorSpecEnum.getListboxStr();
    handles.pointColorCombo.Value = ColorSpecEnum.getIndForName(point.markerColor.name);

    handles.pointMarkerShapeCombo.String = MarkerStyleEnum.getListboxStr();
    handles.pointMarkerShapeCombo.Value = MarkerStyleEnum.getIndForName(point.markerShape.name);

    handles.pointLineColorCombo.String = ColorSpecEnum.getListboxStr();
    handles.pointLineColorCombo.Value = ColorSpecEnum.getIndForName(point.trkLineColor.name);

    handles.pointLineSpecCombo.String = LineSpecEnum.getListboxStr();
    handles.pointLineSpecCombo.Value = LineSpecEnum.getIndForName(point.trkLineSpec.name);

    handles.dispTrajCheckbox.Value = double(point.plotTrkLine);

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

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

        point.setName(handles.pointNameText.String);

        [elemSet, ~] = getCurrentElemSetFromExistingValues(handles);
        point.elemSet = elemSet;

        str = handles.pointColorCombo.String{handles.pointColorCombo.Value};
        point.markerColor = ColorSpecEnum.getEnumForListboxStr(str);

        str = handles.pointMarkerShapeCombo.String{handles.pointMarkerShapeCombo.Value};
        point.markerShape = MarkerStyleEnum.getEnumForListboxStr(str);

        str = handles.pointLineColorCombo.String{handles.pointLineColorCombo.Value};
        point.trkLineColor = ColorSpecEnum.getEnumForListboxStr(str);

        str = handles.pointLineSpecCombo.String{handles.pointLineSpecCombo.Value};
        point.trkLineSpec = LineSpecEnum.getEnumForListboxStr(str);

         point.plotTrkLine = logical(handles.dispTrajCheckbox.Value);

        maStateLog = lvdData.stateLog.getMAFormattedStateLogMatrix(false);

        stateLogMinTime = min(maStateLog(:,1));
        if(stateLogMinTime > 0)
            minTime = 0;
        else
            minTime = stateLogMinTime;
        end

        simMaxDur = lvdData.settings.simMaxDur;
        stateLogMaxTime = max(maStateLog(:,1));
        if(stateLogMinTime + simMaxDur > stateLogMaxTime)
            maxTime = stateLogMinTime + simMaxDur;
        else
            maxTime = stateLogMaxTime;
        end

        hHelpDlg = helpdlg('The two body point is (re-)generating its internal state cache.  Please wait.','Creating Cache');
        point.refeshTrajCache(minTime, maxTime);
        if(isvalid(hHelpDlg))
            close(hHelpDlg);
        end

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

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

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

function errMsg = validateInputs(handles)
    errMsg = {};

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

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

function pointNameText_Callback(hObject, eventdata, handles)
% hObject    handle to pointNameText (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 pointNameText as text
%        str2double(get(hObject,'String')) returns contents of pointNameText as a double

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    updateValuesInState(handles);

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

    updateValuesInState(handles);

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

    updateValuesInState(handles);

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

    updateValuesInState(handles);

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

    updateValuesInState(handles);

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

    updateValuesInState(handles);

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

    updateValuesInState(handles);

% --- Executes during object creation, after setting all properties.
function orbit6Text_CreateFcn(hObject, eventdata, handles)
% hObject    handle to orbit6Text (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 updateStateDueToFrameChange(handles, newFrame)
    lvdData = getappdata(handles.lvd_EditTwoBodyPointGUI,'lvdData');
    celBodyData = lvdData.celBodyData;

    curElemSet = getappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet');

    contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    refFrameEnum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);

    if(not(isempty(newFrame)) && newFrame.typeEnum ~= refFrameEnum)
        refFrameEnum = newFrame.typeEnum;
        handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(refFrameEnum.name);
    end

    switch refFrameEnum
        case ReferenceFrameEnum.BodyCenteredInertial
            if(isempty(newFrame))
                bodyInfo = getSelectedBodyInfo(handles);
            else
                bodyInfo = newFrame.getOriginBody();
            end

            newFrame = bodyInfo.getBodyCenteredInertialFrame();

        case ReferenceFrameEnum.BodyFixedRotating
            if(isempty(newFrame))
                bodyInfo = getSelectedBodyInfo(handles);
            else
                bodyInfo = newFrame.getOriginBody();
            end

            newFrame = bodyInfo.getBodyFixedFrame();

        case ReferenceFrameEnum.TwoBodyRotating
            if(isempty(newFrame))
                bodyInfo = getSelectedBodyInfo(handles);
                if(not(isempty(bodyInfo.childrenBodyInfo)))
                    primaryBody = bodyInfo;
                    secondaryBody = bodyInfo.childrenBodyInfo(1);
                else
                    primaryBody = bodyInfo.getParBodyInfo();
                    secondaryBody = bodyInfo;
                end

                originPt = TwoBodyRotatingFrameOriginEnum.Primary;

                newFrame = TwoBodyRotatingFrame(primaryBody, secondaryBody, originPt, celBodyData);
            else
                newFrame = TwoBodyRotatingFrame(newFrame.primaryBodyInfo, newFrame.secondaryBodyInfo, newFrame.originPt, celBodyData);
            end

        case ReferenceFrameEnum.UserDefined
            if(isempty(newFrame))
                numFrames = lvdData.geometry.refFrames.getNumRefFrames();
                if(numFrames >= 1)
                    geometricFrame = AbstractGeometricRefFrame.empty(1,0);
                    for(i=1:numFrames)
                        frame = lvdData.geometry.refFrames.getRefFrameAtInd(i);
                        if(frame.isVehDependent() == false)
                            geometricFrame = frame;
                            break;
                        end
                    end

                    if(not(isempty(geometricFrame)))
                        newFrame = UserDefinedGeometricFrame(geometricFrame, lvdData);
                    else
                        bodyInfo = getSelectedBodyInfo(handles);
                        newFrame = bodyInfo.getBodyCenteredInertialFrame();

                        warndlg('There are no geometric frames available which are not dependent on vehicle properties.  A body-centered inertial frame will be selected instead.');
                    end
                else
                    bodyInfo = getSelectedBodyInfo(handles);
                    newFrame = bodyInfo.getBodyCenteredInertialFrame();

                    warndlg('There are no geometric frames available which are not dependent on vehicle properties.  A body-centered inertial frame will be selected instead.');
                end

            else
                newFrame = UserDefinedGeometricFrame(newFrame.geometricFrame, lvdData);
            end

        otherwise
            error('Unknown reference frame type: %s', string(refFrameEnum));
    end

    if(not(isempty(newFrame)) && newFrame.typeEnum ~= refFrameEnum)
        refFrameEnum = newFrame.typeEnum;
        handles.refFrameTypeCombo.Value = ReferenceFrameEnum.getIndForName(refFrameEnum.name);
    end

    try
        newElemSet = curElemSet.convertToFrame(newFrame);

        elemVect = newElemSet.getElementVector();

        if(any(isnan(elemVect)) || any(not(isfinite(elemVect))))
            error('State conversion resulted in NaN');
        end

        handles.orbit1Text.String = fullAccNum2Str(elemVect(1));
        handles.orbit2Text.String = fullAccNum2Str(elemVect(2));
        handles.orbit3Text.String = fullAccNum2Str(elemVect(3));
        handles.orbit4Text.String = fullAccNum2Str(elemVect(4));
        handles.orbit5Text.String = fullAccNum2Str(elemVect(5));
        handles.orbit6Text.String = fullAccNum2Str(elemVect(6));

        setappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet', newElemSet);
    catch ME
        updateValuesInState(handles);
        msgbox('Error converting state to new frame.','Conversion Error','error');
    end

    handles.setFrameOptionsButton.TooltipString = sprintf('Current Frame: %s', newFrame.getNameStr());

function updateValuesInState(handles)
    curElemSet = getappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet');
    newElemSet = curElemSet;

    time = str2double(handles.utText.String);
    orbit1Elem = str2double(handles.orbit1Text.String);
    orbit2Elem = str2double(handles.orbit2Text.String);
    orbit3Elem = str2double(handles.orbit3Text.String);
    orbit4Elem = str2double(handles.orbit4Text.String);
    orbit5Elem = str2double(handles.orbit5Text.String);
    orbit6Elem = str2double(handles.orbit6Text.String);

    frame = newElemSet.frame;
	switch newElemSet.typeEnum
        case ElementSetEnum.CartesianElements
            newElemSet = CartesianElementSet(time, [orbit1Elem; orbit2Elem; orbit3Elem], [orbit4Elem; orbit5Elem; orbit6Elem], frame);

        case ElementSetEnum.KeplerianElements
            newElemSet = KeplerianElementSet(time, orbit1Elem, orbit2Elem, deg2rad(orbit3Elem), deg2rad(orbit4Elem), deg2rad(orbit5Elem), deg2rad(orbit6Elem), frame);

        case ElementSetEnum.GeographicElements
            newElemSet = GeographicElementSet(time, deg2rad(orbit1Elem), deg2rad(orbit2Elem), orbit3Elem, deg2rad(orbit4Elem), deg2rad(orbit5Elem), orbit6Elem, frame);

        case ElementSetEnum.UniversalElements
            newElemSet = UniversalElementSet(time, orbit1Elem, orbit2Elem, deg2rad(orbit3Elem), deg2rad(orbit4Elem), deg2rad(orbit5Elem), orbit6Elem, frame);

        otherwise
            error('Unknown element set type: %s', string(elemSetEnum));
	end

    setappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet', newElemSet);

function bodyInfo = getSelectedBodyInfo(handles)
    curElemSet = getappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet');
    bodyInfo = curElemSet.frame.getOriginBody();

function [orbitModel, elemSetEnum] = getCurrentElemSetFromExistingValues(handles)
        contents = cellstr(get(handles.elementSetCombo,'String'));
        selElemSet = contents{get(handles.elementSetCombo,'Value')};
        elemSetEnum = ElementSetEnum.getEnumForListboxStr(selElemSet);

        time = str2double(handles.utText.String);

        orbit1Elem = str2double(handles.orbit1Text.String);
        orbit2Elem = str2double(handles.orbit2Text.String);
        orbit3Elem = str2double(handles.orbit3Text.String);
        orbit4Elem = str2double(handles.orbit4Text.String);
        orbit5Elem = str2double(handles.orbit5Text.String);
        orbit6Elem = str2double(handles.orbit6Text.String);

        curElemSet = getappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet');
        frame = curElemSet.frame;

        switch elemSetEnum
            case ElementSetEnum.CartesianElements
                orbitModel = CartesianElementSet(time, [orbit1Elem; orbit2Elem; orbit3Elem], [orbit4Elem; orbit5Elem; orbit6Elem], frame);

            case ElementSetEnum.KeplerianElements
                orbitModel = KeplerianElementSet(time, orbit1Elem, orbit2Elem, deg2rad(orbit3Elem), deg2rad(orbit4Elem), deg2rad(orbit5Elem), deg2rad(orbit6Elem), frame);

            case ElementSetEnum.GeographicElements
                orbitModel = GeographicElementSet(time, deg2rad(orbit1Elem), deg2rad(orbit2Elem), orbit3Elem, deg2rad(orbit4Elem), deg2rad(orbit5Elem), orbit6Elem, frame);

            case ElementSetEnum.UniversalElements
                orbitModel = UniversalElementSet(time, orbit1Elem, orbit2Elem, deg2rad(orbit3Elem), deg2rad(orbit4Elem), deg2rad(orbit5Elem), orbit6Elem, frame);

            otherwise
                error('Unknown element set type: %s', class(elemSetEnum));
        end

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

% Hints: contents = cellstr(get(hObject,'String')) returns elementSetCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from elementSetCombo
    contents = cellstr(get(hObject,'String'));
    sel = contents{get(hObject,'Value')};
    [~, elemSetEnum] = ElementSetEnum.getIndForName(sel);

    elemNames = elemSetEnum.elemNames;
    unitNames = elemSetEnum.unitNames;

    handles.orbit1Label.String = elemNames{1};
    handles.orbit2Label.String = elemNames{2};
    handles.orbit3Label.String = elemNames{3};
    handles.orbit4Label.String = elemNames{4};
    handles.orbit5Label.String = elemNames{5};
    handles.orbit6Label.String = elemNames{6};

    handles.orbit1UnitLabel.String = unitNames{1};
    handles.orbit2UnitLabel.String = unitNames{2};
    handles.orbit3UnitLabel.String = unitNames{3};
    handles.orbit4UnitLabel.String = unitNames{4};
    handles.orbit5UnitLabel.String = unitNames{5};
    handles.orbit6UnitLabel.String = unitNames{6};

    curElemSet = getappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet');

    try
        switch elemSetEnum
            case ElementSetEnum.CartesianElements
                newElemSet = curElemSet.convertToCartesianElementSet();

            case ElementSetEnum.KeplerianElements
                newElemSet = curElemSet.convertToKeplerianElementSet();

            case ElementSetEnum.GeographicElements
                newElemSet = curElemSet.convertToGeographicElementSet();

            case ElementSetEnum.UniversalElements
                newElemSet = curElemSet.convertToUniversalElementSet();

            otherwise
                error('Unknown element set type: %s', class(elemSetEnum));
        end

        elemVect = newElemSet.getElementVector();

        if(any(isnan(elemVect)) || any(not(isfinite(elemVect))))
            error('State conversion resulted in NaN or Inf');
        end

        handles.orbit1Text.String = fullAccNum2Str(elemVect(1));
        handles.orbit2Text.String = fullAccNum2Str(elemVect(2));
        handles.orbit3Text.String = fullAccNum2Str(elemVect(3));
        handles.orbit4Text.String = fullAccNum2Str(elemVect(4));
        handles.orbit5Text.String = fullAccNum2Str(elemVect(5));
        handles.orbit6Text.String = fullAccNum2Str(elemVect(6));

        setappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet', newElemSet);

    catch ME
        updateValuesInState(handles);
        msgbox('Error converting state to new element set.','Conversion Error','error');
    end

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

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

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

% Hints: contents = cellstr(get(hObject,'String')) returns refFrameTypeCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from refFrameTypeCombo
    updateStateDueToFrameChange(handles, AbstractReferenceFrame.empty(1,0));

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

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

% --- Executes on button press in setFrameOptionsButton.
function setFrameOptionsButton_Callback(hObject, eventdata, handles)
% hObject    handle to setFrameOptionsButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    curElemSet = getappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet');
    frame = curElemSet.frame;
    newFrame = frame.editFrameDialogUI(EditReferenceFrameContextEnum.ForState);

    updateStateDueToFrameChange(handles, newFrame);

% --------------------------------------------------------------------
function getOrbitFromSFSFileContextMenu_Callback(hObject, eventdata, handles)
% hObject    handle to getOrbitFromSFSFileContextMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
	contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    enum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);
    if(not(enum == ReferenceFrameEnum.BodyCenteredInertial))
        enum = ReferenceFrameEnum.BodyCenteredInertial;
        ind = ReferenceFrameEnum.getIndForName(enum.name);
        handles.refFrameTypeCombo.Value = ind;
        refFrameTypeCombo_Callback(handles.refFrameTypeCombo, [], handles);
    end

    contents = cellstr(get(handles.elementSetCombo,'String'));
    selOrbitType = contents{get(handles.elementSetCombo,'Value')};
    [~,enum] = ElementSetEnum.getIndForName(selOrbitType);
    if(not(enum == ElementSetEnum.KeplerianElements))
        enum = ElementSetEnum.KeplerianElements;
        ind = ElementSetEnum.getIndForName(enum.name);
        handles.elementSetCombo.Value = ind;
        elementSetCombo_Callback(handles.elementSetCombo, [], handles);
    end

    refBodyID = orbitPanelGetOrbitFromSFSContextCallBack(handles.ksptotMainGUI, handles.orbit1Text, handles.orbit2Text, handles.orbit3Text, handles.orbit4Text, handles.orbit5Text, handles.orbit6Text, handles.utText);
    tru = computeTrueAnomFromMean(deg2rad(str2double(get(handles.orbit6Text,'String'))), str2double(get(handles.orbit2Text,'String')));
    set(handles.orbit6Text,'String',fullAccNum2Str(rad2deg(tru)));

    if(~isempty(refBodyID) && isnumeric(refBodyID))
        lvdData = getappdata(handles.lvd_EditTwoBodyPointGUI,'lvdData');
        celBodyData = lvdData.celBodyData;
        bodyInfo = getBodyInfoByNumber(refBodyID, celBodyData);

        curElemSet = getCurrentElemSetFromExistingValues(handles);
        setappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet',curElemSet);

        curElemSet.frame.setOriginBody(bodyInfo);
        updateStateDueToFrameChange(handles, AbstractReferenceFrame.empty(1,0));
    end

% --------------------------------------------------------------------
function getOrbitFromKSPTOTConnectContextMenu_Callback(hObject, eventdata, handles)
% hObject    handle to getOrbitFromKSPTOTConnectContextMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
	contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    enum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);
    if(not(enum == ReferenceFrameEnum.BodyCenteredInertial))
        enum = ReferenceFrameEnum.BodyCenteredInertial;
        ind = ReferenceFrameEnum.getIndForName(enum.name);
        handles.refFrameTypeCombo.Value = ind;
        refFrameTypeCombo_Callback(handles.refFrameTypeCombo, [], handles);
    end

    contents = cellstr(get(handles.elementSetCombo,'String'));
    selOrbitType = contents{get(handles.elementSetCombo,'Value')};
    [~,enum] = ElementSetEnum.getIndForName(selOrbitType);
    if(not(enum == ElementSetEnum.KeplerianElements))
        enum = ElementSetEnum.KeplerianElements;
        ind = ElementSetEnum.getIndForName(enum.name);
        handles.elementSetCombo.Value = ind;
        elementSetCombo_Callback(handles.elementSetCombo, [], handles);
    end

    refBodyID = orbitPanelGetOrbitFromKSPTOTConnectCallBack(handles.orbit1Text, handles.orbit2Text, handles.orbit3Text, handles.orbit4Text, handles.orbit5Text, handles.orbit6Text, handles.utText);
    tru = computeTrueAnomFromMean(deg2rad(str2double(get(handles.orbit6Text,'String'))), str2double(get(handles.orbit2Text,'String')));
    set(handles.orbit6Text,'String',fullAccNum2Str(rad2deg(tru)));

    if(~isempty(refBodyID) && isnumeric(refBodyID))
        lvdData = getappdata(handles.lvd_EditTwoBodyPointGUI,'lvdData');
        celBodyData = lvdData.celBodyData;
        bodyInfo = getBodyInfoByNumber(refBodyID, celBodyData);

        curElemSet = getCurrentElemSetFromExistingValues(handles);
        setappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet',curElemSet);

        curElemSet.frame.setOriginBody(bodyInfo);
        updateStateDueToFrameChange(handles, AbstractReferenceFrame.empty(1,0));
    end

% --------------------------------------------------------------------
function getOrbitFromKSPActiveVesselMenu_Callback(hObject, eventdata, handles)
% hObject    handle to getOrbitFromKSPActiveVesselMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
	contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    enum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);
    if(not(enum == ReferenceFrameEnum.BodyCenteredInertial))
        enum = ReferenceFrameEnum.BodyCenteredInertial;
        ind = ReferenceFrameEnum.getIndForName(enum.name);
        handles.refFrameTypeCombo.Value = ind;
        refFrameTypeCombo_Callback(handles.refFrameTypeCombo, [], handles);
    end

    contents = cellstr(get(handles.elementSetCombo,'String'));
    selOrbitType = contents{get(handles.elementSetCombo,'Value')};
    [~,enum] = ElementSetEnum.getIndForName(selOrbitType);
    if(not(enum == ElementSetEnum.KeplerianElements))
        enum = ElementSetEnum.KeplerianElements;
        ind = ElementSetEnum.getIndForName(enum.name);
        handles.elementSetCombo.Value = ind;
        elementSetCombo_Callback(handles.elementSetCombo, [], handles);
    end

    refBodyID = orbitPanelGetOrbitFromKSPTOTConnectActiveVesselCallBack(handles.orbit1Text, handles.orbit2Text, handles.orbit3Text, handles.orbit4Text, handles.orbit5Text, handles.orbit6Text, handles.utText);
    tru = computeTrueAnomFromMean(deg2rad(str2double(get(handles.orbit6Text,'String'))), str2double(get(handles.orbit2Text,'String')));
    set(handles.orbit6Text,'String',fullAccNum2Str(rad2deg(tru)));

    if(~isempty(refBodyID) && isnumeric(refBodyID))
        lvdData = getappdata(handles.lvd_EditTwoBodyPointGUI,'lvdData');
        celBodyData = lvdData.celBodyData;
        bodyInfo = getBodyInfoByNumber(refBodyID, celBodyData);

        curElemSet = getCurrentElemSetFromExistingValues(handles);
        setappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet',curElemSet);

        curElemSet.frame.setOriginBody(bodyInfo);
        updateStateDueToFrameChange(handles, AbstractReferenceFrame.empty(1,0));
    end

% --------------------------------------------------------------------
function copyOrbitToClipboardMenu_Callback(hObject, eventdata, handles)
% hObject    handle to copyOrbitToClipboardMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    bodyInfo = getSelectedBodyInfo(handles);

    o1V = handles.orbit1Text.String;
    o2V = handles.orbit2Text.String;
    o3V = handles.orbit3Text.String;
    o4V = handles.orbit4Text.String;
    o5V = handles.orbit5Text.String;
    o6V = handles.orbit6Text.String;

	contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    enum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);
    framEnumOrig = enum;
    if(not(enum == ReferenceFrameEnum.BodyCenteredInertial))
        enum = ReferenceFrameEnum.BodyCenteredInertial;
        ind = ReferenceFrameEnum.getIndForName(enum.name);
        handles.refFrameTypeCombo.Value = ind;
        refFrameTypeCombo_Callback(handles.refFrameTypeCombo, [], handles);
    end

    contents = cellstr(get(handles.elementSetCombo,'String'));
    selOrbitType = contents{get(handles.elementSetCombo,'Value')};
    [~,enum] = ElementSetEnum.getIndForName(selOrbitType);
    elemSetEnumOrig = enum;
    if(not(enum == ElementSetEnum.KeplerianElements))
        enum = ElementSetEnum.KeplerianElements;
        ind = ElementSetEnum.getIndForName(enum.name);
        handles.elementSetCombo.Value = ind;
        elementSetCombo_Callback(handles.elementSetCombo, [], handles);
    end

    copyOrbitToClipboardFromText(handles.utText, handles.orbit1Text, handles.orbit2Text, ...
                                 handles.orbit3Text, handles.orbit4Text, handles.orbit5Text, ...
                                 handles.orbit6Text, true, bodyInfo.id);

    ind = ElementSetEnum.getIndForName(elemSetEnumOrig.name);
    handles.elementSetCombo.Value = ind;
    elementSetCombo_Callback(handles.elementSetCombo, [], handles);

    ind = ReferenceFrameEnum.getIndForName(framEnumOrig.name);
    handles.refFrameTypeCombo.Value = ind;
    refFrameTypeCombo_Callback(handles.refFrameTypeCombo, [], handles);

    handles.orbit1Text.String = o1V;
    handles.orbit2Text.String = o2V;
    handles.orbit3Text.String = o3V;
    handles.orbit4Text.String = o4V;
    handles.orbit5Text.String = o5V;
    handles.orbit6Text.String = o6V;

% --------------------------------------------------------------------
function pasteOrbitFromClipboardMenu_Callback(hObject, eventdata, handles)
% hObject    handle to pasteOrbitFromClipboardMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
	contents = cellstr(get(handles.refFrameTypeCombo,'String'));
    selFrameType = contents{get(handles.refFrameTypeCombo,'Value')};
    enum = ReferenceFrameEnum.getEnumForListboxStr(selFrameType);
    if(not(enum == ReferenceFrameEnum.BodyCenteredInertial))
        enum = ReferenceFrameEnum.BodyCenteredInertial;
        ind = ReferenceFrameEnum.getIndForName(enum.name);
        handles.refFrameTypeCombo.Value = ind;
        refFrameTypeCombo_Callback(handles.refFrameTypeCombo, [], handles);
    end

    contents = cellstr(get(handles.elementSetCombo,'String'));
    selOrbitType = contents{get(handles.elementSetCombo,'Value')};
    [~,enum] = ElementSetEnum.getIndForName(selOrbitType);
    if(not(enum == ElementSetEnum.KeplerianElements))
        enum = ElementSetEnum.KeplerianElements;
        ind = ElementSetEnum.getIndForName(enum.name);
        handles.elementSetCombo.Value = ind;
        elementSetCombo_Callback(handles.elementSetCombo, [], handles);
    end

	lvdData = getappdata(handles.lvd_EditTwoBodyPointGUI,'lvdData');
    celBodyData = lvdData.celBodyData;

    bodyInfo = pasteOrbitFromClipboard(handles.utText, handles.orbit1Text, handles.orbit2Text, ...
                                       handles.orbit3Text, handles.orbit4Text, handles.orbit5Text, ...
                                       handles.orbit6Text, true, [], celBodyData);

	if(not(isempty(bodyInfo)))
        curElemSet = getappdata(handles.lvd_EditTwoBodyPointGUI,'curElemSet');
        curElemSet.frame.setOriginBody(bodyInfo);
        updateStateDueToFrameChange(handles, AbstractReferenceFrame.empty(1,0));
	end

% --------------------------------------------------------------------
function enterUTAsDateTimeContextMenu_Callback(hObject, eventdata, handles)
% hObject    handle to enterUTAsDateTimeContextMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    secUT = enterUTAsDateTimeGUI(str2double(get(gco, 'String')));
    if(secUT >= 0)
        set(gco, 'String', fullAccNum2Str(secUT));
        utText_Callback(handles.utText, eventdata, handles);
    end

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

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

% --- Executes on button press in dispTrajCheckbox.
function dispTrajCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to dispTrajCheckbox (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 dispTrajCheckbox


text:
function g = cos( f )
%COS   Cosine of a BALLFUN.
%   COS(F) computes the cosine of F.
%
% See also COSH, COS.

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

g = compose( f, @cos );

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function [gm, gc, pm, pc] = termmarg(dB,degrees,w)
%
% Utility Function: TERMMARG
%
% The purpose of this function is to compute the gain and phase margins
% from the frequency response data

% Author: Craig Borghesani
% Date: 9/19/94
% Revised: 10/27/94
% Copyright (c) 1999, Prentice-Hall

%
% DETERMINING GAIN MARGIN
%
% find where the phase is less than -180 degrees.  this is done by adding
% +180 degrees and looking for where the sign changes from +1 to -1

shift_degrees = degrees + 180;
sign_deg = sign(shift_degrees);
diff_sign = abs([0,diff(sign_deg)]);
cross_180 = find(diff_sign == 2);

% what if phase vector begins at -180 (or very close to)
if shift_degrees(1) < 1 & shift_degrees(1) > -1,
 cross_180 = [2,cross_180];
end

% determine frequencies that saddle the -180 degree point
if length(cross_180),
 loc1 = cross_180 - 1;
 loc2 = cross_180;

% eliminate ghost crossings
 loc1(abs(shift_degrees(loc1)) > 20) = [];
 loc2(abs(shift_degrees(loc2)) > 20) = [];

 if length(loc1),
  degrees1 = degrees(loc1);
  degrees2 = degrees(loc2);
  w1 = w(loc1);
  w2 = w(loc2);

  dB1      = dB(loc1);
  dB2      = dB(loc2);

% compute slope of line between the two points
  deg_slope = (degrees2 - degrees1)./(log10(w2) - log10(w1));
  mag_slope = (dB2 - dB1)./(log10(w2) - log10(w1));

% compute y-intercept
  deg_int = degrees1 - deg_slope.*log10(w1);
  mag_int = dB1 - mag_slope.*log10(w1);

% use phase line equation to interpolate crossover frequency at -180 degrees
  gc_vec = 10 .^((-180 - deg_int)./deg_slope);

% use magnitude line equation to interpolate gain margin in dB
  gm_vec = -(mag_slope.*log10(gc_vec) + mag_int);

% return smallest gain margin value in arithmetic
  gm_vec = 10 .^(gm_vec/20);
  [min_gm,loc_min] = min(gm_vec);
  gm = min_gm;
  gc = gc_vec(loc_min);

 else

  gc = NaN;
  gm = inf;

 end
else

 gc = NaN;
 gm = inf;

end

%
% DETERMINING PHASE MARGIN
%
% find where the magnitude is greater than 0 dB.  this is done by seeing
% where the sign changes from +1 to -1
sign_dB = sign(dB);
diff_sign = abs([0,diff(sign_dB)]);
cross_0 = find(diff_sign==2);

% determine frequencies that saddle the 0 dB point
if length(cross_0),

 loc1 = cross_0 - 1;
 loc2 = cross_0;

 w1 = w(loc1);
 w2 = w(loc2);

 dB1      = dB(loc1);
 dB2      = dB(loc2);
 degrees1 = degrees(loc1);
 degrees2 = degrees(loc2);

% compute slope of line between the two points
 mag_slope = (dB2 - dB1)./(log10(w2) - log10(w1));
 deg_slope = (degrees2 - degrees1)./(log10(w2) - log10(w1));

% compute y-intercept
 mag_int = dB1 - mag_slope.*log10(w1);
 deg_int = degrees1 - deg_slope.*log10(w1);

% use magnitude line equation to interpolate crossover frequency at 0 dB
 pc_vec = 10 .^((0 - mag_int)./mag_slope);

% use phase line equation to interpolate phase margin
 pm_vec = 180 + (deg_slope.*log10(pc_vec) + deg_int);

% determine smallest phase margin
 [min_pm,loc_min] = min(pm_vec);
 pm = min_pm;
 pc = pc_vec(loc_min);

else

 pc = NaN;
 pm = inf;

end

author: Sable

repo: mcbench-benchmarks


text:
function uv = compute_flow_base(this, uv)
%%
%COMPUTE_FLOW_BASE   Base function for computing flow field
%   UV = COMPUTE_FLOW_BASE(THIS, INIT) computes the flow field UV with
%   algorithm THIS and the initialization INIT.
%
%   This is a member function of the class 'classic_nl_optical_flow'.
%
% Authors: Deqing Sun, Department of Computer Science, Brown University
% Contact: dqsun@cs.brown.edu
% $Date: $
% $Revision: $
%
% Copyright 2007-2010, Brown University, Providence, RI. USA
%
%                          All Rights Reserved
%
% All commercial use of this software, whether direct or indirect, is
% strictly prohibited including, without limitation, incorporation into in
% a commercial product, use in a commercial service, or production of other
% artifacts for commercial purposes.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for research purposes is hereby granted without fee,
% provided that the above copyright notice appears in all copies and that
% both that copyright notice and this permission notice appear in
% supporting documentation, and that the name of the author and Brown
% University not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior permission.
%
% For commercial uses contact the Technology Venture Office of Brown University
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO
% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR
% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
% THIS SOFTWARE.

  % Construct quadratic formulation
  qua_this          = this;
  qua_this.lambda   = this.lambda_q;

  % Spatial
  if isa(this.rho_spatial_u{1}, 'robust_function')
      for i = 1:length(this.rho_spatial_u)
          a = this.rho_spatial_u{i}.param;
          qua_this.rho_spatial_u{i}   = robust_function('quadratic', a(1));
          a = this.rho_spatial_u{i}.param;
          qua_this.rho_spatial_v{i}   = robust_function('quadratic', a(1));
      end;
  elseif isa(this.rho_spatial_u{1}, 'gsm_density')
      for i = 1:length(this.rho_spatial_u)
          qua_this.rho_spatial_u{i}   = robust_function('quadratic', sqrt(1/this.rho_spatial_u{i}.precision));
          qua_this.rho_spatial_v{i}   = robust_function('quadratic', sqrt(1/this.rho_spatial_v{i}.precision));
      end;
  else
      error('evaluate_log_posterior: unknown rho function!');
  end;

  % Data
  if isa(qua_this.rho_data, 'robust_function')
      a = this.rho_data.param;
      qua_this.rho_data        = robust_function('quadratic', a(1));
  elseif isa(qua_this.rho_data, 'gsm_density')
      qua_this.rho_data        = robust_function('quadratic', sqrt(1/this.rho_data.precision));
  else
      error('evaluate_log_posterior: unknown rho function!');
  end;

  % Iterate flow computation
  for i = 1:this.max_iters

    duv = zeros(size(uv));

    % Compute spatial and temporal partial derivatives
    [It Ix Iy] = partial_deriv(this.images, uv, this.interpolation_method, this.deriv_filter);

    for j = 1:this.max_linear

        % Every linearization step updates the nonlinearity using the
        % previous flow increments

        % Compute linear flow operator
        if this.alpha == 1
            [A, b, parm, iterative] = ...
                flow_operator(qua_this, uv, duv, It, Ix, Iy);

        elseif this.alpha > 0
            [A, b] = ...
                flow_operator(qua_this, uv, duv, It, Ix, Iy);
            [A1, b1, parm, iterative] = ...
                flow_operator(this, uv, duv, It, Ix, Iy);
            A = this.alpha * A + (1-this.alpha) * A1;
            b = this.alpha * b + (1-this.alpha) * b1;

        elseif this.alpha == 0
            [A, b, parm, iterative] = ...
                flow_operator(this, uv, duv, It, Ix, Iy);

        else
            error('flow_operator@classic_nl_optical_flow: wrong gnc parameter alpha %3.2e', this.alpha);
        end;

        % Invoke the selected linear equation solver
        switch (lower(this.solver))
            case 'backslash'
                x = reshape(A \ b, size(uv));
            case 'sor'
                % Use complied mex file (may need to compile utils/mex/sor.pp)
                [x, flag, res, n] = sor(A', b, 1.9, this.sor_max_iters, 1E-2, uv(:));
                x = reshape(x, size(uv));
                fprintf('%d %d %d  ', flag, res, n);

            case 'bicgstab'
                [x,flag] = reshape(bicgstab(A, b, 1E-3, 200, [], [], uv(:)), size(uv)); %, parm
            case 'pcg'
                [x flag] = pcg(A,b, [], 10);
                x        = reshape(x, size(uv));
            otherwise
                error('Invalid solver!')
        end

        % If limiting the incremental flow to [-1, 1] is requested, do so
        if (this.limit_update)
            x(x > 1)  = 1;
            x(x < -1) = -1;
        end

        % Print status information (change betwen flow increment = flow
        %   increment at first linearization step)
        if this.display
            disp(['--Iteration: ', num2str(i), '   ', num2str(j), '   (norm of flow increment   ', ...
                num2str(norm(x(:)-duv(:))), ')'])
        end;

        % Terminate iteration early if flow doesn't change substantially
%         if norm(x(:)-duv(:)) < 1E-3
%             break;
%         end

        duv = x;

        uv0 = uv;
        uv  = uv+duv;

        if ~isempty(this.median_filter_size)

            %Compute weighted median solved by Li & Osher formula
            occ = detect_occlusion(uv, this.images);
            uv = denoise_color_weighted_medfilt2(uv, this.color_images, occ, this.area_hsz, this.median_filter_size, this.sigma_i, this.fullVersion);

        end;

        duv = uv - uv0;
        uv  = uv0;

    end;

    % Update flow fileds
    uv = uv + duv;

  end

author: kristinbranson

repo: JAABA


text:
function [inflMap, colXCoord, rowYCoord, colDividerXCoord, rowDividerYCoord, rowLeafPositions] = getLSInfluenceMapFactorEx(LS,leak,beamIndex)
%"getLSInfluenceMap"
%   Gets an image of the influence generated by the beam described in LS.
%   Use getDICOMLeafPositions to generate LS.
%
%JRA&KZ 02/8/05
%
%Usage:
%   function inflMap = getLSInfluenceMap(LS);
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Maximum precision of leaf position, in mm.
precision = .1;

%Get x max, min and round to precision value.
% xMax = ceil(max(vertcat(LS.xLimits{1}),[],1) / precision) * precision;
% xMin = floor(min(vertcat(LS.xLimits{1}),[],1) / precision) * precision;
% fieldSize.x = max(xMax) - min(xMin);
% fieldLim.x  = [max(xMax) min(xMin)];

%Siemens no X jaws exist
if ~isfield(LS,'xLimits')
    xMax = ceil(max(vertcat(LS.xLeafPositions{:}),[],1) / precision) * precision;
    xMin = floor(min(vertcat(LS.xLeafPositions{:}),[],1) / precision) * precision;
    LS.xLimits{1}(1) = xMin;
    LS.xLimits{1}(2) = xMax;
end

xMax = ceil(max(vertcat(LS.xLimits{:}),[],1) / precision) * precision;
xMin = floor(min(vertcat(LS.xLimits{:}),[],1) / precision) * precision;
fieldSize.x = max(xMax) - min(xMin);
fieldLim.x  = [max(xMax) min(xMin)];

yMax = ceil(max(vertcat(LS.yLimits{:}),[],1) / precision) * precision;
yMin = floor(min(vertcat(LS.yLimits{:}),[],1) / precision) * precision;
fieldSize.y = max(yMax) - min(yMin);
fieldLim.y  = [max(yMax) min(yMin)];

yRes = precision;
nyElements = ceil(fieldSize.y/yRes);
xRes = precision;
nxElements = ceil(fieldSize.x/xRes);

inflMap=zeros(nyElements, nxElements);
colDividerXCoord = linspace(fieldLim.x(2), fieldLim.x(1), nxElements+1);
rowDividerYCoord = linspace(fieldLim.y(2), fieldLim.y(1), nyElements+1);

if isfield(LS, 'yLeafPositions')
    rowLeafPositions = round(interp1(rowDividerYCoord, 1:nyElements+1, LS.yLeafPositions,'linear', 'extrap'));
    rowLeafPositions = clip(rowLeafPositions, 1, nyElements+1, 'limits');
    leafBoundariesToKeep = [diff(rowLeafPositions)>0;logical(1)];
    rowLeafPositions = rowLeafPositions(leafBoundariesToKeep);
    leavesToKeep = leafBoundariesToKeep(1:end-1);
else
    %LS.xLeafPositions{1} = [xMin xMax-precision];
    LS.xLeafPositions{1} = [xMin xMax];
    LS.meterSetWeight = {1};
    rowLeafPositions = [1 nyElements+1];
    leavesToKeep = 1;
end

if length(LS.meterSetWeight) == 1
    doses = LS.meterSetWeight{:};
else
    doses = [0 diff([LS.meterSetWeight{:}])];
end

h = waitbar(0,['Generating Fluence Map For Beam ',num2str(beamIndex)]);

for i=1:length(LS.xLeafPositions)

    nLeaves = length(LS.xLeafPositions{i})/2;

    if length(LS.xLimits) > 1
        jpL = LS.xLimits{i}(1);
        jpR = LS.xLimits{i}(2);
    else
        jpL = LS.xLimits{1}(1);
        jpR = LS.xLimits{1}(2);
    end

    lpL = LS.xLeafPositions{i}(1:nLeaves);
    lpR = LS.xLeafPositions{i}(nLeaves+1:end);
    lpLK = lpL(leavesToKeep);
    lpRK = lpR(leavesToKeep);
    lpLCols = interp1(colDividerXCoord, 1:nxElements+1, lpLK, 'linear', 'extrap');
    lpRCols = interp1(colDividerXCoord, 1:nxElements+1, lpRK, 'linear', 'extrap');

    %Column divider positions of jaws.
    jpLCol = interp1(colDividerXCoord, 1:nxElements+1, jpL, 'linear', 'extrap');
    jpRCol = interp1(colDividerXCoord, 1:nxElements+1, jpR, 'linear', 'extrap');

    lpLCols = clip(lpLCols, jpLCol, jpRCol, 'limits');
    lpRCols = clip(lpRCols, jpLCol, jpRCol, 'limits');

    lpLCols = round(lpLCols);
    lpRCols = round(lpRCols);

    %head scatter radiation parametrs for varian
    a2 = 0.078;
    beta = 1.79;
    lambda = 7.69;

    for j=1:length(lpLCols)
        %HCF from output ratio for MLC fields Zhu, MedPhys
        YMLC = rowDividerYCoord(rowLeafPositions(j)) + abs((rowDividerYCoord(rowLeafPositions(j+1)) - rowDividerYCoord(rowLeafPositions(j))))/2;
        YMLC = YMLC/10;
        sizeLeaf = abs((rowDividerYCoord(rowLeafPositions(j+1)) - rowDividerYCoord(rowLeafPositions(j))));
        sizeLeaf = sizeLeaf/10;
        HCF_UP = 1 + a2*(erf(2*lpLK(j)*beta/(10*lambda)) +  erf(2*lpRK(j)*beta/(10*lambda)))*(erf(2*(YMLC + sizeLeaf/2)/lambda) - erf(2*(YMLC - sizeLeaf/2)/lambda))/4;
        HCF_Down = 1 + a2*(erf(2*jpL/(10*lambda)) +  erf(2*jpR/(10*lambda)))*(erf(2*(YMLC + sizeLeaf/2)/lambda) - erf(2*(YMLC - sizeLeaf/2)/lambda))/4;
        HCF = HCF_UP/HCF_Down;
        inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpLCols(j):lpRCols(j)-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpLCols(j):lpRCols(j)-1) + HCF*doses(i);
        inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, jpLCol:lpLCols(j)-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, jpLCol:lpLCols(j)-1) + leak*doses(i);
        inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpRCols(j):jpRCol-1) = inflMap(rowLeafPositions(j):rowLeafPositions(j+1)-1, lpRCols(j):jpRCol-1) + leak*doses(i);
    end

    waitbar(i/length(LS.xLeafPositions));
end
close(h);
colXCoord = colDividerXCoord(1:end-1) + precision/2;
rowYCoord = rowDividerYCoord(1:end-1) + precision/2;

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function rouderFigure4(nrSets,options)
% Runs the simulations of Rouder et al. 2009 in Figure 4.
% This basically shows the ability to extract Main and Interaction effects
% in a 2-way anova.
if nargin<2
    options = bf.options;
    if nargin <1
        nrSets = 10;
    end
end
rouder2012 = load('rouder2012Data.mat');
effects = [0   0   0
    0.2 0   0
    0.5 0   0
    1   0   0
    0.2 0.4 0
    0.5 0.4 0
    1   0.4 0
    0.2 0.2   0
    0.5 0.5   0
    1   1     0
    0.4 0.4 0.2
    0.4 0.4 0.5];

nrEffects = size(effects,1);
% Create a design matrix from the data, only to simulate fake rt's with
% different effects
X= classreg.regr.modelutils.designmatrix(rouder2012.data,'intercept',false,'responsevar','rt','DummyVarCoding','effects','PredictorVars',{'ori','freq'},'model','interactions');
bfOri = nan(nrSets,nrEffects);
bfFreq= nan(nrSets,nrEffects);
bfInteraction= nan(nrSets,nrEffects);
parfor (j=1:nrEffects,options.nrWorkers)
    rt = X *effects(j,:)';
    for i=1:nrSets
        tmp  =rouder2012.data; %#ok<PFBNS>
        tmp.rt =rt + randn([size(X,1) 1]);
        bfFull = bf.anova(tmp,'rt~ori*freq');
        bfMain = bf.anova(tmp,'rt~ori+freq');
        bfOri(i,j)  = bf.anova(tmp,'rt~ori');
        bfFreq(i,j)  = bf.anova(tmp,'rt~freq');
        bfInteraction(i,j) = bfFull/bfMain;
    end
end

%%
figure(4);clf
effectIx = {1:4,5:7,8:10,11:12};
for i=1:4
    thisPlotEffects  = effectIx{i};
    subplot(1,4,i)
    if i==4
        x = effects(thisPlotEffects,3);
    else
        x = effects(thisPlotEffects,1);
    end
    [meOri]= median(bfOri(:,thisPlotEffects));
    hOri=  plot(x,meOri,'o-','MarkerSize',10,'Color','k','MarkerFaceColor','k');
    hold on
    meFreq = median(bfFreq(:,thisPlotEffects));
    hFreq=  plot(x,meFreq,'o-','MarkerSize',10,'Color','k','MarkerFaceColor',[0.7 0.5 0]);
    meInt = median(bfInteraction(:,thisPlotEffects));

    hInt=  plot(x,meInt,'o-','MarkerSize',10,'Color','k','MarkerFaceColor','w');
    if i==1
        legend([hOri, hFreq,hInt],{'Orientation','Frequency','Interaction'},'Location','NorthWest');
    end
    set(gca,'YScale','Log','YLim',[0.1 1e6],'YTick',[0.1 1 10 100 1000 1e6])
    ylabel 'Median Bayes Factor for Effect'
end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function varargout = std2(varargin)
%STD2   Standard deviation of a DISKFUN.
%   V = STD2(F) computes the standard deviation of a DISKFUN, i.e.,
%
%     STD2(F)^2 = 1/A * sum2(|f(x,y) - m|^2).
%
%   where A is the area of the domain of F.
%
% See also DISKFUN/MEAN, DISKFUN/MEAN2, DISKFUN/STD.

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

[varargout{1:nargout}] = std2@separableApprox(varargin{:});

end


text:
function r = roots( f, g, varargin )
%ROOTS   Zeros of a SEPARABLEAPPROX.
%   R = ROOTS(F) returns the zero contours of F as a quasimatrix of chebfuns.
%   Each column of R is one zero contour.  This command only finds contours when
%   there is a change of sign, and it can also group intersecting contours in a
%   non-optimal way.
%
%   For a faster plot to graphical accuracy use CONTOUR(F, [0 0]).
%
%   R = ROOTS(F, G) returns the isolated mutual roots of F and G.
%
%   R = ROOTS(F, G, METHOD) allows the underlying rootfinding algorithm to
%   be specified.  If METHOD = 'ms' or 'marchingsquares', the Marching
%   Squares algorithm is employed, which is fast but not very robust.
%   If METHOD = 'resultant', a hidden variable resultant method
%   based on Bezout resultants is employed, slower but more robust.
%   See the CHEBFUN2V/ROOTS documentation to see which algorithm is used
%   when no METHOD is passed.
%
% Example:
%   cheb.xy;
%   f = x.^2 + y.^2 - 1/4;
%   roots(x,f)                               % [0 -.5; 0 .5]
%   c = roots(f);
%   arclength = sum(abs(diff(c)))            % pi
%   area = abs(sum(real(c).*diff(imag(c))))  % pi/4
%
% See also CHEBFUN2V/ROOTS.

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

% Check for empty chebfun input:
if ( isempty( f ) )
    r = [];
    return
end

dom = f.domain;
scl = norm(dom,inf);

if ( nargin == 1 )  % Seek zero curves of scalar function

    if ( length( f ) == 1 )  % Special case: f has rank 1:
        cols = f.cols;
        rows = f.rows;
        yrts = 1i*(roots( cols )+realmin);
        xrts = roots( rows ) + realmin*1i; % Add complex to ensure it's not real
        r = chebfun;
        % Go though col(yrts) = 0, make into a horizontal line:
        dom = rows.domain;
        len = (dom(2)-dom(1))/2;
        for j = 1 : numel(yrts)
            f = chebfun(@(x) (len*(x+1)+dom(1)) + yrts(j));
            r = [r f];
        end
        % Go though row(xrts) = 0, make into a vertical line:
        dom = cols.domain;
        len = (dom(2)-dom(1))/2;
        for j = 1 : numel(xrts)
            f = chebfun(@(x) 1i*(len*(x+1)+dom(1)) + xrts(j));
            r = [r f];
        end

    elseif ( isreal( f ) )  % Main case: zero curves for real function
        % We seek accurate chebfun representations of each component
        % of the zero curve.  First we call Matlab's contourc function
        % to get initial data points, which typically will lie on the zero
        % curve to 5-6 digit accuracy and will be smoothly spaced along
        % it to 2-3 digit accuracy.  The choice n = 502 is used to get a
        % grid that does not involve the boundary of the domain.
        n = 502;
        x = linspace( dom(1), dom(2), n );
        x(1) = []; x(end) = [];
        y = linspace( dom(3), dom(4), n );
        y(1) = []; y(end) = [];
        [xx, yy] = meshgrid( x, y );
        vals = feval( f, xx, yy );
        C = contourc( x, y, vals, 0*[1 1] );
        [fx, fy] = grad(f);
        gradf = @(data) feval( fx, real(data), imag(data)) ...
                   + 1i*feval( fy, real(data), imag(data));
        fval = @(data) feval( f, real(data), imag(data));

        % The construction of chebfuns proceeds by improving the accuracy
        % of the curves component by component, using complex arithmetic
        % for convenience.
        j = 1; r = chebfun;
        while ( j < length(C) )
            k = j + C(2, j);
            D = C(:, j+1:k);
            data = ( D(1, :) + 1i*(D(2, :)+realmin) ).';
            ii = find(abs(diff(data)) < 1e-8*scl);
            data(ii) = [];                           % eliminate repetitions
            npts = length(data);
            err = 999; errnew = 1e-2;
            stepno = 0;
            curvenew = chebfun(data);
            while (errnew < err) && (stepno < 6)
                stepno = stepno+1;
                err = errnew;
                curve = curvenew;
                s = [0; cumsum(abs(diff(data)))];    % empirical arclength
                s = 2*s/s(end) - 1;                  % normalize to [-1,1]
                data = interp1(s, data, chebpts ...  % interpolate
                    (length(data)), 'spline');
                curvenew = chebfun(data);            % make chebfun
                data = curvenew(chebpts(npts));      % sample finely
                data = snap(data);                   % snap to boundary
                ff = fval(data);                     % function values
                g = gradf(data);                     % gradient values
                errnew = norm(ff,inf)/vscale(f);     % max rel error
                data = data - ff.*( g./abs(g).^2 );  % Newton step
                curvenew = chebfun(data);            % make chebfun
                curvenew = simplify(curvenew);       % simplify it
            end
            j = k + 1;
            r = [ r , curve ];
        end

    else  % Function is complex-valued: reduce to real case
        r = roots( [ real(f) ; imag(f) ] );
        if ( ~isempty( r ) )
            r = r(:, 1) + 1i*r(:, 2);
        end
    end

elseif ( isa(g, 'separableApprox') )  % seek zero points of vector function
    % TODO: This should not call chebfun2v directly.
    r = roots( chebfun2v( f, g ), varargin{:} );

end

function d = snap(d)   % adjust endpoints to snap to boundary of domain
    n = length(d);

    if abs(real(d(1))-dom(2)) < .02*scl                 % snap to right bndry
        dx0 = dom(2)-real(d(2)); dx = real(d(1)-d(2));
        d(1) = d(2) + (dx0/dx)*(d(1)-d(2));
    end
    if abs(real(d(n))-dom(2)) < .02*scl
        dx0 = dom(2)-real(d(n-1)); dx = real(d(n)-d(n-1));
        d(n) = d(n-1) + (dx0/dx)*(d(n)-d(n-1));
    end

    if abs(real(d(1))-dom(1)) < .02*scl                 % snap to left bndry
        dx0 = dom(1)-real(d(2)); dx = real(d(1)-d(2));
        d(1) = d(2) + (dx0/dx)*(d(1)-d(2));
    end
    if abs(real(d(n))-dom(1)) < .02*scl
        dx0 = dom(1)-real(d(n-1)); dx = real(d(n)-d(n-1));
        d(n) = d(n-1) + (dx0/dx)*(d(n)-d(n-1));
    end

    if abs(imag(d(1))-dom(4)) < .02*scl                 % snap to top bndry
        dy0 = dom(4)-imag(d(2)); dy = imag(d(1)-d(2));
        d(1) = d(2) + (dy0/dy)*(d(1)-d(2));
    end
    if abs(imag(d(n))-dom(4)) < .02*scl
        dy0 = dom(4)-imag(d(n-1)); dy = imag(d(n)-d(n-1));
        d(n) = d(n-1) + (dy0/dy)*(d(n)-d(n-1));
    end

    if abs(imag(d(1))-dom(3)) < .02*scl                 % snap to bottom bndry
        dy0 = dom(3)-imag(d(2)); dy = imag(d(1)-d(2));
        d(1) = d(2) + (dy0/dy)*(d(1)-d(2));
    end
    if abs(imag(d(n))-dom(3)) < .02*scl
        dy0 = dom(3)-imag(d(n-1)); dy = imag(d(n)-d(n-1));
        d(n) = d(n-1) + (dy0/dy)*(d(n)-d(n-1));
    end

end

end


text:
%% COMPILE_MATCONVNET
%
% Compile MatConvNet
%
% Hyeonseob Nam, 2015
%

run matconvnet/matlab/vl_setupnn ;
cd matconvnet;
vl_compilenn('enableGpu', true, ...
               'cudaRoot', '/usr/local/cuda-7.5', ...
               'cudaMethod', 'nvcc');
cd ..;

author: flyers

repo: drone-tracking


text:
function Ip=perm2PermMatrix(p)
%%PERM2PERMMATRIX Given a permutation of the values 1:n, obtain the
%                 permutation matrix that corresponds to the permutation.
%
%INPUTS: p A 1Xn or nX1 permutation of the values 1:n.
%
%OUTPUTS: Ip A permutation matrix such that Ip*(1:n).'=p.
%
%The creation of a permutation matrix from a permutation basically involves
%rearranging the columns of an identity matrix.
%
%EXAMPLE:
% p=[3;1;4;5;2];
% Ip=perm2PermMatrix(p);
% all(Ip*(1:5).'==p)
%
%November 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

n=length(p);
Ip=zeros(n,n);
for i=1:n
    Ip(i,p(i))=1;
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 [xopt,fval,exitflag,output] = spcgsearch(z, xbox, options)
% SPCGSEARCH  Optimizes the sparse grid interpolant using the CG
%    method.
%    X = SPCGSEARCH(Z) Starts search at the best available
%    sparse grid point and attempts to find a local minimizer of the
%    sparse grid interpolant Z. The entire range of the sparse
%    grid interpolant is searched.
%
%    X = SPCGSEARCH(Z,XBOX)  Uses the search box XBOX = [a1,
%    b1; a2, b2; ...]. The size of search box XBOX must be smaller
%    than or equal to the range of the interpolant.
%
%    X = SPCGSEARCH(Z,XBOX,OPTIONS)  Minimizes with the default
%    optimization parameters replaced by values in the structure
%    OPTIONS, created with the SPOPTIMSET function.  See SPOPTIMSET
%    for details.
%
%    [X,FVAL] = SPCGSEARCH(...)  Returns the value of the
%    sparse grid interpolant at X.
%
%    [X,FVAL,EXITFLAG] = SPCGSEARCH(...)  Returns an EXITFLAG
%    that describes the exit condition of SPCGSEARCH. Possible
%    values of EXITFLAG and the corresponding exit conditions are
%
%    1  SPCGSEARCH converged to a solution X.
%    0  Maximum number of function evaluations or iterations
%       reached.
%
%    [X,FVAL,EXITFLAG,OUTPUT] = SPCGSEARCH(...) Returns a
%    structure OUTPUT with the number of function evaluations in
%    OUTPUT.nFEvals, the number of gradients in .nGradEvals,
%    and the computing time in .time.
%
%    Example: (minimizing the three-hump camel-back function)
%      f = inline('12*x.^2-6.3*x.^4+x.^6+6*y*(y-x)');
%      range = [-3 3; -3 3];
%      options = spset('keepFunctionValues','on', ...
%                      'GridType', 'Chebyshev', ...
%                      'DimensionAdaptive', 'on', ...
%                      'DimAdaptDegree', 1, ...
%                      'MinPoints', 10);
%      z = spvals(f, 2, range, options)
%      [xopt, fval] = spcgsearch(z)
%
%    See also SPOPTIMSET.

% Author : Andreas Klimke
% Version: 1.0
% Date   : September 1, 2007

% Change log:
% V1.0   : September 1, 2007
%          Initial version.

% ------------------------------------------------------------
% 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
% ------------------------------------------------------------

t0 = clock;

if nargin < 2, xbox = []; end
if nargin < 3, options = []; end

d = z.d;

% In case that no range has been provided to spvals -> set it to
% [0,1]^d.
range = z.range;
if isempty(range)
	range = [zeros(d,1) ones(d,1)];
end
if isempty(xbox)
	xbox = range;
end

% Break if maximize is set; not yet supported.
maximize = spoptimget(options, 'Maximize', 'off');
minimize = spoptimget(options, 'Minimize', 'on');
if strcmpi(maximize, 'on')
  warning('MATLAB:spinterp:unsupported',['spcgsearch ' ...
	  'does currently not support searching for maxima. ' ...
		'Search for local maximum is skipped.']);
	options = spoptimset(options, 'Maximize', 'off');
  if strcmpi(minimize, 'off')
    xopt = NaN;
	  fval = NaN;
	  exitflag = 0;
	  if nargout == 4
		  output.nFEvals = 0;
		  output.nGradEvals = 0;
		  output.time = etime(clock, t0);
	  end
	  return;
  end
end

% Determine optimization start point
[x, fval] = spgetstartpoint(z, xbox, options);
fprev = fval;

maxiter = spoptimget(options, 'MaxIter', 100);
tolfun  = spoptimget(options, 'TolFun', 1e-6);
dispopt = spoptimget(options, 'Display', 'off');
[isdispiter, iterstr] = initoptidisp(dispopt);

if isfield(z,'selectOutput')
	numout = z.selectOutout;
else
	numout = 1;
end
abstol = (z.fevalRange(numout,2) - z.fevalRange(numout,1)).*100*eps;

% Default tolx is computed from range times floating point accuracy.
tolxvec = eps * (range(:,2) - range(:,1));

% Define step size variable; initial value will be computed by
% spminbracket.
stepsize = [];

% Do a maximum of 50 inner iterations
brentopt = spoptimset('MaxIter',50,'TolFun',tolfun);

[dummy, gf] = spsurfun(x,z);

nfevals = 1; ngradevals = 1;
if isdispiter, disp(sprintf(iterstr, 0, 1, 1, fprev, 'start point')); end
neggf  = -gf;
xi = neggf;
h  = neggf;

exitflag = 0;
for k = 1:maxiter
	% Check if gradient is zero
	gg  = dot(neggf,neggf);
	if gg == 0.0
		exitflag = 1;
		break;
	end
	% Check if new search direction is all-zero vector
	if dot(xi,xi) == 0.0
		exitflag = 1;
		break;
	end
	[xbrac,fxbrac,bflag,p,fp,gfp,addfevals] = ...
	  spminbracket(z,x,fval,-neggf,xi,xbox,[],stepsize);
	nfevals = nfevals + addfevals;

	if bflag == 0 || bflag == 2
		% Compute tolx along the search line
		brentopt.TolX = abs(dot(xi / norm(xi), tolxvec));
		brentopt.gf = -neggf;
		[u,fnext,flag,tempoutput] = spbrent(z,x,xi,xbrac,fxbrac,brentopt);

		% Next line intentionally commented out (AK)
		% if 2.0*(fnext-fprev) <= tolfun * (abs(fnext)+abs(fprev)+eps);

		% Security check that fval has not increased beyond
		% allowed tolerance for break condition
		fval = fnext;
		stepsize = norm(xi * u);
		x = x + xi * u;

		% Next line intentionally commented out (AK)
		% end

		nfevals = nfevals + tempoutput.nFEvals;
		if isdispiter, disp(sprintf(iterstr, k, nfevals, ...
												ngradevals, fval, 'line search')); end
	else
		if isdispiter, disp(sprintf(iterstr, k, nfevals, ...
												ngradevals, fval, 'boundary hit')); end
		stepsize = norm(x-p);
		x = p;
		fval = fp;
		xi = gfp;
		ngradevals = ngradevals + 1;
	end

	if 2.0*abs(fval-fprev) <= max(tolfun * (abs(fval)+abs(fprev)),abstol)
	  exitflag = 1;
	  break;
	end

	fprev = fval;
	if bflag == 0 || bflag == 2
	  [dummy, xi] = spsurfun(x,z);
		nfevals = nfevals + 1;
		ngradevals = ngradevals + 1;
	end
	dgg = dot((xi + neggf),xi);
	neggf = -xi;
	xi = neggf + dgg / gg * h;
	% Adjust search direction for boundary
	for l = 1:d
		if x(l) <= xbox(l,1) + 100*eps*(range(l,2)-range(l,1))
			if neggf(l) < 0
			  xi(l) = 0;
			elseif sign(xi(l)) < 0
			  xi(l) = neggf(l);
		  end
	  end
		if x(l) >= xbox(l,2) - 100*eps*(range(l,2)-range(l,2))
		  if neggf(l) > 0
			  xi(l) = 0;
		  elseif sign(xi(l)) > 0
			  xi(l) = neggf(l);
			end
		end
	end
	h = xi;
end

xopt = x;

% Return stats
if nargout == 4
  output.nFEvals = nfevals;
  output.nGradEvals = ngradevals;
	output.time = etime(clock, t0);
end

if strcmpi(maximize, 'on')
  xopt = [xopt NaN.*ones(size(xopt))];
	fval = [fval NaN];
	exitflag = [exitflag 0];
end

author: johannesgerer

repo: jburkardt-m


text:
function [dat] = read_neuralynx_sdma(dataset, begsample, endsample, chanindx)

% READ_NEURALYNX_SDMA read specified channels and samples from a Neuralynx splitted DMA dataset
%
% Use as
%    [hdr] = read_neuralynx_sdma(dataset)
%    [dat] = read_neuralynx_sdma(dataset, begsample, endsample, chanindx)
%
% The splitted DMA dataset is not a formal Neuralynx format, but at
% the FCDC we use it in conjunction with SPIKEDOWNSAMPLE. The dataset
% directory contains files, one for each channel, each containing a
% 8-byte header followed by the binary values for all samples. Commonly
% the binary values are represented as int32, but it is possible to use
% int16 or other numeric representations. The 8-byte header specifies the
% numeric representation and the bitshift that should be applied (in case
% of integer representations).
%
% This function returns the electrophysiological data in AD units
% and not in uV. You should look up the details of the headstage and
% the Neuralynx amplifier and scale the values accordingly.

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

needhdr = (nargin==1);
needdat = (nargin>=2);

if ~isfolder(dataset)
  ft_error('dataset should be a directory');
end

% determine the content of the dataset directory
dirlist = dir(dataset);

% determine the correspondence between files and channels
label         = cell(length(dirlist),1);
filesel       = zeros(length(dirlist),1);
headerfile    = [];
[pd, nd, xd]  = fileparts(dataset);
for i=1:length(dirlist)
  [pf, nf, x1] = fileparts(dirlist(i).name);
  [pf, nf, x2] = fileparts(nf);
  % compare the name of the channel with the name of the dataset and look at the file extention
  % the file should be called "dataset/dataset.chanlabel" or "dataset/dataset.chanlabel.bin"
  if strcmp(nf, nd) && ~isempty(x1)
    if ~isempty(x2)
      label{i}   = x2(2:end);
      filesel(i) = 1;
    elseif strcmp(x1, '.txt')
      % this is not a proper channel, but an ascii file with header info
      label{i}   = [];
      filesel(i) = 0;
      headerfile = fullfile(dataset, dirlist(i).name);
    else
      label{i}   = x1(2:end);
      filesel(i) = 1;
    end
  else
    label{i}   = [];
    filesel(i) = 0;
  end
end
label = label(filesel==1);
bytes = cell2mat({dirlist(filesel==1).bytes}); % number of bytes in each file
filelist = {dirlist(filesel==1).name};         % filename excluding the path
clear dirlist filesel pd nd xd

for i=1:length(filelist)
  % include the full path in the filename
  filelist{i} = fullfile(dataset, filelist{i});
end

% there is a preferred ordering, which corresponds with the channel order in the non-splitted DMA file
preferred = {
  'stx'
  'pid'
  'siz'
  'tsh'
  'tsl'
  'cpu'
  'ttl'
  'x01'
  'x02'
  'x03'
  'x04'
  'x05'
  'x06'
  'x07'
  'x08'
  'x09'
  'x10'
  'csc001'
  'csc002'
  'csc003'
  'csc004'
  'csc005'
  'csc006'
  'csc007'
  'csc008'
  'csc009'
  'csc010'
  'csc011'
  'csc012'
  'csc013'
  'csc014'
  'csc015'
  'csc016'
  'csc017'
  'csc018'
  'csc019'
  'csc020'
  'csc021'
  'csc022'
  'csc023'
  'csc024'
  'csc025'
  'csc026'
  'csc027'
  'csc028'
  'csc029'
  'csc030'
  'csc031'
  'csc032'
  'csc033'
  'csc034'
  'csc035'
  'csc036'
  'csc037'
  'csc038'
  'csc039'
  'csc040'
  'csc041'
  'csc042'
  'csc043'
  'csc044'
  'csc045'
  'csc046'
  'csc047'
  'csc048'
  'csc049'
  'csc050'
  'csc051'
  'csc052'
  'csc053'
  'csc054'
  'csc055'
  'csc056'
  'csc057'
  'csc058'
  'csc059'
  'csc060'
  'csc061'
  'csc062'
  'csc063'
  'csc064'
  'csc065'
  'csc066'
  'csc067'
  'csc068'
  'csc069'
  'csc070'
  'csc071'
  'csc072'
  'csc073'
  'csc074'
  'csc075'
  'csc076'
  'csc077'
  'csc078'
  'csc079'
  'csc080'
  'csc081'
  'csc082'
  'csc083'
  'csc084'
  'csc085'
  'csc086'
  'csc087'
  'csc088'
  'csc089'
  'csc090'
  'csc091'
  'csc092'
  'csc093'
  'csc094'
  'csc095'
  'csc096'
  'csc097'
  'csc098'
  'csc099'
  'csc100'
  'csc101'
  'csc102'
  'csc103'
  'csc104'
  'csc105'
  'csc106'
  'csc107'
  'csc108'
  'csc109'
  'csc110'
  'csc111'
  'csc112'
  'csc113'
  'csc114'
  'csc115'
  'csc116'
  'csc117'
  'csc118'
  'csc119'
  'csc120'
  'csc121'
  'csc122'
  'csc123'
  'csc124'
  'csc125'
  'csc126'
  'csc127'
  'csc128'
  'csc129'
  'csc130'
  'csc131'
  'csc132'
  'csc133'
  'csc134'
  'csc135'
  'csc136'
  'csc137'
  'csc138'
  'csc139'
  'csc140'
  'csc141'
  'csc142'
  'csc143'
  'csc144'
  'csc145'
  'csc146'
  'csc147'
  'csc148'
  'csc149'
  'csc150'
  'csc151'
  'csc152'
  'csc153'
  'csc154'
  'csc155'
  'csc156'
  'csc157'
  'csc158'
  'csc159'
  'csc160'
  'csc161'
  'csc162'
  'csc163'
  'csc164'
  'csc165'
  'csc166'
  'csc167'
  'csc168'
  'csc169'
  'csc170'
  'csc171'
  'csc172'
  'csc173'
  'csc174'
  'csc175'
  'csc176'
  'csc177'
  'csc178'
  'csc179'
  'csc180'
  'csc181'
  'csc182'
  'csc183'
  'csc184'
  'csc185'
  'csc186'
  'csc187'
  'csc188'
  'csc189'
  'csc190'
  'csc191'
  'csc192'
  'csc193'
  'csc194'
  'csc195'
  'csc196'
  'csc197'
  'csc198'
  'csc199'
  'csc200'
  'csc201'
  'csc202'
  'csc203'
  'csc204'
  'csc205'
  'csc206'
  'csc207'
  'csc208'
  'csc209'
  'csc210'
  'csc211'
  'csc212'
  'csc213'
  'csc214'
  'csc215'
  'csc216'
  'csc217'
  'csc218'
  'csc219'
  'csc220'
  'csc221'
  'csc222'
  'csc223'
  'csc224'
  'csc225'
  'csc226'
  'csc227'
  'csc228'
  'csc229'
  'csc230'
  'csc231'
  'csc232'
  'csc233'
  'csc234'
  'csc235'
  'csc236'
  'csc237'
  'csc238'
  'csc239'
  'csc240'
  'csc241'
  'csc242'
  'csc243'
  'csc244'
  'csc245'
  'csc246'
  'csc247'
  'csc248'
  'csc249'
  'csc250'
  'csc251'
  'csc252'
  'csc253'
  'csc254'
  'csc255'
  'csc256'
  'crc'
  };

[sel1, sel2] = match_str(preferred, label);
if length(sel2)==length(label)
  % all reorder the labels/files
  label = label(sel2);
  bytes = bytes(sel2);
  filelist = filelist(sel2);
else
  % not all files in this SDMA dataset could be accounted for in the
  % preference list, hence do not attempt to apply the preferred ordering
end

if needhdr
  % construct a general header for the complete dataset
  if ~isempty(headerfile)
    orig             = neuralynx_getheader(headerfile);
    hdr.Fs           = orig.SamplingFrequency;
    hdr.nSamples     = [];        % see below
    hdr.nSamplesPre  = 0;         % number of pre-trigger samples in each trial
    hdr.nTrials      = 1;         % number of trials
    hdr.label        = label;
    hdr.nChans       = length(label);
    hdr.orig.dataset = orig;       % keep the header details
  else
    % some parts of the header have to be hardcoded, since the splitted dataset does not contain all header information
    hdr.Fs           = 32556;     % sampling frequency
    hdr.nSamples     = [];        % see below
    hdr.nSamplesPre  = 0;         % number of pre-trigger samples in each trial
    hdr.nTrials      = 1;         % number of trials
    hdr.label        = label;
    hdr.nChans       = length(label);
  end

  % read the header of each individual file, i.e. for each variable
  clear orig
  for i=1:length(filelist)
    orig(i) = read_neuralynx_bin(filelist{i});
  end

  % determine the number of samples for each channel
  nsamples = cell2mat({orig.nSamples});
  if any(nsamples~=nsamples(1))
    ft_error('different number of samples over channels are not supported');
  else
    hdr.nSamples = nsamples(1);
  end

  % determine the sampling frequency for each channel
  fsample = cell2mat({orig.Fs});
  if any(diff(fsample))
    ft_error('different sampling rates over channels are not supported');
  elseif any(fsample~=hdr.Fs)
    ft_error('inconsistent sampling rates');
  end

  % determine the first and last timestamp, by reading them from the timestamp channels
  tslfile = filelist{find(strcmp('tsl', label))};
  tshfile = filelist{find(strcmp('tsh', label))};
  beg_tsl = read_neuralynx_bin(tslfile, 1, 1);
  beg_tsh = read_neuralynx_bin(tshfile, 1, 1);
  end_tsl = read_neuralynx_bin(tslfile, hdr.nSamples, hdr.nSamples);
  end_tsh = read_neuralynx_bin(tshfile, hdr.nSamples, hdr.nSamples);
  hdr.FirstTimeStamp = timestamp_neuralynx(beg_tsl, beg_tsh);
  hdr.LastTimeStamp  = timestamp_neuralynx(end_tsl, end_tsh);
  hdr.TimeStampPerSample = double(hdr.LastTimeStamp-hdr.FirstTimeStamp)./(hdr.nSamples-1);  % this should be double, since it can be fractional

  % also remember the original header details
  hdr.orig.chan = orig;

  % only return the header information
  dat = hdr;

else
  % allocate memory for all data
  dat = zeros(length(chanindx), endsample-begsample+1);

  % read all channels, one small chunk at at time, and write it to separate files
  for i=1:length(chanindx)
    j = chanindx(i);
    dat(i,:) = double(read_neuralynx_bin(filelist{j}, begsample, endsample));
  end
end


text:
function A = skew(a)
% Return the skew matrix or its original vector
%
% USAGE
%  A=skew(a)
%
% INPUTS 1 - returns the skew matrix of a vector
%  a       - 3x1 or 1x3 vector
%
% INPUTS 2 - returns the vector that created the closest skew matrix
%  a       - 3x3 skew matrix
%
% OUTPUTS 1
%  A       - corresponding skew matrix
%
% OUTPUTS 2
%  A       - vector that created the matrix
%
% EXAMPLE
%
% See also
%
% Vincent's Structure From Motion Toolbox      Version 3.1.1
% Copyright (C) 2008-2011 Vincent Rabaud.  [vrabaud-at-cs.ucsd.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the GPL [see external/gpl.txt]

if numel(a)==3
  % returns the skew matrix of a vector
  % Reference: HZ2, p581, equation (A4.5)
  A=[0 -a(3) a(2); a(3) 0 -a(1); -a(2) a(1) 0];
  return
end

if all(size(a)==[3,3])
  % returns the vector that created the closest skew matrix
  A=0.5*[ a(3,2)-a(2,3); a(1,3)-a(3,1); a(2,1)-a(1,2)];
  return
end

error('Bad input dimensions. Input must be 1x3, 3x1 or 3x3');

author: vrabaud


text:
function res = is_symbolic_lambda(x)
% internal: a symbolic lambda function is one which generates expressions when invoked with arguments (this is what exp_symbol generates)
res = isa(x,'function_handle') && ~isempty(regexp(char(x),'@\(varargin\)struct\(''head'',\{.*\},''parts'',\{varargin\}\)','once'));

repo: REST


text:
function dt = dtiImgToInd(dt, mask)
%Convert dti image to an alternative format
%
%    Yind = dtiImgToInd(Y, [MASK])
%
% Takes a XxYxZxpxN array as input and converts it to indexed form nxpxN,
% where n corresponds to a list of coordinates given by find(MASK).
%
% The form DT = dtiImgToInd(DT) works on the entire structure DT and
% implements the inverse of dtiIndToImg.m, in which case DT.mask is used as default.
% This results in a compression factor of about 50.
%
% See also:
%   dtiLoadTensorSubjects.m, dtiIndToImg.m
%
% HISTORY:
%   2004.11.24 Armin Shwartzmann wrote it

% If not struct
if ~isstruct(dt),
    Y = dt;
    sz = size(Y);
    L = prod(sz(1:3));
    N = sz(4:end);
    if isempty(N), N = 1; end
    Yind = reshape(Y, [L N]);
    imask = find(mask);
    Yind = Yind(imask,:);
    Yind = reshape(Yind, [length(imask) N]);
    dt = Yind;
    return
end

% If struct
if ~isfield(dt,'format'),
    error('Format field does not exist')
end
if strcmp(dt.format, 'Ind'),
    error('Data already in Ind format')
end
if ~exist('mask'),
    mask = dt.mask;
end

L = numel(mask);
imask = find(mask);

if isfield(dt,'fa'),
    N = size(dt.fa,4);
    Y = reshape(dt.fa, [L N]);
    dt.fa = Y(imask,:);
end
if isfield(dt,'val'),
    if (size(dt.val,4)~=3), error('Wrong "val" format'), end
    N = size(dt.val,5);
    Y = reshape(dt.val, [L 3 N]);
    dt.val = Y(imask,:,:);
end
if isfield(dt,'vec'),
    if (size(dt.vec,4)~=3 | size(dt.vec,5)~=3), error('Wrong "vec" format'), end
    N = size(dt.vec,6);
    Y = reshape(dt.vec, [L 3 3 N]);
    dt.vec = Y(imask,:,:,:);
end
if isfield(dt,'dt6'),
    if (size(dt.dt6,4)~=6), error('Wrong "val" format'), end
    N = size(dt.dt6,5);
    Y = reshape(dt.dt6, [L 6 N]);
    dt.dt6 = Y(imask,:,:);
end

dt.format = 'Ind';

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [U, s, V] = fft_svd(PSF, center)
%
%   [U, s, V] = fft_svd(PSF, center);
%
%  Given a PSF this function computes an "SVD" factorization
%  for periodic boundary conditions.  That is, the "SVD" is
%  "Spectral Value Decomposition":
%            A = USV',
%  where U = V = inverse DFT matrix.
%
%  On Entry:
%     A  -  psfMatrix obect, with periodic boundary conditions
%
%  On Exit:
%     U, V  -  transformMatrix objects, with
%              U.transform = V.transform = 'fft'
%        s  -  column vector containing the eigenvalues
%              of A.  Note that these are not sorted from largest
%              smallest.
%
P = circshift(PSF, -(center - 1));
S = fftn(P);
s = S(:);

U = transformMatrix('fft');
U = U';
V = transformMatrix('fft');
V = V';

repo: IRtools


text:
function [f1,W,beta,grt] = par_fun_B(theta,W_old,K,M,Pt,omega,Hd,Hr,G)
    Theta=diag(theta');
    H=Hd+Hr*Theta*G;
    W_span=W_old;
    [ ~,grt,f0 ] = update_SINR( H,W_old,K,omega );
    [ beta ] =upadte_beta( H,W_old,K,grt);
    while(1)
        [ A,L ] = Proxlinear_beam_para( H,K,M,beta );
        [ W ] =Proxlinear_beam_v2( W_span,H,K,M,grt,Pt,beta,omega,A,L );
        W_span=W;%+step*(W-W_last);
        [ ~,grt,f1 ] = update_SINR( H,W,K,omega );
        [ beta ] =upadte_beta( H,W,K,grt);
        if abs(f0-f1)<1e-3
            break
        end
        f0=f1;
    end
end

author: guohuayan


text:
function drawPnt(h,x,c)

% DRAWPNT  Draw 3D point with color.
%   DRAWPNT(H,X) Draw 2D or 3D point with handle H at position X.
%
%   DRAWPNT(H,X,C) uses color C.

%   Copyright 2008-2009 Joan Sola @ LAAS-CNRS.

if numel(x) == 2

    set(h,'xdata',x(1),'ydata',x(2),'vis','on')

elseif numel(x) == 3

    set(h,'xdata',x(1),'ydata',x(2),'zdata',x(3),'vis','on')

else

    error('??? Size of vector ''x'' not correct.')

end

if nargin == 3
    set(h,'color',c)
end

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

%   # START GPL LICENSE

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

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

%   # END GPL LICENSE

author: joansola

repo: slamtb

save_path: github-repos/MATLAB/joansola-slamtb