text:
function varargout= mcorr(varargin)
%MCORR Multi-plot of all correlations between columns of a matrix
% MCORR (X) plots correlations between all possible combinations of the
% columns of array X, in a single figure. If the first argument is the
% name of a file present in the current directory, mcorr reads
% it (including variable names in the first row) as X. Otherwise, MCORR assumes
% its first argument is the array to plot, in which case consecutive
% numbers will be used as variable names. If there is a second (numeric)
% argument, mcorr will plot only the columns indicated in the second argument.
% mcorr does not plot self-correlations (each variable with itself). It
% is unpractical to try to plot more than, say, 8 variables, since each
% individual plot becomes too small.
%
% OUTPUT= MCORR (X,'sig') calculates the Pearson correlation coefficient between
% each pair of columns and, if the correlation is sgnificant at the 95%
% level, points are plotted in red and the column numbers, Pearson coefficient
% and p-value are returned in the OUTPUT array. Requires Statistical Toolbox
%
% EXAMPLES:
% mcorr ('myfile')
% mcorr ('myfile',[1:5])
% mcorr (X,[3:6])
% output= mcorr (X,'sig')
%
% Last modified: Feb. 2008

if nargin == 0 error ('mcorr needs at least 1 argument: name of file or array'); end
pearson= 0;
color= 'b';
output= [];

%Its a file => Read. Else is matrix
if ischar(varargin{1}) & ~isempty(dir(varargin{1}))
	[A,varnames] = tblread(varargin{1});
else
	A= varargin{1};
 	varnames= num2cell([1:size(A,2)]);
end

%Select columns
if nargin > 1 & isnumeric(varargin{2})
	A= A(:,varargin{2});
	varnames= varnames(varargin{2});
end
ncol= size(A,2);

%Pearson corr. coef.
for j= 1:length(varargin)
	if ischar(varargin{j}) & ~isempty(findstr(lower(varargin{j}),'sig'))
		pearson= 1;
	end
end

%Function
for j= 2:ncol
for k= 1:j-1
	subplot(ncol-1,ncol-1,(j-2)*(ncol-1)+k);
	if pearson [rho,pval]= corr(A(:,k),A(:,j));
		if pval < 0.05
			color= 'r';
			output= [output;k,j,rho,pval];
		else
			color= 'b';
		end
	end
	plot(A(:,k),A(:,j),'.','MarkerSize',5,'MarkerEdgeColor',color);
	set (gca,'FontSize',6);
	if k == 1 ylabel(varnames(j),'FontSize',7); end
	if j == ncol xlabel(varnames(k),'FontSize',7); end
end
end

varargout{1}= output;

author: Sable

repo: mcbench-benchmarks


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

% Last Modified by GUIDE v2.5 03-Jan-2021 15:29:14

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

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

    centerUIFigure(hObject);

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

    handles = populateGUI(handles, fminconOpt);

    % Update handles structure
    guidata(hObject, handles);

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

function handles = populateGUI(handles, fminconOpt)
    options = fminconOpt.getOptions();

    setDocLbl(handles);

    algoListboxStr = LvdFminconAlgorithmEnum.getListBoxStr();
    handles.algoCombo.String = algoListboxStr;
    handles.algoCombo.Value = LvdFminconAlgorithmEnum.getIndForName(options.algorithm.name);

    finiteDiffTypeStrs = FminconFiniteDiffTypeEnum.getListBoxStr();
    handles.finiteDiffTypeCombo.String = finiteDiffTypeStrs;
    handles.finiteDiffTypeCombo.Value = FminconFiniteDiffTypeEnum.getIndForName(options.finDiffType.name);

    typicalXStrs = OptimizerTypicalXEnum.getListBoxStr();
    handles.typicalXCombo.String = typicalXStrs;
    handles.typicalXCombo.Value = OptimizerTypicalXEnum.getIndForName(options.typicalXType.name);

    hessApproxStrs = FminconHessApproxAlgEnum.getListBoxStr();
    handles.IpApproxAlgoCombo.String = hessApproxStrs;
    handles.IpApproxAlgoCombo.Value = FminconHessApproxAlgEnum.getIndForName(options.hessianApproxAlg.name);

    subProbStrs = FminconIpSubprobAlgEnum.getListBoxStr();
    handles.IpSubproblemAlgoCombo.String = subProbStrs;
    handles.IpSubproblemAlgoCombo.Value = FminconIpSubprobAlgEnum.getIndForName(options.subproblemAlgorithm.name);

    useParaStr = FminconUseParallelEnum.getListBoxStr();
    handles.useParallelCombo.String = useParaStr;
    handles.useParallelCombo.Value = FminconUseParallelEnum.getIndForName(options.useParallel.name);

    setOptsDoubleValueStrInGUI(handles, options, 'optTol', 'optTolText');
    setOptsDoubleValueStrInGUI(handles, options, 'tolCon', 'conTolText');
    setOptsDoubleValueStrInGUI(handles, options, 'stepTol', 'stepTolText');

    setOptsDoubleValueStrInGUI(handles, options, 'maxIter', 'maxItersText');
    setOptsDoubleValueStrInGUI(handles, options, 'maxFuncEvals', 'maxFuncEvalsText');

    setOptsDoubleValueStrInGUI(handles, options, 'finDiffStepSize', 'finiteDiffStepSizeText');

    setOptsDoubleValueStrInGUI(handles, options, 'initBarrierParam', 'IpInitBarrierParamText');
    setOptsDoubleValueStrInGUI(handles, options, 'initTrustRegionRadius', 'IpInitTrustRegionRadiusText');
    setOptsDoubleValueStrInGUI(handles, options, 'maxProjCGIter', 'IpMaxProjCGItersText');
    setOptsDoubleValueStrInGUI(handles, options, 'tolProjCG', 'IpRelProjCGTolText');
    setOptsDoubleValueStrInGUI(handles, options, 'tolProjCGAbs', 'IpAbsProjCGTolText');

    setOptsDoubleValueStrInGUI(handles, options, 'funcTol', 'AsFuncTolText');
    setOptsDoubleValueStrInGUI(handles, options, 'maxSQPIter', 'AsMaxSqpItersText');
    setOptsDoubleValueStrInGUI(handles, options, 'relLineSrchBnd', 'AsRelLineSrchBndText');
    setOptsDoubleValueStrInGUI(handles, options, 'relLineSrchBndDuration', 'AsLineSrchBndDurText');
    setOptsDoubleValueStrInGUI(handles, options, 'tolConSQP', 'AsTolConSqpText');

    setOptsDoubleValueStrInGUI(handles, options, 'numWorkers', 'numParaWorkersText');

    handles.computeOptimalStepCheckbox.Value = double(options.computeOptimalStepSizes);
    computeOptimalStepCheckbox_Callback(handles.computeOptimalStepCheckbox, [], handles);

function setDocLbl(handles)
    docLinkLblPos = handles.matlabDocLinkLabel.Position;
    docLinkLblParent = handles.matlabDocLinkLabel.Parent;
    handles.matlabDocLinkLabel.Visible = 'off';

    % Create and display the text label
    url = 'https://www.mathworks.com/help/optim/ug/fmincon.html';
    labelStr = ['
For more information, visit the MATLAB documentation for FMINCON: ' url '
'];
    jLabel = javaObjectEDT('javax.swing.JLabel', labelStr);
    [hjLabel,~] = javacomponent(jLabel, docLinkLblPos, docLinkLblParent);

    % Modify the mouse cursor when hovering on the label
    hjLabel.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));

    % Set the mouse-click callback
    set(hjLabel, 'MouseClickedCallback', @(h,e)web([url], '-browser'));

% --- Outputs from this function are returned to the command line.
function varargout = lvd_editFminconOptionsGUI_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
        fminconOpt = getappdata(hObject,'fminconOpt');
        options = fminconOpt.getOptions();

        algoListboxStr = LvdFminconAlgorithmEnum.getListBoxStr();
        options.algorithm = LvdFminconAlgorithmEnum.getEnumForListboxStr(algoListboxStr{handles.algoCombo.Value});

        finiteDiffTypeStrs = FminconFiniteDiffTypeEnum.getListBoxStr();
        options.finDiffType = FminconFiniteDiffTypeEnum.getEnumForListboxStr(finiteDiffTypeStrs{handles.finiteDiffTypeCombo.Value});

        typicalXStrs = OptimizerTypicalXEnum.getListBoxStr();
        options.typicalXType = OptimizerTypicalXEnum.getEnumForListboxStr(typicalXStrs{handles.typicalXCombo.Value});

        hessApproxStrs = FminconHessApproxAlgEnum.getListBoxStr();
        options.hessianApproxAlg = FminconHessApproxAlgEnum.getEnumForListboxStr(hessApproxStrs{handles.IpApproxAlgoCombo.Value});

        subProbStrs = FminconIpSubprobAlgEnum.getListBoxStr();
        options.subproblemAlgorithm = FminconIpSubprobAlgEnum.getEnumForListboxStr(subProbStrs{handles.IpSubproblemAlgoCombo.Value});

        useParaStrs = FminconUseParallelEnum.getListBoxStr();
        options.useParallel = FminconUseParallelEnum.getEnumForListboxStr(useParaStrs{handles.useParallelCombo.Value});

        setOptsDoubleValueInObject(handles, options, 'optTol', 'optTolText');
        setOptsDoubleValueInObject(handles, options, 'stepTol', 'conTolText');
        setOptsDoubleValueInObject(handles, options, 'tolCon', 'stepTolText');

        setOptsDoubleValueInObject(handles, options, 'maxIter', 'maxItersText');
        setOptsDoubleValueInObject(handles, options, 'maxFuncEvals', 'maxFuncEvalsText');

        setOptsDoubleValueInObject(handles, options, 'finDiffStepSize', 'finiteDiffStepSizeText');

        setOptsDoubleValueInObject(handles, options, 'initBarrierParam', 'IpInitBarrierParamText');
        setOptsDoubleValueInObject(handles, options, 'initTrustRegionRadius', 'IpInitTrustRegionRadiusText');
        setOptsDoubleValueInObject(handles, options, 'maxProjCGIter', 'IpMaxProjCGItersText');
        setOptsDoubleValueInObject(handles, options, 'tolProjCG', 'IpRelProjCGTolText');
        setOptsDoubleValueInObject(handles, options, 'tolProjCGAbs', 'IpAbsProjCGTolText');

        setOptsDoubleValueInObject(handles, options, 'funcTol', 'AsFuncTolText');
        setOptsDoubleValueInObject(handles, options, 'maxSQPIter', 'AsMaxSqpItersText');
        setOptsDoubleValueInObject(handles, options, 'relLineSrchBnd', 'AsRelLineSrchBndText');
        setOptsDoubleValueInObject(handles, options, 'relLineSrchBndDuration', 'AsLineSrchBndDurText');
        setOptsDoubleValueInObject(handles, options, 'tolConSQP', 'AsTolConSqpText');

        setOptsDoubleValueInObject(handles, options, 'numWorkers', 'numParaWorkersText');

        options.computeOptimalStepSizes = logical(handles.computeOptimalStepCheckbox.Value);

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

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

    errMsg = validateDoubleValue(handles, errMsg, 'optTolText', 'Optimality Tolerance', 0, 1, false);
    errMsg = validateDoubleValue(handles, errMsg, 'conTolText', 'Constraint Tolerance', 0, 1, false);
    errMsg = validateDoubleValue(handles, errMsg, 'stepTolText', 'Step Tolerance', 0, 1, false);

    errMsg = validateDoubleValue(handles, errMsg, 'maxItersText', 'Max Iterations', 0, Inf, true);
    errMsg = validateDoubleValue(handles, errMsg, 'maxFuncEvalsText', 'Max Function Evaluations', 0, Inf, true);

	errMsg = validateDoubleValue(handles, errMsg, 'finiteDiffStepSizeText', 'Finite Difference Step Size', 1E-10, 1E-2, false);

	errMsg = validateDoubleValue(handles, errMsg, 'IpInitBarrierParamText', 'I-P Intial Barrier Param', 1E-10, Inf, false);
    errMsg = validateDoubleValue(handles, errMsg, 'IpInitTrustRegionRadiusText', 'I-P Initial Trust Region', 1E-10, Inf, false);
    errMsg = validateDoubleValue(handles, errMsg, 'IpMaxProjCGItersText', 'I-P Max Projected C.G. Iterations', 1, Inf, true);
    errMsg = validateDoubleValue(handles, errMsg, 'IpRelProjCGTolText', 'I-P Relative Projected C.G. Tolerance', 1E-10, Inf, false);
    errMsg = validateDoubleValue(handles, errMsg, 'IpAbsProjCGTolText', 'I-P Absolute Projected C.G. Tolerance', 1E-10, Inf, false);

    errMsg = validateDoubleValue(handles, errMsg, 'AsFuncTolText', 'A-S Function Tolerance', 1E-10, 1, false);
    errMsg = validateDoubleValue(handles, errMsg, 'AsMaxSqpItersText', 'A-S Max SQP Iterations', 1, Inf, true);
    errMsg = validateDoubleValue(handles, errMsg, 'AsRelLineSrchBndText', 'A-S Relative Line Search Bound', 0, Inf, false);
    errMsg = validateDoubleValue(handles, errMsg, 'AsLineSrchBndDurText', 'A-S Line Search Bound Duration', 1, Inf, true);
    errMsg = validateDoubleValue(handles, errMsg, 'AsTolConSqpText', 'A-S Inner SQP Constraint Tolerance', 1E-10, Inf, false);

    errMsg = validateDoubleValue(handles, errMsg, 'numParaWorkersText', 'Number of Parallel Workers', 1, feature('numCores'), true);

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

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

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

% --- Executes during object creation, after setting all properties.
function stepTolText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to stepTolText (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 selection change in algoCombo.
function algoCombo_Callback(hObject, eventdata, handles)
% hObject    handle to algoCombo (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 algoCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from algoCombo

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

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

% --- Executes during object creation, after setting all properties.
function maxFuncEvalsText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxFuncEvalsText (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 selection change in finiteDiffTypeCombo.
function finiteDiffTypeCombo_Callback(hObject, eventdata, handles)
% hObject    handle to finiteDiffTypeCombo (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 finiteDiffTypeCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from finiteDiffTypeCombo

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

% --- Executes during object creation, after setting all properties.
function finiteDiffStepSizeText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to finiteDiffStepSizeText (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 selection change in typicalXCombo.
function typicalXCombo_Callback(hObject, eventdata, handles)
% hObject    handle to typicalXCombo (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 typicalXCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from typicalXCombo

% --- Executes during object creation, after setting all properties.
function typicalXCombo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to typicalXCombo (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 IpApproxAlgoCombo.
function IpApproxAlgoCombo_Callback(hObject, eventdata, handles)
% hObject    handle to IpApproxAlgoCombo (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 IpApproxAlgoCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from IpApproxAlgoCombo

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

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

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

% --- Executes during object creation, after setting all properties.
function IpMaxProjCGItersText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to IpMaxProjCGItersText (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 selection change in IpSubproblemAlgoCombo.
function IpSubproblemAlgoCombo_Callback(hObject, eventdata, handles)
% hObject    handle to IpSubproblemAlgoCombo (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 IpSubproblemAlgoCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from IpSubproblemAlgoCombo

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

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

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

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

% --- Executes on button press in 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_editFminconOptionsGUI);
    else
        msgbox(errMsg,'Invalid FMINCON Options Inputs','error');
    end

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

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

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

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

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

% --- Executes during object creation, after setting all properties.
function AsFuncTolText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to AsFuncTolText (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 selection change in useParallelCombo.
function useParallelCombo_Callback(hObject, eventdata, handles)
% hObject    handle to useParallelCombo (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 useParallelCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from useParallelCombo

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

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

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

% --- Executes on button press in computeOptimalStepCheckbox.
function computeOptimalStepCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to computeOptimalStepCheckbox (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 computeOptimalStepCheckbox
    if(get(hObject,'Value'))
        handles.finiteDiffStepSizeText.Enable = 'off';
    else
        handles.finiteDiffStepSizeText.Enable = 'on';
    end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function [annotationString,notes] = makeSBMLAnnotationString(model,id,fieldentries,position,mergeAnnotations)
% makeSBMLAnnotationString gives the annotationString for an SBML based on the fields in the model
%
% USAGE:
%
%       [annotationString, notes] = makeSBMLAnnotationString(model,id,fieldentries,position)
%
% INPUT:
%    model:            the model to extract the data
%    id:               the ID of the entity
%    fieldentries:     either a char indicating the field
%                      (prot,met,rxn,comp,gene), or a cell array with X{:,1}
%                      being field IDs and X{:,2} being bioql qualiiers to
%                      annotate for the field.
%    position:         the position in the model to extract the data.
% OPTIONAL INPUTS:
%    mergeAnnotations: If multiple fields are given, merge the fields and
%                      only produce one annotation.
% OUTPUT:
%
%   annotationString: The annotation String to be put into the SBML.
%   notes:            A 2*x cell array of fields which did not contain
%                     valid identifiers (according to the pattern check.
%
% .. Authors:
%       - Thomas Pfau May 2017

allQualifiers = getBioQualifiers();

if ischar(fieldentries)
    fieldentries = {fieldentries, allQualifiers};
end

if ~exist('mergeAnnotations','var')
    mergeAnnotations = false;
end

annotationString = '';
modelFields = fieldnames(model);
%Only look at the relevant fields.
tmp_note = '';
notes = cell(0,2);
bagindentlevel = '      ';
qualifierMap = containers.Map();
for pos = 1:size(fieldentries,1)
    field = fieldentries{pos,1};
    if isempty(fieldentries{pos,2})
        allowedQualifiers = allQualifiers;
    else
        allowedQualifiers = fieldentries{pos,2};
    end
    fieldMappings = getDatabaseMappings(field);
    [~,upos,~] = unique(fieldMappings(:,3));
    fieldMappings = fieldMappings(upos,:);

    relfields = modelFields(cellfun(@(x) strncmp(x,field,length(field)),modelFields));

    for i = 1:numel(allowedQualifiers)
        annotationsFields = relfields(cellfun(@(x) strncmp(x,[field allowedQualifiers{i}],length([field allowedQualifiers{i}])),relfields));

        knownFields = fieldMappings(cellfun(@(x) strcmp(x,allowedQualifiers{i}),fieldMappings(:,2)),:);
        %if we merge the annotations,
        dbnote = {};
        for fieldid = 1:numel(annotationsFields)
            if isempty(model.(annotationsFields{fieldid}){position})
                continue
            end
            % get the IDs from the model field and check them against
            % database properties.
            ids = strsplit(model.(annotationsFields{fieldid}){position},'; ');
            dbname = convertSBMLID(regexprep(annotationsFields{fieldid},[field allowedQualifiers{i} '(.*)' 'ID$'],'$1'),false);
            dbrdfstring = [bagindentlevel '    <rdf:li rdf:resource="http://identifiers.org/' dbname '/'];
            dbstring = strjoin(strcat(dbrdfstring,ids,sprintf('%s\n','"/>')),sprintf('\n'));
            dbnote{end+1} = dbstring;
        end
        knownExistentFields = knownFields(ismember(knownFields(:,3),modelFields),:);

        for fieldid = 1:size(knownExistentFields,1)
            if isempty(model.(knownExistentFields{fieldid,3}){position})
                continue
            end
            ids = strtrim(strsplit(model.(knownExistentFields{fieldid,3}){position},';'));
            correctids = ~cellfun(@isempty, regexp(ids,knownExistentFields{fieldid,5}));
            %If we have correct ids, we will annotate those.
            if any(correctids)
                dbname = knownExistentFields{fieldid,1};
                dbrdfstring = [bagindentlevel '    <rdf:li rdf:resource="http://identifiers.org/' dbname '/'];
                dbstring = strjoin(strcat(dbrdfstring,ids(correctids),sprintf('%s\n','"/>')),sprintf('\n'));
                dbnote{end+1} = dbstring;
            end
            %if we have incorrect ids, we will add this data to the notes
            %of the reaction.
            if any(~correctids)
                notes(end+1,:) = {knownExistentFields{fieldid,3}, model.(knownExistentFields{fieldid,3}){position}};
            end
        end
        if ~mergeAnnotations
            if ~isempty(dbnote)
                %Make specification for this bag
                specstring = ['<bqbiol:' allowedQualifiers{i} ' xmlns:bqbiol="http://biomodels.net/biology-qualifiers/">' ];
                specend = ['</bqbiol:' allowedQualifiers{i} '>'];

                specification_string = sprintf('%s%s\n%s  %s\n%s%s\n',bagindentlevel,specstring,bagindentlevel,'<rdf:Bag/>',bagindentlevel,specend);

                tmp_note=[specification_string, tmp_note, bagindentlevel, '<bqbiol:', allowedQualifiers{i}, sprintf('%s\n%s  %s\n','>', bagindentlevel,'<rdf:Bag>')];
                tmp_note = [tmp_note, [dbnote{:}] ];
                tmp_note = [ tmp_note, sprintf('\n  %s%s\n%s%s\n',bagindentlevel,'</rdf:Bag>',bagindentlevel, ['</bqbiol:' allowedQualifiers{i} '>'])]; % ending syntax

            end
        else
            if qualifierMap.isKey(allowedQualifiers{i})
                qualifierMap(allowedQualifiers{i}) = unique([dbnote,qualifierMap(allowedQualifiers{i})]);
            else
                qualifierMap(allowedQualifiers{i}) = dbnote;
            end
        end
    end
end
% merge Annotations from the same qualifiers. This allows multiple
% properties to be matched to the same field.
if mergeAnnotations
    allowedQualifiers = qualifierMap.keys();
    for i = 1:numel(allowedQualifiers)
        dbnote = qualifierMap(allowedQualifiers{i});
        if ~isempty(dbnote)
            specstring = ['<bqbiol:' allowedQualifiers{i} ' xmlns:bqbiol="http://biomodels.net/biology-qualifiers/">' ];
            specend = ['</bqbiol:' allowedQualifiers{i} '>'];

            specification_string = sprintf('%s%s\n%s  %s\n%s%s\n',bagindentlevel,specstring,bagindentlevel,'<rdf:Bag/>',bagindentlevel,specend);

            tmp_note=[specification_string, tmp_note, bagindentlevel, '<bqbiol:', allowedQualifiers{i}, sprintf('%s\n%s  %s\n','>', bagindentlevel,'<rdf:Bag>')];
            tmp_note = [tmp_note, [dbnote{:}] ];
            tmp_note = [ tmp_note, sprintf('\n  %s%s\n%s%s\n',bagindentlevel,'</rdf:Bag>',bagindentlevel, ['</bqbiol:' allowedQualifiers{i} '>'])]; % ending syntax
        end
    end
end

if ~isempty(tmp_note)
    annotopentag = '<annotation xmlns:sbml="http://www.sbml.org/sbml/level3/version1/core">';
    rdfOpenTag = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vCard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:vCard4="http://www.w3.org/2006/vcard/ns#" xmlns:bqbiol="http://biomodels.net/biology-qualifiers/" xmlns:bqmodel="http://biomodels.net/model-qualifiers/">';
    annotationString = sprintf('%s\n  %s\n    ',annotopentag,rdfOpenTag);
    annotationString = [ annotationString '<rdf:Description rdf:about="#',id,'">'];
    annotationString = [annotationString sprintf('\n')];
    annotationString = [annotationString, tmp_note, sprintf('    %s\n  %s\n%s','</rdf:Description>', '</rdf:RDF>', '</annotation>')];
end
end

author: opencobra

repo: cobratoolbox


text:
function [reg_kth_largest,num_regions] = get_kth_islands(img_b,k_th)
% extract the kth largest image island from a binary image, and
% give the total number of islands in this binary image
    img_label = bwlabel(img_b);
    reg_size = regionprops(img_label,'Area');
    reg = cat(1,reg_size.Area);
    num_regions = length(reg);
    if num_regions == 0
        error('cannot find any image island');
    end
    reg_sorted = sort(reg,'descend');
    ind = find(reg == reg_sorted(k_th));
    reg_kth_largest = ismember(img_label,ind);
end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function y = rdivide(X,Y)
%RDIVIDE (overloaded)

% Check dimensions
[nx,mx] = size(X);
[ny,my] = size(Y);
if ~((prod(size(X))==1) | (prod(size(Y))==1))
    if ~((nx==ny & (mx ==my)))
        error('Matrix dimensions must agree.')
    end
end

% Quick exit for simple case X/scalar
if isnumeric(Y) & prod(size(Y))==1
    y = X;
    y.basis = y.basis/Y;
    % Reset info about conic terms
    y.conicinfo = [0 0];
    return
end

if isa(X,'sdpvar') & isnumeric(Y)
    y = X.*(1./Y);
    return
end

% normalize scalar./matrix and matrix./scalar
[nx,mx] = size(X);
[ny,my] = size(Y);
if prod(size(X)) == 1 & prod(size(Y))~=1
    X = repmat(X,ny,my);
end;
if prod(size(Y)) == 1 & prod(size(X))~=1
    Y = repmat(Y,nx,mx);
end

% power is optimized already for simple cases
y = X.*(Y.^(-1));

% Reset info about conic terms
if isa(y,'sdpvar')
    y.conicinfo = [0 0];
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function Gamma = ehmminit(data,T,options)
%
% Initialise the ehmm chain using iterative vanilla K=2 HMMs
%
% INPUT
% data      observations, a struct with X (time series) and C (classes, optional)
% T         length of observation sequence
% options   structure with the training options
% Sind
%
% OUTPUT
% Gamma     p(state given X)
%
% Author: Diego Vidaurre, Aarhus University / Oxford , 2020

if ~isfield(options,'maxorder')
    [~,order] = formorders(options.order,options.orderoffset,...
        options.timelag,options.exptimelag);
    options.maxorder = order;
end
K = options.K;
if isfield(options,'initTestSmallerK') && options.initTestSmallerK
    warning('Option initTestSmallerK ignored')
end
% provided_baseline = ...
%     (isfield(options,'ehmm_baseline_data') && ~isempty(options.ehmm_baseline_data)) ...
%     || (isfield(options,'ehmm_baseline_w') && ~isempty(options.ehmm_baseline_w));
% r = 1; stop = false;

if isfield(options,'ehmm_baseline_data') && ~isempty(options.ehmm_baseline_data)
    baseline = computeBaseline(options);
elseif (isfield(options,'ehmm_baseline_w') && ~isempty(options.ehmm_baseline_w))
    if isstruct(options.ehmm_baseline_w)
        baseline = options.ehmm_baseline_w;
    else
        baseline = struct(); baseline.Mu_W = options.ehmm_baseline_w;
    end
else
    baseline = computeBaseline(options,data.X,T);
end

[hmm,I,G] = run_short_hmm_batches(data,T,options,K);
Gamma = findStandoutChains(T-options.order,hmm,baseline,I,G,K);

end

function [hmm,I,G] = run_short_hmm_batches(data,T,options,K)
L = 10000; step = 2000; threshold = 20;
N = length(T); order = options.order;
hmm = []; I = []; G = [];
for j = 1:N
    t0 = sum(T(1:j-1)); t0g = t0 - (j-1) * order;
    t =  t0 + (1:(L+order)); tg = t0g + (1:L);
    while t(end) <= T
        dat = data; dat.X = dat.X(t,:);
        [hm,g] = run_short_hmm(dat,length(t),options,K);
        if isempty(hmm)
            hmm = hm;
        else
            for k = 1:length(hm.state)
                if sum(g(:,k))>threshold
                    hmm.state(end+1) = hm.state(k);
                end
            end
        end
        for k = 1:length(hm.state)
            if sum(g(:,k))>threshold
                I = [I; [tg(1) tg(end)]];
                G = [G single(g(:,k))];
            end
        end
        t = t + step; tg = tg + step;
    end
end
end

function [hmm,Gamma] = run_short_hmm(data,T,options,K)
options.K = K;
GammaInit = initGamma_random(T-options.maxorder,K,...
    min(median(double(T))/10,500));
hmm = struct('train',struct());
hmm.K = K;
hmm.train = options;
hmm.train.ndim = size(data.X,2);
hmm.train.cyc = hmm.train.cyc;
hmm.train.verbose = 0; %%%%
hmm.train.episodic = 0;
hmm.train.Pstructure = true(options.K);
hmm.train.Pistructure = true(1,options.K);
hmm.train.stopcriterion = 'FreeEnergy';
if isfield(options,'DirichletDiag_Init')
    hmm.train.DirichletDiag = options.DirichletDiag_Init;
end
hmm = hmmhsinit(hmm);
if isfield(options,'DirichletDiag_Init')
    hmm.train.DirichletDiag = options.DirichletDiag;
end
[hmm,residuals] = obsinit(data,T,hmm,GammaInit);
data.C = NaN(size(data.C,1),hmm.K);
[hmm,Gamma] = hmmtrain(data,T,hmm,GammaInit,residuals);
end

function Gamma = findStandoutChains(T,hmm,baseline,I,G,nchains)
K = length(hmm.state);
hmm.state(K+1).W = baseline;
hmm.train.Pstructure = true(K+1); hmm.train.Pistructure = true(1,K+1);
hmm.train.stopcriterion = 'FreeEnergy';
fit = hmmspectramar([],[],hmm);
c = zeros(K,1);
ndim = size(fit.state(K+1).psd,2);
psd = []; for n = 1:ndim, psd = [psd; fit.state(K+1).psd(:,n,n)]; end
psd = psd ./ sum(psd);
W = zeros(length(baseline.Mu_W),K);
PSD = zeros(length(psd),K);
for k = 1:K
    psdk = []; for n = 1:ndim, psdk = [psdk; fit.state(k).psd(:,n,n)]; end
    psdk = psdk ./ sum(psdk);
    c(k) = corr(psdk,psd);
    W(:,k) = hmm.state(k).W.Mu_W;
    PSD(:,k) = psdk;
end
[~,jj] = min(c);
while length(jj) < nchains
   for k = 1:K
      c(k) = max(c(k),corr(PSD(:,k),PSD(:,jj(end))));
   end
   [~,j] = min(c); jj = [jj j];
end
Gamma = zeros(sum(T),nchains);
for k = 1:nchains
   Gamma(I(jj(k),1):I(jj(k),2),k) = G(:,jj(k));
end
end

%
% function Gamma = estimateGamma(data,T,W,Wbaseline,options)
% orders = formorders(options.order,options.orderoffset,options.timelag,options.exptimelag);
% [XX,Y] = formautoregr(data.X,T,orders,orders(end),1);
% K = size(W,2);
% % r = zeros(size(Y,1),K+1);
% % for k = 1:K
% %     r(:,k) = (XX * W(:,k) - Y).^2;
% % end
% % r(:,K+1) = (XX * Wbaseline - Y).^2;
% ehmm = struct('train',struct());
% ehmm.K = options.K;
% ehmm.train = options;
% ehmm = hmmhsinit(ehmm,[],T);
% for k = 1:K
%     ehmm.state(k).W.Mu_W = W(:,k);
% end
% ehmm.state(K+1).W.Mu_W = Wbaseline;
% ehmm.Omega = struct('Gam_rate',1,'Gam_shape',1);
% np = size(W,1); ndim = 1;
% for n = 1:ndim
%     ehmm.state_shared(n).Mu_W = zeros((K+1)*np,1);
% end
% for k = 1:K+1
%     ind = (k-1)*np + (1:np);
%     for n = 1:ndim
%         ehmm.state_shared(n).Mu_W(ind) = ehmm.state(k).W.Mu_W;
%     end
% end
% Gamma = hsinference(data,T,ehmm,Y,options,XX,zeros(sum(T)-length(T)*options.order,K));
% end
%
%

author: OHBA-analysis

repo: HMM-MAR


text:
function plot_rocch_det(plot_obj,plot_args,legend_string)
% Plots a DET curve using the ROCCH.
% Inputs:
%   plot_args: A cell array of arguments to be passed to plot that control
%     the appearance of the curve. See Matlab's help on 'plot' for information.
%   legend_string: Optional. A string to describe this curve in the legend.

if ischar(plot_args)
    plot_args = {plot_args};
end

pfa_min = plot_obj.pfa_limits(1);
pfa_max = plot_obj.pfa_limits(2);
pmiss_min = plot_obj.pmiss_limits(1);
pmiss_max = plot_obj.pmiss_limits(2);

figure(plot_obj.fh);
dps = 100; %dots per segment
[x,y] = rocchdet(plot_obj.tar,plot_obj.non,[],pfa_min,pfa_max,pmiss_min,pmiss_max,dps);
assert(iscell(plot_args))
lh = plot(x,y,plot_args{:});

if exist('legend_string','var') && ~isempty(legend_string)
    assert(ischar(legend_string))
    plot_obj.add_legend_entry(lh,legend_string,true);
end

end

author: nesl


text:
% The COBRAToolbox: testMergeTwoModels.m
%
% Purpose:
%     - testMergeTwoModels tests the mergeTwoModels function for
%     applicability to multiple different scenarios.
%
% Authors:
%     - Thomas Pfau 2018

% We will create 2 toy models
%model1
model1 = createModel();
model1 = addMultipleMetabolites(model1,{'A[c]','B[c]','C[c]','D[c]','E[c]'},'metKEGGID',{'C1','C2','C3','C4','C5'});
model1 = addGenes(model1,{'G1','G2','G3'},'geneNames',{'Gene1','Gene2','Gene3'});
model1 = addMultipleReactions(model1,{'R1','R2','R3'},model1.mets,rand(5,3),'grRules',{'G1','G2 and G3',''});

% Model2
model2 = createModel();
model2 = addMultipleMetabolites(model2,{'A2[c]','B2[c]','C2[c]','D2[c]','E2[c]'},'metKEGGID',{'C1','C2','C3','C4','C5'});
model2 = addGenes(model2,{'G21','G22','G23'},'geneNames',{'Gene1a','Gene2a','Gene3a'});
model2 = addMultipleReactions(model2,{'R21','R22','R23'},model2.mets,rand(5,3),'grRules',{'G21','G22 and G23',''});

%join the models (first, with genes)
modelJoint = mergeTwoModels(model1,model2);
%New S is of size 10 x 6
assert(size(modelJoint.S,1) == 10)
assert(size(modelJoint.S,2) == 6)
%Test, that the reactions are the same.
model2rxn = printRxnFormula(model2,'rxnAbbrList',model2.rxns(1),'printFlag',false);
modelJointRxn = printRxnFormula(modelJoint,'rxnAbbrList',model2.rxns(1),'printFlag',false);
assert(strcmp(model2rxn{1},modelJointRxn{1}));
model1rxn = printRxnFormula(model1,'rxnAbbrList',model1.rxns(2),'printFlag',false);
modelJointRxn = printRxnFormula(modelJoint,'rxnAbbrList',model1.rxns(2),'printFlag',false);
assert(strcmp(model1rxn{1},modelJointRxn{1}));

%Check, that the rules are correctly updated.
ruleR22 = modelJoint.rules{ismember(modelJoint.rxns,'R22')};
genePos = find(ismember(modelJoint.genes,{'G22','G23'}));
rule = strjoin(cellfun(@(x) ['x(' num2str(x) ')'], num2cell(genePos),'Uniform',0),' & ');
fp = FormulaParser();
modelRule = fp.parseFormula(ruleR22);
shouldBeRule = fp.parseFormula(rule);
assert(modelRule.isequal(shouldBeRule))

%Now, lets change G22 in model2 to G2 and introduce a common reaction
model2 = changeGeneAssociation(model2,'R22','G1 and G2');
model2 = addReaction(model2,'Rcommon','A[c] + B[c] -> C[c]');
model1 = addReaction(model1,'Rcommon','A[c] + B[c] -> C[c]');
model2.geneNames(end-1) = {'GeneFromModel2'};

%Assert that Model2 overrides model 1
modelJoint = mergeTwoModels(model1,model2);
assert(size(modelJoint.S,1) == 10)
assert(size(modelJoint.S,2) == 7)
geneWithName = model2.genes(end-1);
m2pos = ismember(model2.genes,geneWithName);
m1pos = ismember(model1.genes,geneWithName);
mjointPos = ismember(modelJoint.genes,geneWithName);
assert(strcmp(modelJoint.geneNames{mjointPos}, model1.geneNames{m1pos}))
model1rxn = printRxnFormula(model1,'rxnAbbrList','Rcommon','printFlag',false);
modelJointRxn = printRxnFormula(modelJoint,'rxnAbbrList','Rcommon','printFlag',false);
assert(strcmp(model1rxn{1},modelJointRxn{1}));

%Now also check that the objective is set correctly
model2.c(1) = 1;
model1.c(1) = 1;
modelJoint = mergeTwoModels(model1,model2,2);
assert(strcmp(modelJoint.rxns{find(modelJoint.c)},model2.rxns{1}));
modelJoint = mergeTwoModels(model1,model2,1);
assert(strcmp(modelJoint.rxns{find(modelJoint.c)},model1.rxns{1}));

%Finally, check that the merger is ok without merging genes
modelJoint = mergeTwoModels(model1,model2,2,false);
assert(~isfield(modelJoint,'geneNames'));
assert(isempty(modelJoint.genes));

%Test appropriate error if there are duplicate ids with distinct
%stoichiometries:
model2 = addReaction(model2,'Rcommon','A[c] -> C[c]');
assert(verifyCobraFunctionError('mergeTwoModels','outputArgCount',1,'inputs',{model1,model2},...
                         'testMessage','The following reactions were present in both models but had distinct stoichiometries:\nRcommon'));


text:
function program_02 ( )

%*****************************************************************************80
%
%% PROGRAM_02 demonstrates point and triangle orientation.
%
%  Discussion:
%
%    The program
%    * reads a triangle T (defined by three points),
%    * determines the orientation of the triangle;
%    * computes and prints the length of the edges;
%    * reads a point P
%    * computes the signed distance from P to each line
%      (not the line segment!)
%    * reports whether the point is INSIDE, ON or OUTSIDE the triangle.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 February 2007
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'PROGRAM_02 - Point/Triangle Orientation\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Define a triangle T:\n' );

  t_v1 = input ( '  Enter [ T.v1.x, T.v1.y]: ' );
  t_v2 = input ( '  Enter [ T.v2.x, T.v2.y]: ' );
  t_v3 = input ( '  Enter [ T.v3.x, T.v3.y]: ' );
%
%  Compute the edges.
%
  t_e1 = t_v2 - t_v1;
  t_e2 = t_v3 - t_v2;
  t_e3 = t_v1 - t_v3;
%
%  Compute the unit normal vectors to each edge.
%  MATLAB's NORM function returns the square root of the sum
%  of the squares of the entries of a vector.
%
  t_e1_nv = [ -t_e1(2), t_e1(1) ] / norm ( t_e1 );
  t_e2_nv = [ -t_e2(2), t_e2(1) ] / norm ( t_e2 );
  t_e3_nv = [ -t_e3(2), t_e3(1) ] / norm ( t_e3 );
%
%  Orientation test.
%  The signed distance of V3 from the line from V1 to V2 must be positive.
%
  test = t_e1_nv * ( t_v3 - t_v1 )';

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Orientation test value = %f\n', test );

  if ( test < 0.0 )
    fprintf ( 1, '  Error!  The triangle is improperly oriented.\n' );
    return
  elseif ( test == 0.0 )
    fprintf ( 1, '  Error!  The triangle is degenerate!\n' );
  else
    fprintf ( 1, '  The triangle is properly oriented.\n' );
  end
%
%  Edge lengths.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Edge1 = v2-v1, length = %f\n', norm ( t_e1 ) );
  fprintf ( 1, '  Edge2 = v3-v2, length = %f\n', norm ( t_e2 ) );
  fprintf ( 1, '  Edge3 = v1-v3, length = %f\n', norm ( t_e3 ) );
%
%  Check various points.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Now we see whether a point is in the triangle.\n' );
  fprintf ( 1, '\n' );

  while ( 1 )

    p = [];
    fprintf ( 1, '\n' );
    p = input ( '  Enter a point [ P.x, P.y], or RETURN to quit: ' );

    if ( isempty ( p ) )
      break
    end

%  Compute the signed distance from the point to the line that
%  includes each edge.
%
    p_e1_dist = t_e1_nv * ( p - t_v1 )';
    p_e2_dist = t_e2_nv * ( p - t_v2 )';
    p_e3_dist = t_e3_nv * ( p - t_v3 )';

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Distance to line through edge 1 = %f\n', p_e1_dist );
    fprintf ( 1, '  Distance to line through edge 2 = %f\n', p_e2_dist );
    fprintf ( 1, '  Distance to line through edge 3 = %f\n', p_e3_dist );

    fprintf ( 1, '\n' );
    if ( p_e1_dist < 0.0 | p_e2_dist < 0.0 | p_e3_dist < 0.0 )
      fprintf ( 1, '  The point is OUTSIDE the triangle\n' );
    elseif ( p_e1_dist == 0.0 | p_e2_dist == 0.0 | p_e3_dist == 0.0 )
      fprintf ( 1, '  The point is ON the triangle\n' );
    else
      fprintf ( 1, '  The point is INSIDE the triangle.\n' );
    end

  end

  fprintf ( 1, '\n' );
  fprintf ( 1, 'PROGRAM_02\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%-------------------------------------------------------------------------------------------------------------------%
%
% IB2d is an Immersed Boundary Code (IB) for solving fully coupled non-linear
% 	fluid-structure interaction models. This version of the code is based off of
%	Peskin's Immersed Boundary Method Paper in Acta Numerica, 2002.
%
% Author: Nicholas A. Battista
% Email:  battistn@tcnj.edu
% Date Modified: April 2021
% Current Institution: TCNJ
% IB2d Date Created: May 27th, 2015
% Institution Created: UNC-CH
%
% This code is capable of creating Lagrangian Structures using:
% 	1. Springs
% 	2. Beams (torsional springs or non-invariant beams)
% 	3. Target Points
%	4. Muscle-Model (combined Force-Length-Velocity model, "HIll+(Length-Tension)")
%
% One is able to update those Lagrangian Structure parameters, e.g., spring constants, resting lengths, etc
%
% There are a number of built in Examples, mostly used for teaching purposes.
%
% If you would like us to add a specific muscle model, please let Nick (battistn@tcnj.edu) know.
%
%--------------------------------------------------------------------------------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION: main2d is the function that gets called to run the code. It
%           itself, reads in parameters from the input2d file, and passes
%           them to the IBM_Driver function to run the simulation
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function main2d()

% This is the "main" file, which gets called to initialized the Immersed Boundary
% Simulation. It reads in all the parameters from "input2d", and sends them
% off to the "IBM_Driver.m" function to actual perform the simulation

%
% Path Reference to where Driving code is found %
%
warning('off','all');
addpath('../IBM_Blackbox/','../../IBM_Blackbox/','../../../IBM_Blackbox/','../../../../IBM_Blackbox/');

%
% THROW ERROR TO CORRECT PATH IF DRIVER IS NOT FOUND
%
assert( exist( 'IBM_Driver.m', 'file' ) == 2, 'IBM_Driver.m not found -> Please check path to IBM_Blackbox in main2d.m!' );

%
% READ-IN INPUT PARAMETERS %
%
[Fluid_Params, Grid_Params, Time_Params, Lag_Struct_Params, Output_Params, Lag_Name_Params,Con_Params] = please_Initialize_Simulation();

%
%-%-%-% DO THE IMMERSED BOUNDARY SOLVE!!!!!!!! %-%-%-%
%
[X, Y, U, V, xLags, yLags] = IBM_Driver(Fluid_Params,Grid_Params,Time_Params,Lag_Struct_Params,Output_Params,Lag_Name_Params,Con_Params);

%
% Print simulation has completed.
%
fprintf('\n\n');
fprintf(' |****** IMMERSED BOUNDARY SIMULATION HAS FINISHED! ******|\n\n')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Function to read in input files from "input2d" -> renames all
% quantities appropriately, just as they are in input file
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [params,struct_name] = give_Me_input2d_Parameters()

filename= 'input2d';  %Name of file to read in

fileID = fopen(filename); %Opens file for 'textscan' function
    % Read in the file, use 'CollectOutput' to gather all similar data together
    % and 'CommentStyle' to to end and be able to skip lines in file.
    C1 = textscan(fileID,'%s %s %f','CollectOutput',1,'CommentStyle','%');
    C2 = textscan(fileID,'%s %s %s','CollectOutput',1,'CommentStyle','%');
fclose(fileID);

params = C1{2};

struct_name = C2{1,1};

author: nickabattista


text:
function MOVC = PQ_InitMOVC (Nchan, Np)
MOVC.MDiff.Mt1B = zeros (Nchan, Np);
MOVC.MDiff.Mt2B = zeros (Nchan, Np);
MOVC.MDiff.Wt   = zeros (Nchan, Np);

MOVC.NLoud.NL   = zeros (Nchan, Np);

MOVC.Loud.NRef  = zeros (Nchan, Np);
MOVC.Loud.NTest = zeros (Nchan, Np);

MOVC.BW.BWRef  = zeros (Nchan, Np);
MOVC.BW.BWTest = zeros (Nchan, Np);

MOVC.NMR.NMRavg = zeros (Nchan, Np);
MOVC.NMR.NMRmax = zeros (Nchan, Np);

MOVC.PD.Pc = zeros (1, Np);
MOVC.PD.Qc = zeros (1, Np);

MOVC.EHS.EHS = zeros (Nchan, Np);

author: stephencwelch

repo: Perceptual-Coding-In-Python


text:
%% Analyzing Neural Time Series Data
% Matlab code for Chapter 2
% Mike X Cohen
%
% This code accompanies the book, titled "Analyzing Neural Time Series Data"
% (MIT Press). Using the code without following the book may lead to confusion,
% incorrect data analyses, and misinterpretations of results.
% Mike X Cohen assumes no responsibility for inappropriate or incorrect use of this code.

%% Figure 2.1

load sampleEEGdata.mat

nTrials = 6; % modifiable

figure
data = zeros(nTrials,EEG.pnts);

% wavelet... more on this in Chapters 13 and 14
wavetime   = -1:1/EEG.srate:1;
n_conv     = length(wavetime)+EEG.pnts-1;
waveletfft = fft(exp(2*1i*pi*10.*wavetime) .* exp(-wavetime.^2./(2*(5/(2*pi*10))^2))/10,n_conv);
data10hz   = zeros(nTrials,EEG.pnts);

for triali=1:nTrials

    % create single trial "ERP"
    data(triali,:) = .5*sin(2*pi*6.*EEG.times/1000 + 2*pi*triali/nTrials-pi) + randn(1,EEG.pnts)/6;
    % add non-phase-locked stimulus potential (note distributed phases in sine wave)
    data(triali,260:360) = data(triali,260:360) + sin(2*pi*10.*EEG.times(260:360)/1000 + 2*pi*triali/nTrials-pi) + randn(1,101)/5;

    % plot data from this trial
    subplot(nTrials,3,(triali-1)*3+1)
    plot(EEG.times,data(triali,:))
    set(gca,'xlim',[-250 850],'ylim',[-2.2 2.2])

    % plot ERP from trial 1 to current
    subplot(nTrials,3,(triali-1)*3+2)
    plot(EEG.times,mean(data(1:triali,:),1))
    set(gca,'xlim',[-250 850],'ylim',[-2.2 2.2])

    % convolve with 10 Hz wavelet (more on convolution in a few chapters...)
    convolution_result_fft = ifft(waveletfft.*fft(data(triali,:),n_conv)) * sqrt(5/(2*pi*10));
    convolution_result_fft = convolution_result_fft(floor(length(wavetime)/2)+1:end-floor(length(wavetime)/2));
    data10hz(triali,:) = abs(convolution_result_fft).^2;

    % plot 10 Hz power
    subplot(nTrials,3,(triali-1)*3+3)
    plot(EEG.times,mean(data10hz(1:triali,:),1))
    set(gca,'xlim',[-250 850],'ylim',[-.1 .8])
end

%% Figure 2.2
% (This code involves performing convolution with a complex Morlet wavelet,
% which you will learn about in Chapters 10-13.)

srate=1000;

time=(0:1/srate:10);

DCoffset=-.5;

% create multi-frequency signal
a = sin(2*pi*10.*time);             % part 1 of signal (high frequency)
b = .1*sin(2*pi*.3*time)+DCoffset;  % part 2 of signal (low frequency)

data = a.*b; % combined signal
data = data + (2*sin(2*pi*3*time) .* sin(2*pi*.07*time)*.1+DCoffset);

% morlet wavelet convolution (more on this in later chapters)
num_frex = 40;
min_freq =  2;
max_freq = 20;

Ldata  = length(data);
Ltapr  = length(data);
Lconv1 = Ldata+Ltapr-1;
Lconv  = pow2(nextpow2(Lconv1));

frex=logspace(log10(min_freq),log10(max_freq),num_frex);

% initialize
tf=zeros(num_frex,length(data));
datspctra = fft(data,Lconv);

s=4./(2*pi.*frex);
t=-((length(data)-1)/2)/srate:1/srate:((length(data)-2)/2)/srate+1/srate;

for fi=1:length(frex)

    wavelet=exp(2*1i*pi*frex(fi).*t).*exp(-t.^2./(2*s(fi)^2));

    m = ifft(datspctra.*fft(wavelet,Lconv),Lconv);
    m = m(1:Lconv1);
    m = m(floor((Ltapr-1)/2):end-1-ceil((Ltapr-1)/2));

    tf(fi,:) = abs(m).^2;
end

figure

subplot(221)
plot(a)
set(gca,'xlim',[1 8]*1000,'ylim',[-1 1],'xtick',0:1000:10000,'xticklabel',0:10);
title('10 Hz signal, DC=0')

subplot(222)
plot(b)
set(gca,'xlim',[1 8]*1000,'ylim',[-1 1],'xtick',0:1000:10000,'xticklabel',0:10);
title([ '.3 Hz signal, DC=' num2str(DCoffset) ])

subplot(223)
plot(data)
set(gca,'xlim',[1 8]*1000,'ylim',[-1 1],'xtick',0:1000:10000,'xticklabel',0:10);
title('Time-domain signal')

subplot(224)
imagesc(1:length(data),[],tf);
set(gca,'xlim',[1 8]*1000,'ydir','normal','ytick',1:8:num_frex,'yticklabel',round(frex(1:8:end)),'xtick',0:1000:10000,'xticklabel',0:10)
title('Time-frequency representation')

%% Figure 2.3

chan2plot = 'pz'; % you can pick any electrode (type {EEG.chanlocs.labels} for all electrodes)

% compute ERP (time-domain trial average from selected electrode)
erp = squeeze(mean(EEG.data(strcmpi(chan2plot,{EEG.chanlocs.labels}),:,:),3));

% low-pass filter data (uses signal processing toolbox; you'll learn about
% how filtering works in chapter 14. If you don't have the signal processing
% toolbox, just comment out the next eight lines; they are not necessary.)
nyquist       = EEG.srate/2;
filter_cutoff = 40;  % Hz
trans_width   = 0.1; % transition width, in fraction of 1

ffrequencies  = [ 0 filter_cutoff filter_cutoff*(1+trans_width) nyquist ]/nyquist;
idealresponse = [ 1 1 0 0 ];
filterweights = firls(100,ffrequencies,idealresponse);
filtered_erp  = filtfilt(filterweights,1,double(erp));

figure
% plot ERP
plot(EEG.times,filtered_erp,'k.-')

% now down-sample and plot
times2plot = dsearchn(EEG.times',(-200:40:1000)');
hold on
plot(EEG.times(1:5:end),filtered_erp(1:5:end),'mo-')

set(gca,'xlim',[-200 1000],'ydir','r')
xlabel('Time (ms)'), ylabel('Voltage (\muV)')
title([ 'ERP from electrode ' chan2plot ])
legend({'256 Hz';'50 Hz'})

%%

author: mikexcohen

repo: AnalyzingNeuralTimeSeries


text:
function [ d ] = edist( x , y )
%edist euclidean distance between two vectors

d = sqrt( sum( (x-y).^2,2 ) );

author: epfl-lasa


text:
function [reac, exMets, micRea, binOrg, patOrg, reacPat, reacNumb, reacSet, reacTab, reacAbun, reacNumber] = getMappingInfo(modPath, organisms, abunFilePath)
% This function automatically extracts information from strain abundances in
% different individuals and combines this information into different tables.
%
% USAGE:
%
%    [reac, exMets, micRea, binOrg, patOrg, reacPat, reacNumb, reacSet, reacTab, reacAbun, reacNumber] = getMappingInfo(modPath, organisms, abunFilePath, patNumb)
%
% INPUTS:
%   organisms:         nx1 cell array cell array with names of organisms in the study
%   modPath:           char with path of directory where models are stored
%   abunFilePath:      char with path and name of file from which to retrieve abundance information
%   patNumb:           number of individuals in the study
%
% OUTPUTS:
%   reac:              cell array with all the unique set of reactions
%                      contained in the models
%   exMets:            cell array with all unique extracellular metabolites
%                      contained in the models
%   micRea:            binary matrix assessing presence of set of unique
%                      reactions for each of the microbes
%   binOrg:            binary matrix assessing presence of specific strains in
%                      different individuals
%   reacPat:           matrix with number of reactions per individual
%                      (organism resolved)
%   reacSet:           matrix with names of reactions of each individual
%   reacTab:           char with names of individuals in the study
%   reacAbun:          binary matrix with presence/absence of reaction per
%                      individual: to compare different individuals
%   reacNumber:        number of unique reactions of each individual
%
% .. Author: Federico Baldini 2017-2018

reac = {}; % array with unique set of all the reactions present in the models
exMets = {}; % array with unique set of all the extracellular metabolites present in the models

models = {};
parfor i = 1:length(organisms) % find the unique set of all the reactions contained in the models
    model =readCbModel([modPath filesep organisms{i,1} '.mat']);
    models{i, 1} = model;
end

for i = 1:length(organisms) % find the unique set of all the reactions contained in the models
    smd = models{i, 1};
    reac = union(reac,smd.rxns);
    findmets = smd.mets(find(contains(smd.mets,'[e]')));
    exMets = union(exMets,findmets);
end

% Code to detect reaction presence in each model and create inary matrix
% assessing presence of set of unique reactions for each of the microbes

micRea = zeros(length(models), length(reac));

mdlt = length(models);
parfor i = 1:mdlt
    model = models{i, 1};
    micRea(i,:) = ismember(reac,model.rxns)
end

% creating binary table for abundances
[abundance] = readtable(abunFilePath);

[binary] = abundance;
s = size(binary);
s = s(1, 2);
binary = binary(:, 2:s);  % removing model info and others
binary{:,:} = double(binary{:,:}~=0);
binOrg = binary;

% Compute number of reactions per individual (species resolved)

reacPat = zeros(length(table2cell(binOrg(:, 1))), length(table2cell(binOrg(1, :))));
cleantabc = table2cell(binOrg);
for j = 1:length(table2cell(binOrg(1, :)))
    for i = 1:length(table2cell(binOrg(:, 1)))
        temp = cell2mat(cleantabc(i, j));
        if temp == 1
            reacPat(i, j) = sum(micRea(i, :));
        end
    end
end

% Computing overall (non unique) number of reactions per individual

totReac = [];
for i = 1:length(reacPat(1, :))
    totReac(i, 1) = sum(reacPat(:, i));
end

% Computing number of reactions per organism

reacNumb = [];
for i = 1:length(micRea(:, 1))
    reacNumb(i, 1) = sum(micRea(i, :));
end

% Computing number of organism per individual

patOrg = [];
for i = 1:length(cleantabc(1, :))
    patOrg(i, 1) = sum(table2array(binOrg(:, i)));
end
patOrg = patOrg';

% number and names of UNIQUE reactions per patient
% Briefly, the nonunique reaction content of each individual (reacvec) is
% retrieved from the binary matrix of microbial presence (binOrg) and each of
% the related models. The same is also done using the abundance table for
% establishing reactions coefficients (abunvec) on the base of microbial presence.
% We end up with two nonunique matrices: (completeset) containing reaction content
% for each individual and (completeabunnorm).  Finally, for each individual using
% a list of unique reactions in all the study (reac) all the matches are found and
% the correspondent abundances summed up (numbtab).

reacSet = {};
reacNumber = [];

for j = 1: length(table2cell(binOrg(1, :)))
    abunvec = [];
    reacvec = [];
    for i = 1: length(table2cell(binOrg(:, 1)))
        if (cell2mat(table2cell(binOrg(i, j)))) == 1
            model = models{i, 1};
            reacvec = vertcat(reacvec, model.rxns);
            abunvec((length(abunvec) + 1): ((length(abunvec)) + length(model.rxns))) = table2array(abundance(i, j + 1));
        end
    end

    completeset(1:length(reacvec), j) = reacvec;  % to get lists of reactions per each individual
    completeabunorm(1:length(reacvec), j) = abunvec';  % matrix with abundance coefficients for normalization
    reacSet(1:length(unique(reacvec)), j) = unique(reacvec);  % to get lists of reactions per each individual
    reacNumber(j) = length(unique(reacvec));
end

reacLng = length(reac);

parfor j = 2:size(abundance,2)
    for i = 1:reacLng
        indrxn = find(strcmp(reac(i, 1), completeset(:, j-1)));
        numbtab(i, j-1) = sum(completeabunorm(indrxn,j-1));
    end
end

reacAbun = [reac, num2cell(numbtab)];

% presence/absence of reaction per patient: to compare different patients
% with pCoA
reacTab = zeros(length(reac), length(reacPat(1, :)));

parfor k = 1: length(reacPat(1, :))
    match = zeros(1,length(reac));
        for i = 1: length(reac)
            for j = 1: length(reacSet(:, 1))
                if strcmp(reac(i), reacSet(j, k)) == 1  % the 2 reactions are equal
                    match(i) = 1;
                end
            end
        end
    reacTab(:, k) = match
end
end


text:
function test_suite = test_svi_classific

%   Run specific demo, save values and compare the results to the expected.
%   Works for both xUnit Test Framework package by Steve Eddins and for
%   the built-in Unit Testing Framework (as of Matlab version 2013b).
%
%   See also
%     TEST_ALL, DEMO_SVI_CLASSIFIC
%
% Copyright (c) 2011-2012 Ville Tolvanen
% Copyright (c) 2014 Tuomas Sivula

% This software is distributed under the GNU General Public
% License (version 3 or later); please refer to the file
% License.txt, included with the software, for details.

  % Check which package to use
  if exist('initTestSuite', 'file')
    initTestSuite_path = which('initTestSuite');
  else
    initTestSuite_path = '';
  end
  if ~isempty(initTestSuite_path) && ...
     exist([initTestSuite_path(1:end-15) 'runtests'], 'file')
    % xUnit package
    initTestSuite;
  else
    % Built-in package
    % Use all functions except the @setup
    tests = localfunctions;
    tests = tests(~cellfun(@(x)strcmp(func2str(x),'setup'),tests));
    test_suite = functiontests(tests);
  end
end

% -------------
%     Tests
% -------------

function testRunDemo(testCase)
  % Run the correspondin demo and save the values. Note this test has to
  % be run at lest once before the other test may succeed.
  rundemo(getName(), {'lpyt', {'w', @(x)gp_pak(x), 'gp'} })
end

function testPrediction(testCase)
  verifyVarsEqual(testCase, getName(), {'lpyt'}, ...
    'RelTolElement', 0.05, 'RelTolRange', 0.01)
end

function testParameters(testCase)
  verifyVarsEqual(testCase, getName(), {'w'}, ...
    'RelTolElement', 0.05, 'RelTolRange', 0.01)
end

% ------------------------
%     Helper functions
% ------------------------

function testCase = setup
  % Helper function to suply empty array into variable testCase as an
  % argument for each test function, if using xUnit package. Not to be
  % used with built-in test framework.
  testCase = [];
end

function name = getName
  % Helperfunction that returns the name of the demo, e.g. 'binomial1'.
  name = mfilename;
  name = name(6:end);
end

author: gpstuff-dev

repo: gpstuff

save_path: github-repos/MATLAB/gpstuff-dev-gpstuff


text:
function dUpsilon = lfmavGradientUpsilonMatrix(gamma, sigma2, t1, ...
    t2, mode, upsilon)

% LFMAVGRADIENTUPSILONMATRIX Gradient upsilon matrix accel. vel.
% FORMAT
% DESC computes the gradient of a portion of the LFMAV kernel.
% ARG gamma : Gamma value for system.
% ARG sigma2 : length scale of latent process.
% ARG t1 : first time input (number of time points x 1).
% ARG t2 : second time input (number of time points x 1).
% ARG upsilon : precomputation of the upsilon matrix.
% ARG mode : operation mode, according to the derivative (mode 0,
% derivative wrt t1, mode 1 derivative wrt t2)
% RETURN upsilon : result of this subcomponent of the kernel for the given values.
%
% COPYRIGHT : Mauricio Alvarez, 2010
%
% SEEALSO : lfmavComputeUpsilonMatrix.m

% KERN

sigma = sqrt(sigma2);

if nargin<6
    upsilon = lfmvpComputeUpsilonMatrix(gamma, sigma2, t1, t2, 1 - mode);
    if nargin <5
        mode =0;
    end
end

dUpsi = lfmvpGradientUpsilonMatrix(gamma, sigma2, t1, t2, 1 - mode);
gridt1 = repmat(t1, 1, length(t2));
gridt2 = repmat(t2', length(t1), 1);
timeGrid = gridt1 - gridt2;

if mode ==0
    dUpsilon = 2*gamma*upsilon + (gamma^2)*dUpsi - (4/(sqrt(pi)*sigma^3))* ...
        timeGrid.*exp(-(timeGrid.^2)./sigma2);
else
    dUpsilon = 2*gamma*upsilon + (gamma^2)*dUpsi + (4/(sqrt(pi)*sigma^3))* ...
        timeGrid.*exp(-(timeGrid.^2)./sigma2) - (2/(sqrt(pi)*sigma))*...
        (exp(-gamma*t1).*(1-gamma*t1))*((gamma - 2*t2/sigma2).*exp(-(t2.^2)/sigma2)).' ...
        - (2*gamma/(sqrt(pi)*sigma))*exp(-gamma*t1)*(exp(-(t2.^2)/sigma2)).';
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
%% Render Random Scenes
%
% This script will generate numerous random scenes and save the results in
% the Output directory. This is useful to sample a large number of scene.
% Note that each scene will be saved as an image with a date stamp *and*
% the random number generator seed used to generate the seed. Passing this
% number to |rng| before running |example_scene| will result in the scene
% being recreated exactly. This allows a user to examine numerous scenes,
% select a scene of interest, recreate it, explore it, and potentially
% export it for whatever purpose. In other words, the seed number is all
% that's necessary to completely regenerate a scene. For example, if an
% image is named |scene_2012-12-13-18-38-28_seed_59150.png|, then the
% following completely recreates the scene.
%
% >> rng(59150);
% >> example_scene;
%
% Tucker McClure
% Copyright 2012, The MathWorks, Inc.

%% Options
% Number of scenes to create.
n_images = 50;

%% Initialize the Figure
fprintf('Generating %d scenes...\n', n_images);
tic();

% Create or clear a figure for the rendering.
figure(1);
clf();
set(1, 'PaperPositionMode',     'auto', ...
       'WindowButtonDownFcn',   [], ...
       'WindowButtonUpFcn',     [], ...
       'WindowButtonMotionFcn', [], ...
       'WindowScrollWheelFcn',  []);

% Choose the next random number generator seed.
rng_seed = mod(floor(1e8*now()), 2^32);
rng(rng_seed);

%%
% Add an Output directory if one doesn't exist.
if ~exist('Output', 'dir')
    mkdir('Output');
end

%% Land and Sea

% Create the terrain height map.
[~, ~, ~, hm, xm, ym] = generate_terrain(7, 513, 0, 0.1);

% Generate appropriate colors.
cm = generate_terrain_colors(hm);

% Flatten the oceans.
hmp = max(hm, 0);

% Draw the land and calculate its normal vectors.
h_land = patch(surf2patch(xm, ym, hmp, cm));
[nx, ny, nz] = surfnorm(hmp);
land_normals = [nx(:), ny(:), nz(:)];

% Set it's material properties for interpolated colors and appropriate
% lighting.
set(h_land, 'VertexNormals',    land_normals, ...
            'DiffuseStrength',  0.8, ...      % Reacts to light direction
            'SpecularStrength', 0, ...        % Not shiny
            'AmbientStrength',  0.3, ...      % Reacts to ambient light
            'BackFaceLighting', 'unlit');     % Don't illuminate reverse

% Add a black backdrop beneath the land. Sometimes a vertex seems to miss
% its position slightly, and sky colors creep through, and that's weird.
patch('Faces',           [1 2 3 4], ...
      'Vertices',        [-1 -1 -0.01; ...
                           1 -1 -0.01; ...
                           1  1 -0.01; ...
                          -1  1 -0.01], ...
      'FaceVertexCData', 0.25*ones(4, 3));

%% Sky

% Draw a random time of day between sunrise and sunset. Get the
% corresponding light color. The sky is always the color of the sun at noon
% (and is then affected by the sun color at the current time).
current_time = 0.24 + 0.52 * rand();
sun_color    = sun_tones(current_time);
sky_color    = sun_tones(0.5);

% Create the sky patch by scaling a sphere. Note that the nothing in the
% scene can be rendered outside of [-100, 100] on any axis due to a
% documented rendering bug. Therefore, the sphere will be scaleld up to
% 99, which is plenty far away since the terrain is limited to [-1, 1].
[xs, ys, zs] = sphere(16);
sky_scale = 99;
sky_patch = surf2patch(sky_scale*xs, sky_scale*ys, sky_scale*zs, ...
                       repmat(reshape(sky_color, [1 1 3]), [17 17 1]));
h_sky = patch(sky_patch);

% Set appropriate lighting options for the sky.
set(h_sky, 'DiffuseStrength',  0.3, ...
           'SpecularStrength', 0, ...
           'AmbientStrength',  1, ...
           'BackFaceLighting', 'unlit');

% Vertex normals are the opposite of what I expect. Reverse them.
set(h_sky,  'VertexNormals', -get(h_sky,  'VertexNormals'));

%% Sun

% Create a light for the sun.
h_light = lightangle(90, 360*(current_time - 0.25));

% Set the light's color.
set(h_light, 'Color',             sun_color);

% Set the ambient color used in the scene.
set(gca(),   'AmbientLightColor', sun_color);

% Use decent lighting.
lighting gouraud;

%% Axes and Global Settings

% Set axes options.
camera_target   = [0 0 mean(hmp(:)) + 0.5*std(hmp(:))];
camera_position = camera_target + [1.15 0 0.5];
set(gca, 'DataAspectRatio', [1 1 1], ...
         'Visible',         'off', ...
         'Projection',      'Perspective', ...
         'Position',        [0 0 1 1], ...
         'CameraTarget',    camera_target, ...
         'CameraViewAngle', 45, ...
         'CameraUpVector',  [0 0 1], ...
         'CameraPosition',  camera_position, ...
         'XLim',            [-100 100], ...
         'YLim',            [-100 100], ...
         'ZLim',            [-100 100]);
camorbit(360*rand(), 0);

% Patches should have no edges and interpolated face colors.
shading interp;

% Force the drawing.
drawnow();

%% Loop, Updating Image Each Time
image_number = 0;
while true

    % Increase image count.
    image_number = image_number + 1;

    % Force a drawing.
    drawnow();

    % Capture the image.
    image_name = sprintf('scene_%s_seed_%d.png', ...
                         datestr(now(), 'yyyy-mm-dd-HH-MM-SS'), ...
                         rng_seed);
    print('-dpng', ['Output' filesep image_name]);

    % If we've generated enough images, stop.
    if image_number == n_images
        break;
    end

    % Choose the next random number generator seed.
    rng_seed = mod(floor(1e8*now()), 2^32);
    rng(rng_seed);

    % Generate new terrain.
    [~, ~, ~, hm, xm, ym] = generate_terrain(7, 513, 0, 0.1);
    cm = generate_terrain_colors(hm);
    hmp = max(hm, 0);
    current_time = 0.24 + 0.52 * rand();
    [nx, ny, nz] = surfnorm(hmp);
    land_normals = [nx(:), ny(:), nz(:)];

    % Update the patches, lights, and camera.
    land_patch = surf2patch(xm, ym, hmp, cm);
    set(h_land, 'Vertices',        land_patch.vertices, ...
                'Faces',           land_patch.faces, ...
                'FaceVertexCData', land_patch.facevertexcdata, ...
                'VertexNormals',   land_normals);
    lightangle(h_light, 90, 360*(current_time - 0.25));
    sun_color = sun_tones(current_time);
    set(h_light, 'Color', sun_color);
    camera_target   = [0 0 mean(hmp(:)) + 0.5*std(hmp(:))];
    camera_position = camera_target + [1.15 0 0.5];
    set(gca(), 'AmbientLightColor', sun_color, ...
               'CameraTarget',      camera_target, ...
               'CameraPosition',    camera_position, ...
               'CameraUpVector',    [0 0 1]);
    camorbit(360*rand(), 0);

end

fprintf('Done.\n');
toc();


text:
% MAP_INTERPOLATE - Plots interpolated values over a map.
%
% Plots a smooth coloring over a map based on interpolation using values at
% some specific locations. It is possible to make several interpolated plots
% if the set of locations is identical.
%
% MAP_INTERPOLATE(C, Y, LONH, LATH, ...)
%
% where
%
% C    : 2 x N matrix of longitudes and latitudes
% Y    : N x K matrix of values
% LONH : vector defining the longitudinal grid points
% LATH : vector defining the latitudinal grid points
%
% Optional parameters:
%
% 'method'   : 'nn' is nearest neighbour interpolation
%              'rbf' is linear radial basis functions interpolation (default)
% 'layout'   : vector of the number of rows and columns of the subplot
%              layout (default is square layout)
% 'distfunc' : distance function to be used (default: 'haversine')

% Last modified 2010-06-11
% Copyright (c) Jaakko Luttinen (jaakko.luttinen@tkk.fi)

function hax = map_interpolate(C, Y, lonh, lath, varargin)

options = struct( ...
    'method',   'rbf', ...
    'layout',   [],   ...
    'distfunc', 'haversine');

% Check arguments
[options, errmsg] = argparse(options, varargin{:});
error(errmsg)

% Form a regular grid
[LONH,LATH] = meshgrid(lonh,lath);

% Evaluate distances for interpolation
Ch = [LONH(:),LATH(:)]';
D = dist_haversine(C, C);
Dh = dist_haversine(Ch, C);

% Settings for multiple plots
K = size(Y,2);
if K > 1 && ~isempty(options.layout)
  M = options.layout(1);
  N = options.layout(2);
else
  M = ceil(sqrt(K));
  N = ceil(K/M);
end
hax = zeros(K,1);

% Plot maps
for k=1:K

  hax(k) = subplot(M,N,k);

  % Interpolate
  yh = interpolate(D, Y(:,k), Dh, 'method', options.method);
  yh = reshape(yh, size(LONH));

  % Plot
  map_pcolor(LONH, LATH, yh);

end

if nargout < 1
  clear hax;
end

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


text:
% MatrixUser, a multi-dimensional matrix analysis software package
% https://sourceforge.net/projects/matrixuser/
%
% The MatrixUser is a matrix analysis software package developed under Matlab
% Graphical User Interface Developing Environment (GUIDE). It features
% functions that are designed and optimized for working with multi-dimensional
% matrix under Matlab. These functions typically includes functions for
% multi-dimensional matrix display, matrix (image stack) analysis and matrix
% processing.
%
% Author:
%   Fang Liu <leoliuf@gmail.com>
%   University of Wisconsin-Madison
%   Aug-30-2014

function MU_func3DRender(Temp,Event,handles)
handles = guidata(handles.MU_matrix_display);

MU_3D_Render(handles);

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function I = data_augmentation(I, K)

if K == 1
    return;
elseif K == 2 % flipped
    I = flipud(I);
    return;
elseif K == 3 % rotation 90
    I = rot90(I,1);
    return;
elseif K == 4 % rotation 90 & flipped
    I = rot90(I,1);
    I = flipud(I);
    return;
elseif K == 5 % rotation 180
    I = rot90(I,2);
    return;
elseif K == 6 % rotation 180 & flipped
    I = rot90(I,2);
    I = flipud(I);
    return;
elseif K == 7 % rotation 270
    I = rot90(I,3);
    return;
elseif K == 8 % rotation 270 & flipped
    I = rot90(I,3);
    I = flipud(I);
    return;
end

author: cszn

repo: FFDNet

save_path: github-repos/MATLAB/cszn-FFDNet