text:
%GETPREPROC Get datafile PREPROC field
%
%	   PREPROC = GETPREPROC(A)
%
% Retrieves the PREPROC field of the datafile A. This is a
% structure array with two fields:
% - preproc: a string with a command name
% - pars:    a cell array with parameters
%
%    [COMMAND,PARS]  = GETPREPROC(A,N)
%
% In this case just the command name and the parameter cell array of
% the N-th preprocessing command are returned.
%
% or just the name of the N-th file.
% If N larger than the number of stored commands, COMMAND and PARS
% will be empty.

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function roff = i4cvv_offset ( m, nr )

%*****************************************************************************80
%
%% I4CVV_OFFSET determines the row offsets of an I4CVV.
%
%  Discussion:
%
%    An I4CVV is a "vector of vectors" of I4's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows in the array.
%
%    Input, integer NR(M), the row sizes.
%
%    Output, integer ROFF(M+1), the row offsets.
%
  roff = zeros ( m + 1, 1 );

  roff(1) = 0;
  for i = 1 : m
    roff(i+1) = roff(i) + nr(i);
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function rgb = cortex_dark

% This returns a predefined color as [red green blue] values
%   red               = [255   0   0]/255;
%   green             = [  0 192   0]/255;
%   blue              = [  0   0 255]/255;
%   magenta           = [255 255   0]/255;
%   cyan              = [  0 255 255]/255;
%   yellow            = [255 255   0]/255;
%   white             = [255 255 255]/255;
%   black             = [  0   0   0]/255;
%
%   skull             = [140  85  85]/255
%   cortex            = [255 213 119]/255;
%   cortex_light      = [199 194 169]/255;
%   cortex_dark       = [100  97  85]/255;
%   skin              = [249 223 192]/255;
%   skin_light        = [249 223 192]/255;
%   skin_medium_light = [225 194 158]/255;
%   skin_medium       = [188 142 106]/255;
%   skin_medium_dark  = [155 102	65]/255;
%   skin_dark         = [ 91  71  61]/255;

rgb = [100 97 85]/255;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function varargout = process_extract_maxfreq( varargin )
% PROCESS_EXTRACT_MAXFREQ: Find the maximum value in time (returns the latency or the peak values).

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2016; Martin Cousineau, 2017

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Find maximum in frequency';
    sProcess.FileTag     = @GetFileTag;
    sProcess.Category    = 'File';
    sProcess.SubGroup    = 'Extract';
    sProcess.Index       = 355;
    sProcess.Description = '';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'timefreq'};
    sProcess.OutputTypes = {'timefreq'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 1;
    sProcess.isSeparator = 1;

    % Definition of the options
    % === SELECT: FREQUENCY RANGE
    sProcess.options.freqrange.Comment  = 'Frequency range: ';
    sProcess.options.freqrange.Type     = 'freqrange';
    sProcess.options.freqrange.Value    = [];
    % === METHOD
    sProcess.options.labelmethod.Comment = '
What to detect:';
    sProcess.options.labelmethod.Type    = 'label';
    sProcess.options.method.Comment = {'Maximum amplitude  (positive or negative peak)', 'Maximum value  (positive peak)', 'Minimum value  (negative peak)'; ...
                                       'absmax', 'max', 'min'};
    sProcess.options.method.Type    = 'radio_label';
    sProcess.options.method.Value   = 'absmax';
    % === OUTPUT
    sProcess.options.labelout.Comment = '
Value to save in the output file:';
    sProcess.options.labelout.Type    = 'label';
    sProcess.options.output.Comment = {'Peak amplitude  (for each signal separately)', 'Frequency of the peak  (for each signal separately)'; ...
                                       'amplitude', 'frequency'};
    sProcess.options.output.Type    = 'radio_label';
    sProcess.options.output.Value   = 'amplitude';
    % === OVERWRITE
    sProcess.options.overwrite.Comment = 'Overwrite input files';
    sProcess.options.overwrite.Type    = 'checkbox';
    sProcess.options.overwrite.Value   = 0;
    sProcess.options.overwrite.Group   = 'output';
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    % Preprocess values to detect the correct peaks
    switch (sProcess.options.method.Value)
        case 'absmax',  Comment = 'Find maximum amplitude: ';
        case 'max',     Comment = 'Find maximum value: ';
        case 'min',     Comment = 'Find minimum value: ';
    end
    % Freq indices
    if isfield(sProcess.options, 'freqrange') && isfield(sProcess.options.freqrange, 'Value') && iscell(sProcess.options.freqrange.Value) && (length(sProcess.options.freqrange.Value) == 3) && (length(sProcess.options.freqrange.Value{1}) == 2)
        FreqRange = sProcess.options.freqrange.Value{1};
        if (FreqRange(1) == FreqRange(2))
            Comment = [Comment, ' Invalid frequency selection'];
            return;
        else
            Comment = [Comment, ' ' num2str(FreqRange(1)) '-' num2str(FreqRange(2)) 'Hz'];
        end
    end
    % Output
    if isequal(sProcess.options.output.Value, 'frequency')
        Comment = [Comment, ', frequency'];
    end
end

%% ===== GET FILE TAG =====
function fileTag = GetFileTag(sProcess)
    fileTag = sProcess.options.method.Value;
end

%% ===== RUN =====
function OutputFile = Run(sProcess, sInput) %#ok<DEFNU>

    % ===== GET OPTIONS =====
    Output = sProcess.options.output.Value;
    Method = sProcess.options.method.Value;
    isOverwrite = sProcess.options.overwrite.Value;
    % Freq indices
    if isfield(sProcess.options, 'freqrange') && isfield(sProcess.options.freqrange, 'Value') && iscell(sProcess.options.freqrange.Value) && (length(sProcess.options.freqrange.Value) == 3) && (length(sProcess.options.freqrange.Value{1}) == 2)
        FreqRange = sProcess.options.freqrange.Value{1};
    else
        FreqRange = [];
    end
    OutputFile = [];

    % ===== LOAD FILE =====
    % Load TF file
    TimefreqMat = in_bst_timefreq(sInput.FileName, 0);
    % Check for measure
    if strcmpi(TimefreqMat.Measure, 'none')
        bst_report('Error', sProcess, sInput, 'Cannot process complex values. Please apply a measure to the values before calling this function.');
        return;
    end
    % Get file frequency vector
    if iscell(TimefreqMat.Freqs)
        BandBounds = process_tf_bands('GetBounds', TimefreqMat.Freqs);
        FreqVector = mean(BandBounds,2);
        FreqBounds = [BandBounds(1,1), BandBounds(end,2)];
    else
        FreqVector = TimefreqMat.Freqs;
        FreqBounds = [FreqVector(1), FreqVector(end)];
    end
    % Rounds the frequency vector, to have the same level of precision as the process (3 significant digits)
    FreqVector = round(FreqVector * 1000) / 1000;
    % Keep only selected frequencies
    if ~isempty(FreqRange)
        % Find the selected frequencies
        iFreqs = find((FreqVector >= FreqRange(1)) & (FreqVector <= FreqRange(2)));
        if isempty(iFreqs)
            bst_report('Error', sProcess, sInput, 'Invalid frequency range.');
            return;
        end
        TimefreqMat.TF = TimefreqMat.TF(:,:,iFreqs);
        % Keep only the selected frequencies
        if iscell(TimefreqMat.Freqs)
            TimefreqMat.Freqs = TimefreqMat.Freqs(iFreqs,:);
        else
            TimefreqMat.Freqs = TimefreqMat.Freqs(iFreqs);
        end
        FreqVector = FreqVector(iFreqs);
    end

    % ===== FIND MAXIMUM =====
    % Preprocess values to detect the correct peaks
    minmaxFunc = @max;
    switch (Method)
        case 'absmax'
            TimefreqMat.TF = abs(TimefreqMat.TF);
        case 'max'
            % nothing to change
        case 'min'
            minmaxFunc = @min;
    end
    % Find maximum in frequency
    [MinMax, iMinMax] = minmaxFunc(TimefreqMat.TF, [], 3);
    % Save the expected value
    switch (Output)
        case 'amplitude'
            TimefreqMat.TF = MinMax;
            strMethod = '';
        case 'frequency'
            TimefreqMat.TF = reshape(FreqVector(iMinMax), size(iMinMax));
            strMethod = ', frequency';
            TimefreqMat.DisplayUnits = 'Hz';
            TimefreqMat.Measure = 'frequency';
    end

    % ===== SAVE FILE =====
    % Save as frequency band
    FreqBounds = round(FreqBounds * 10) / 10;
    TimefreqMat.Freqs = {Method, [num2str(FreqBounds(1)) ', ' num2str(FreqBounds(2))], Method};
    % Add file tag
    TimefreqMat.Comment = [TimefreqMat.Comment, ' | ' Method strMethod];
    % Do not keep the Std/TFmask fields in the output
    if isfield(sInput, 'Std') && ~isempty(sInput.Std)
        sInput.Std = [];
    end
    if isfield(sInput, 'TFmask') && ~isempty(sInput.TFmask)
        sInput.TFmask = [];
    end
    % Add history entry
    TimefreqMat = bst_history('add', TimefreqMat, 'maxfreq', ['Find the ' Method ' across frequencies.']);

    % Overwrite the input file
    if isOverwrite
        OutputFile = file_fullpath(sInput.FileName);
        bst_save(OutputFile, TimefreqMat, 'v6');
        % Reload study
        db_reload_studies(sInput.iStudy);
    % Save new file
    else
        % Output filename: add file tag
        OutputFile = strrep(file_fullpath(sInput.FileName), '.mat', '_maxfreq.mat');
        OutputFile = file_unique(OutputFile);
        % Save file
        bst_save(OutputFile, TimefreqMat, 'v6');
        % Add file to database structure
        db_add_data(sInput.iStudy, OutputFile, TimefreqMat);
    end
end

author: brainstorm-tools


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

% Last Modified by GUIDE v2.5 03-Dec-2018 16:54:55

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

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

    centerUIFigure(hObject);

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

    populateGUI(handles, lvdData);

    % Update handles structure
    guidata(hObject, handles);

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

function populateGUI(handles, lvdData)
    initStateModel = lvdData.initStateModel;

    handles.useLiftForceCheckbox.Value = double(initStateModel.aero.useLift);
    handles.areaText.String = fullAccNum2Str(initStateModel.aero.areaLift);
    handles.liftCoeffText.String = fullAccNum2Str(initStateModel.aero.Cl_0);
    handles.liftVectXText.String = fullAccNum2Str(initStateModel.aero.bodyLiftVect(1));
    handles.liftVectYText.String = fullAccNum2Str(initStateModel.aero.bodyLiftVect(2));
    handles.liftVectZText.String = fullAccNum2Str(initStateModel.aero.bodyLiftVect(3));

    useLiftForceCheckbox_Callback(handles.useLiftForceCheckbox, [], handles);

% --- Outputs from this function are returned to the command line.
function varargout = lvd_EditLiftPropertiesGUI_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;
        varargout{2} = false;
        varargout{3} = false;
        varargout{4} = false;
        varargout{5} = false;
    else
        lvdData = getappdata(handles.lvd_EditLiftPropertiesGUI,'lvdData');
        initStateModel = lvdData.initStateModel;

        initStateModel.aero.useLift = logical(handles.useLiftForceCheckbox.Value);
        initStateModel.aero.areaLift = str2double(handles.areaText.String);
        initStateModel.aero.Cl_0 = str2double(handles.liftCoeffText.String);
        initStateModel.aero.bodyLiftVect(1) = str2double(handles.liftVectXText.String);
        initStateModel.aero.bodyLiftVect(2) = str2double(handles.liftVectYText.String);
        initStateModel.aero.bodyLiftVect(3) = str2double(handles.liftVectZText.String);

        varargout{1} = true;
        varargout{2} = initStateModel.aero.useLift;
        varargout{3} = initStateModel.aero.areaLift;
        varargout{4} = initStateModel.aero.Cl_0;
        varargout{5} = initStateModel.aero.bodyLiftVect;
        close(handles.lvd_EditLiftPropertiesGUI);
    end

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

    area = str2double(get(handles.areaText,'String'));
    enteredStr = get(handles.areaText,'String');
    numberName = 'Surface Area';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(area, numberName, lb, ub, isInt, errMsg, enteredStr);

    cD = str2double(get(handles.liftCoeffText,'String'));
    enteredStr = get(handles.liftCoeffText,'String');
    numberName = 'Lift Coefficient';
    lb = 0;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(cD, numberName, lb, ub, isInt, errMsg, enteredStr);

    bodyX = str2double(get(handles.liftVectXText,'String'));
    enteredStr = get(handles.liftVectXText,'String');
    numberName = 'Lift Vector Body X';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(bodyX, numberName, lb, ub, isInt, errMsg, enteredStr);

    bodyY = str2double(get(handles.liftVectYText,'String'));
    enteredStr = get(handles.liftVectYText,'String');
    numberName = 'Lift Vector Body Y';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(bodyY, numberName, lb, ub, isInt, errMsg, enteredStr);

    bodyZ = str2double(get(handles.liftVectZText,'String'));
    enteredStr = get(handles.liftVectZText,'String');
    numberName = 'Lift Vector Body Z';
    lb = -Inf;
    ub = Inf;
    isInt = false;
    errMsg = validateNumber(bodyZ, numberName, lb, ub, isInt, errMsg, enteredStr);

% --- Executes on button press in saveCloseButton.
function saveCloseButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveCloseButton (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_EditLiftPropertiesGUI);
    else
        msgbox(errMsg,'Errors were found while editing lift properties.','error');
    end

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

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

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

% --- Executes during object creation, after setting all properties.
function liftCoeffText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to liftCoeffText (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 useLiftForceCheckbox.
function useLiftForceCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to useLiftForceCheckbox (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 useLiftForceCheckbox
    if(get(hObject,'Value'))
        handles.areaText.Enable = 'on';
        handles.liftCoeffText.Enable = 'on';
        handles.liftVectXText.Enable = 'on';
        handles.liftVectYText.Enable = 'on';
        handles.liftVectZText.Enable = 'on';
    else
        handles.areaText.Enable = 'off';
        handles.liftCoeffText.Enable = 'off';
        handles.liftVectXText.Enable = 'off';
        handles.liftVectYText.Enable = 'off';
        handles.liftVectZText.Enable = 'off';
    end

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

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

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

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

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

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

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function view=createParamMapFromAnatomy(view)
% anatomyParamMap=createParamMapFromAnatomy(view)
%
% Creates a gray parameter map from the gray matter values in each gray node
% Only works in gray mode
% Author ARW 050805: Wrote it.
% Example : VOLUME{1}=createParamMapFromAnatomy(VOLUME{1})
%
%
mrGlobals;

if ~strcmp(view.viewType,'Gray')
    error('This function requires a Gray view');
end

%
% if (ieNotDefined('view.anat'))
%     error('Anat must be loaded');
% end

% Find out the size of the 'anat' field in the view.
anatSize=size(view.anat);

% Check here in case anat is not loaded...

% Now turn the coords into indices
grayMatterIndices=sub2ind(anatSize,view.coords(1,:),view.coords(2,:),view.coords(3,:));

map=view.anat(grayMatterIndices);
nScans=length(dataTYPES(view.curDataType).scanParams);
for t=1:nScans
    view.map{t}=[];
end

view.map{getCurScan(view)}=map;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function volROI = ip2volROI(ipROI,ipView,volView)
%
% volROI = ip2volROI(ipROI,ipView,volView)
%
% Creates a volume ROI from an inplane ROI by mapping
% coordinates, keeping track of partial voluming
%
% ipROI and volROI are ROI structures, like those found in
% view.ROIs
%
% ipView must be the INPLANE structure.
% volView must be the VOLUME structure.
%
% djh, 8/98.
global mrSESSION
global vANATOMYPATH

% check that some more-recently-implemented fields are defined
% (ras, 02/2007)
ipROI = roiCheck(ipROI);

% Get voxel sizes to make sure that the transformation preserves volume
ipVoxSize = viewGet(ipView, 'voxel size');
volVoxSize = readVolAnatHeader(vANATOMYPATH);

% Transform ROI coordinates
xform = mrSESSION.alignment;

coords = xformROIcoords(ipROI.coords, xform, ipVoxSize, volVoxSize);

if isempty(coords)
    % put a warning, but only if these aren't hidden views
    if ~isequal(viewGet(ipView,'Name'), 'hidden') && ~isequal(viewGet(volView,'Name'), 'hidden')
        msg = sprintf(['No voxels from %s map to the volume view. ' ...
                       'No ROI created.'], ipROI.name);
        myWarnDlg(msg);
        volROI = [];
        return
    end
end

% Toss coords outside the volume
volSize = viewGet(volView,'Size');
indices = ((coords(1,:) >= 1) & (coords(1,:) <= volSize(1)) & ...
    (coords(2,:) >= 1) & (coords(2,:) <= volSize(2)) & ...
    (coords(3,:) >= 1) & (coords(3,:) <= volSize(3)));
coords = coords(:,indices);

% Set the other fields and sort
volROI = ipROI;
volROI.coords = coords;
volROI.viewType = volView.viewType;

return;

%%%%%%%%%%%%%%
% Debug/test %
%%%%%%%%%%%%%%

ipROI = INPLANE{1}.ROIs(INPLANE{1}.selectedROI);
volROI = ip2volROI(ipROI,INPLANE{1},VOLUME{1});
newipROI = vol2ipROI(volROI,VOLUME{1},INPLANE{1});
ipROI.coords
newipROI.coords


text:
function [cc,c0]=v_lpcar2cc(ar,np)
%V_LPCAR2CC LPC: Convert AR filter to complex cepstrum [CC,C0]=(AR,NP)
%
%  Inputs: ar(nf,n+1)   AR coefficients, one frame per row
%          np           Number of cepstral coefficients to calculate [n]
%
% Outputs: cc(nf,np)    Complex cepstral coefficients, excluding c(0)
%          c0(nf,1)     Coefficient c(0)
%
% The "complex cepstral coefficients", cc(n), are the inverse discrete-time Fourier transform
% of the log of the complex-valued spectrum. The cc(n) are real-valued and, for n<0, cc(n)=0.
% The "real cepstral coeffcients", rc(n), are the inverse discrete-time Fourier transform
% of the log of the magnitude spectrum; rc(0)=cc(0) and rc(n)=0.5*cc(n) for n~=0.

%      Copyright (C) Mike Brookes 1998-2014
%      Version: $Id: v_lpcar2cc.m 10865 2018-09-21 17:22:45Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[nf,p1]=size(ar);
p=p1-1;
if (nargin<2) np=p; end
cc=zeros(nf,np);
if any(ar(:,1)~=1)
    c0=-log(ar(:,1));
    ar=ar./ar(:,ones(1,p1));
else
    c0=zeros(nf,1);
end
cm=(1:np).^(-1);
if np>p
    xm=-(1:p);
    nz=np-p;
    for k=1:nf
        cc(k,:)=filter(1,ar(k,:),[ar(k,2:p1).*xm zeros(1,nz)]).*cm;
    end
else
    p1=np+1;
    xm=-(1:np);
    for k=1:nf
        cc(k,:)=filter(1,ar(k,:),ar(k,2:p1).*xm).*cm;
    end
end
if ~nargout
    v_lpccc2pf(cc,[],[],c0);
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
%EXPORT_CSV Export grid and data in CSV format.
%
%   EXPORT_CSV( FILENAME, FEA, EXPR, SOLNUM, FID_LOG )
%
%   Export of grid points and corresponding solution/expression data
%   in CSV format. The CSV file will consist of a header line with the
%   space coordinate names, dependent variable names, and given
%   expressions (columns). This is followed by the actual data rows
%   where one line corresponds to the data for the specific grid
%   point.
%
%   FILENAME gives the output file name. FEA must be a valid FEA data
%   struct, EXPR is optionally a cell array with expressions to
%   process (the grid coordinates and dependent variables in the FEA
%   struct will be prepended to EXPR). SOLNUM is optionally the
%   solution number of which to evaluate the expressions. FID_LOG is
%   an optional log file handle for message output (negative for gui
%   output or empty for no output).

% Copyright 2013-2022 Precise Simulation, Ltd.

author: precise-simulation

repo: featool-multiphysics


text:
%% Scene Text Detection using CNN
%
% References:
%
% * Minghui Liao, Baoguang Shi, Xiang Bai, Xinggang Wang, Wenyu Liu.
%   "TextBoxes: A Fast Text Detector with a Single Deep Neural Network",
%   AAAI 2017. <https://arxiv.org/abs/1611.06779>
%
% Sources:
%
% * <https://github.com/opencv/opencv_contrib/blob/3.4.1/modules/text/samples/textbox_demo.cpp>
% * <https://github.com/opencv/opencv_contrib/blob/3.4.1/modules/text/samples/deeptextdetection.py>
%

%%
% load model
textSpotter = TextBoxes();

%%
% detect text
im = which('handicapSign.jpg');
assert(~isempty(im), 'specify input image');
img = cv.imread(im, 'Color',true, 'FlipChannels',false);
[bboxes, confs] = textSpotter.detect(img);
fprintf('%d text detections\n', numel(bboxes));

%%
% post-processing
if true
    % non-maximum suppression
    ind = cv.Net.NMSBoxes(bboxes, confs, 0.3, 0.4);
    ind = ind + 1;  % zero to one-based indices
    bboxes = bboxes(ind);
    confs = confs(ind);
else
    % confidence thresholding
    idx = confs > 0.6;
    bboxes = bboxes(idx);
    confs = confs(idx);
end
fprintf('%d text detections after filtering\n', numel(bboxes));

%%
% show results
img = flip(img, 3);
for i=1:numel(bboxes)
    img = insertAnnotation(img, bboxes{i}, sprintf('%.2f', confs(i)), ...
        'Color',[255 0 255], 'TextColor',[255 255 255], 'Thickness',2, 'FontScale',0.3);
    fprintf('text box: [%3d %3d %3d %3d], confidence: %3.0f%%\n', ...
        bboxes{i}, confs(i)*100);
end
imshow(img), title('TextBox Demo')

%%
% Helper functions

function img = insertAnnotation(img, rect, str, varargin)
    % See also: insertObjectAnnotation, insertShape, insertText
    p = inputParser();
    p.addParameter('Alpha', 0.6);
    p.addParameter('Thickness', 1);
    p.addParameter('Color', [255 255 0]);
    p.addParameter('TextColor', [0 0 0]);
    p.addParameter('FontFace', 'HersheySimplex');
    p.addParameter('FontScale', 0.4);
    p.addParameter('AntiAlias', true);
    p.addParameter('Shape', 'rectangle');
    p.parse(varargin{:});
    opts = p.Results;
    opts.Shape = validatestring(opts.Shape, {'rectangle','circle'});
    thick = 1;

    [sz,b] = cv.getTextSize(str, 'Thickness',thick, ...
        'FontFace',opts.FontFace, 'FontScale',opts.FontScale);
    txt_rect = [rect(1), rect(2)-sz(2)-b, sz(1), sz(2)+b];
    txt_orig = [rect(1), rect(2)-b];

    if opts.AntiAlias
        alias = {'LineType','AA'};
    else
        alias = {'LineType',8};
    end

    overlay = img;
    if strcmp(opts.Shape, 'rectangle')
        overlay = cv.rectangle(overlay, rect, ...
            'Color',opts.Color, 'Thickness',opts.Thickness, alias{:});
    else
        c = rect(1:2) + rect(3:4)/2;
        r = max(rect(3:4)/2);
        overlay = cv.circle(overlay, c, r, ...
            'Color',opts.Color, 'Thickness',opts.Thickness, alias{:});
    end
    overlay = cv.rectangle(overlay, txt_rect, ...
        'Color',opts.Color, 'Thickness','Filled', alias{:});
    if opts.Thickness > 1
        overlay = cv.rectangle(overlay, txt_rect, ...
            'Color',opts.Color, 'Thickness',opts.Thickness, alias{:});
    end
    overlay = cv.putText(overlay, str, txt_orig, ...
        'FontFace',opts.FontFace, 'FontScale',opts.FontScale, ...
        'Color',opts.TextColor, 'Thickness',thick, alias{:});

    img = cv.addWeighted(img,1-opts.Alpha, overlay,opts.Alpha, 0);
end

%%
% Pretrained models

function dname = get_dnn_dir(dname)
    %GET_DNN_DIR  Path to model files, and show where to get them if missing

    dname = fullfile(mexopencv.root(), 'test', 'dnn', dname);
    b = isdir(dname);
    if ~b
        % display help of calling function
        % (assumed to be a local function in current file)
        st = dbstack(1);
        help([mfilename() filemarker() st(1).name])
    end
    assert(b, 'Missing model: %s', dname);
end

function net = TextBoxes()
    %TEXTDETECTOR  Text detector model [Caffe]
    %
    % homepage = https://github.com/MhLiao/TextBoxes
    %
    % ## Model
    %
    % file = test/dnn/TextBoxes/textbox.prototxt
    % url  = https://github.com/opencv/opencv_contrib/raw/3.4.1/modules/text/samples/textbox.prototxt
    % hash = c294416fe6d156b9383342d62b9158ab707170c0
    %
    % ## Weights
    %
    % file = test/dnn/TextBoxes/TextBoxes_icdar13.caffemodel
    % url  = https://www.dropbox.com/s/g8pjzv2de9gty8g/TextBoxes_icdar13.caffemodel?dl=0
    % hash = e4b32aef3db3d66fec0630c96006e10999f785c4
    % size = 90.68 MB
    %

    dname = get_dnn_dir('TextBoxes');
    net = cv.TextDetectorCNN(...
        fullfile(dname, 'textbox.prototxt'), ...
        fullfile(dname, 'TextBoxes_icdar13.caffemodel'), ...
        'DetectionSizes',[300 300]);
end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function cache = score_init_cache(N,L)
% SCORE_INIT_CACHE generate an empty cache for local computation in structure learning
% cache = score_init_cache(number_of_nodes,cache_size)
%
% For 2 nodes with cache of size 5 :
%
% cache =
%   Nw  b        0      0      0 --> Nw=number of writings in cache (+1) and b==1 iff the cache is full
%   0   0        1   -239.12   1 --> 1st familly in the cache (node 1 without parents) calculate with bic
%   0   0        2   -318.98   1
%   1   0        2   -189.23   2 --> 3rd familly in the cache (node 2 with 1 as parent) calculate with bayesian
%   0   1        1   -251.09   1
%   0   0        0      0      0 --> empty entry
%   |   |        |      |      |
%   |   |        |      |      |___> scoring function : 1 for 'bic', 2 for 'bayesian', ...
%   |   |        |      |__________> local score of the familly
%   |   |        |_________________> son node of the familly
%   |   |__________________________> ==1 iff node 2 is parent of son node
%   |______________________________> ==1 iff node 1 is parent of son node
%
%
% V1.1 : 6 may 2003 (O. Francois - francois.olivier.c.h@gmail.com, Ph. Leray - philippe.leray@univ-nantes.fr)
%
%

cache=zeros(L+1,N+3);
cache(1,1)=2;

% using a sparse matrix does not improve performances

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function  PATCHA  = readPATCHA(fid)
%
% <<<<<<<<<< CLASSIFICATION: UNCLASSIFIED >>>>>>>>>>
%
% READPATCHA Create structure for metadata fields.
%   PATCHA = READPATCHA(FID) returns a structure of fields and their
%   associated values.

% Written by Matt Donath, NGA, matthew.b.donath@nga.ic.gov
% References:
%  > MIL-STD-2500A, NATIONAL IMAGERY TRANSMISSION FORMAT VERSION 2.0
%  > MIL-STD-2500C, NATIONAL IMAGERY TRANSMISSION FORMAT VERSION 2.1
%  > STDI-0001,     NATIONAL SUPPORT DATA EXTENSIONS (SDE)(VERSION 1.3/CN2)
%                   FOR THE NATIONAL IMAGERY TRANSMISSION FORMAT (NITF)
%  > STDI-0002,     THE COMPENDIUM OF CONTROLLED EXTENSIONS (CE) FOR THE
%                   NATIONAL IMAGERY TRANSMISSION FORMAT (NITF) VERSION 2.1
%
% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

%% Create the metadata structure for PATCHA.

PATCHA.CETAG = fread(fid,6,'uint8=>char')';
PATCHA.CEL = str2double(fread(fid,5,'uint8=>char')');

PATCHA.PAT_NO = str2double(fread(fid,4,'uint8=>char')');
PATCHA.LAST_PAT_FLAG = fread(fid,1,'uint8=>char')';
PATCHA.LNSTRT = str2double(fread(fid,7,'uint8=>char')');
PATCHA.LNSTOP = str2double(fread(fid,7,'uint8=>char')');
PATCHA.AZL = str2double(fread(fid,5,'uint8=>char')');
PATCHA.NVL = str2double(fread(fid,5,'uint8=>char')');
PATCHA.FVL = str2double(fread(fid,3,'uint8=>char')');
PATCHA.NPIXEL = str2double(fread(fid,5,'uint8=>char')');
PATCHA.FVPIX = str2double(fread(fid,5,'uint8=>char')');
PATCHA.FRAME = str2double(fread(fid,3,'uint8=>char')');
PATCHA.UTC = str2double(fread(fid,8,'uint8=>char')');
PATCHA.SHEAD = str2double(fread(fid,7,'uint8=>char')');
PATCHA.GRAVITY = str2double(fread(fid,7,'uint8=>char')');
PATCHA.INS_V_NC = str2double(fread(fid,5,'uint8=>char')');
PATCHA.INS_V_EC = str2double(fread(fid,5,'uint8=>char')');
PATCHA.INS_V_DC = str2double(fread(fid,5,'uint8=>char')');
PATCHA.OFFLAT = str2double(fread(fid,8,'uint8=>char')');
PATCHA.OFFLONG = str2double(fread(fid,8,'uint8=>char')');
PATCHA.TRACK = str2double(fread(fid,3,'uint8=>char')');
PATCHA.GSWEEP = str2double(fread(fid,6,'uint8=>char')');
PATCHA.SHEAR = str2double(fread(fid,8,'uint8=>char')');

% //////////////////////////////////////////
% /// CLASSIFICATION: UNCLASSIFIED       ///
% //////////////////////////////////////////

author: ngageoint


text:
% UFgetPetscMat.m
% modified from UFget_example.m
%   This script
%     (1) gets the selected index file of the UF sparse matrix collection,
%     (2) loads in matrices in matlab format in increasing order of
%         number of rows in the selected matrices,
%     (3) writes into PETSc binary format in the given directory with
%         each matrix named as A_{id}
%
%   See also UFget_example.m
%   Copyright 2009, PETSc Team.

index = UFget;

% sets selection here
f = find (index.nrows == index.ncols & index.nrows > 940000 & index.isReal) ;
[y, j] = sort (index.nrows (f)) ;
f = f (j) ;

for i = f
    %loads in matrix in matlab format
    %---------------------------------
    fprintf ('Loading %s%s%s, please wait ...\n', ...
        index.Group {i}, filesep, index.Name {i}) ;
    Problem = UFget (i,index) ;
    disp (Problem) ;
    title (sprintf ('%s:%s', Problem.name, Problem.title')) ;

    % convets to PETSc binary format and writes into ~mat/A_{id}
    %-----------------------------------------------------------
    fname = ['mat/A',num2str(i)];
    fprintf ('write matrix into petsc binary file %s ...\n',fname);
    PetscBinaryWrite(fname,Problem.A);
    %input ('hit enter to continue:') ;
end

author: wsshin

repo: maxwellfdfd

save_path: github-repos/MATLAB/wsshin-maxwellfdfd


text:
function [idx,D]=fastknnsearch(varargin)
% KNNSEARCH   Linear k-nearest neighbor (KNN) search
% IDX = knnsearch(Q,R,K) searches the reference data set R (n x d array
% representing n points in a d-dimensional space) to find the k-nearest
% neighbors of each query point represented by eahc row of Q (m x d array).
% The results are stored in the (m x K) index array, IDX.
%
% IDX = knnsearch(Q,R) takes the default value K=1.
%
% IDX = knnsearch(Q) or IDX = knnsearch(Q,[],K) does the search for R = Q.
%
% Rationality
% Linear KNN search is the simplest appraoch of KNN. The search is based on
% calculation of all distances. Therefore, it is normally believed only
% suitable for small data sets. However, other advanced approaches, such as
% kd-tree and delaunary become inefficient when d is large comparing to the
% number of data points. On the other hand, the linear search in MATLAB is
% relatively insensitive to d due to the vectorization. In  this code, the
% efficiency of linear search is further improved by using the JIT
% aceeleration of MATLAB. Numerical example shows that its performance is
% comparable with kd-tree algorithm in mex.
%
% See also, kdtree, nnsearch, delaunary, dsearch

% By Yi Cao at Cranfield University on 25 March 2008

% Example 1: small data sets
%{
R=randn(100,2);
Q=randn(3,2);
idx=knnsearch(Q,R);
plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'ro',R(idx,1),R(idx,2),'gx');
%}

% Example 2: ten nearest points to [0 0]
%{
R=rand(100,2);
Q=[0 0];
K=10;
idx=knnsearch(Q,R,10);
r=max(sqrt(sum(R(idx,:).^2,2)));
theta=0:0.01:pi/2;
x=r*cos(theta);
y=r*sin(theta);
plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'co',R(idx,1),R(idx,2),'gx',x,y,'r-','linewidth',2);
%}

% Example 3: cputime comparion with delaunay+dsearch I, a few to look up
%{
R=randn(10000,4);
Q=randn(500,4);
t0=cputime;
idx=knnsearch(Q,R);
t1=cputime;
T=delaunayn(R);
idx1=dsearchn(R,T,Q);
t2=cputime;
fprintf('Are both indices the same? %d\n',isequal(idx,idx1));
fprintf('CPU time for knnsearch = %g\n',t1-t0);
fprintf('CPU time for delaunay  = %g\n',t2-t1);
%}
% Example 4: cputime comparion with delaunay+dsearch II, lots to look up
%{
Q=randn(10000,4);
R=randn(500,4);
t0=cputime;
idx=knnsearch(Q,R);
t1=cputime;
T=delaunayn(R);
idx1=dsearchn(R,T,Q);
t2=cputime;
fprintf('Are both indices the same? %d\n',isequal(idx,idx1));
fprintf('CPU time for knnsearch = %g\n',t1-t0);
fprintf('CPU time for delaunay  = %g\n',t2-t1);
%}
% Example 5: cputime comparion with kd-tree by Steven Michael (mex file)
% kd-tree by Steven Michael
%{
Q=randn(10000,10);
R=randn(500,10);
t0=cputime;
idx=knnsearch(Q,R);
t1=cputime;
tree=kdtree(R);
idx1=kdtree_closestpoint(tree,Q);
t2=cputime;
fprintf('Are both indices the same? %d\n',isequal(idx,idx1));
fprintf('CPU time for knnsearch = %g\n',t1-t0);
fprintf('CPU time for delaunay  = %g\n',t2-t1);
%}

% Check inputs
[Q,R,K,fident] = parseinputs(varargin{:});

% Check outputs
nargoutchk(0,2);

% C2 = sum(C.*C,2)';
[N,M] = size(Q);
L=size(R,1);
idx = zeros(N,K);
D = idx;

if K==1
    % Loop for each query point
    for k=1:N
        d=zeros(L,1);
        for t=1:M
            d=d+(R(:,t)-Q(k,t)).^2;
        end
        if fident
            d(k)=inf;
        end
        [D(k),idx(k)]=min(d);
    end
else
    for k=1:N
        d=zeros(L,1);
        for t=1:M
            d=d+(R(:,t)-Q(k,t)).^2;
        end
        if fident
            d(k)=inf;
        end
        [s,t]=sort(d);
        idx(k,:)=t(1:K);
        D(k,:)=s(1:K);
    end
end
if nargout>1
    D=sqrt(D);
end

function [Q,R,K,fident] = parseinputs(varargin)
% Check input and output
narginchk(1,3);

Q=varargin{1};

if nargin<2
    R=Q;
    fident = true;
else
    fident = false;
    R=varargin{2};
end

if isempty(R)
    fident = true;
    R=Q;
end

if ~fident
    fident = isequal(Q,R);
end

if nargin<3
    K=1;
else
    K=varargin{3};
end

author: matthieukomorowski


text:
function [varargout] = opm_fil(filename, hdr, begsample, endsample, chanindx)

% OPM_FIL reads header, data and events from OPM MEG recordings that are done at the FIL (UCL, London).
%
% Use as
%   hdr = opm_fil(filename);
%   dat = opm_fil(filename, hdr, begsample, endsample, chanindx);
%   evt = opm_fil(filename, hdr);
%
% See https://github.com/tierneytim/OPM for technical details.
%
% See also FT_FILETYPE, FT_READ_HEADER, FT_READ_DATA, FT_READ_EVENT, QUALISYS_TSV, MOTION_C3D, EVENTS_TSV

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

needhdr = (nargin==1);
needevt = (nargin==2);
needdat = (nargin==5);

% It is permitted to pass any of the files that comprise the dataset
% figure out which files comprise the dataset
[p, f, x] = fileparts(filename);
assert(isfile(filename), sprintf('file "%s" not found', filename));

channelsfile  = fullfile(p, 'channels.tsv');
coordsysfile  = fullfile(p, 'coordsystem.json');
datafile      = fullfile(p, 'meg.bin');
headerfile    = fullfile(p, 'meg.json');
positionsfile = fullfile(p, 'positions.tsv');

precision = 'double';
switch precision
  case 'single'
    samplesize = 4;
  case 'double'
    samplesize = 8;
end

if needhdr
  %% read the header

  fid = fopen(headerfile, 'rt');
  header = jsondecode(fread(fid, [1 inf], 'char=>char'));
  fclose(fid);

  channels  = readtable(channelsfile, 'Delimiter', 'tab', 'FileType', 'text');

  % this one is optional
  if exist(coordsysfile, 'file')
    fid = fopen(coordsysfile, 'rt');
    coordsys = jsondecode(fread(fid, [1 inf], 'char=>char'));
    fclose(fid);
  else
    coordsys = [];
  end

  % this one is optional
  if exist(positionsfile, 'file')
    positions = readtable(positionsfile, 'Delimiter', 'tab', 'FileType', 'text');
  else
    positions = [];
  end

  d = dir(datafile);

  hdr.label       = channels.name;
  hdr.nChans      = size(channels, 1);
  hdr.nSamples    = d.bytes/(size(channels, 1) * samplesize);
  hdr.nSamplesPre = 0; % continuous data
  hdr.nTrials     = 1; % continuous data
  hdr.Fs          = header.SamplingFrequency;
  hdr.chantype    = channels.type;
  hdr.chanunit    = repmat({'unknown'}, size(hdr.label));

  % keep the original header details
  hdr.orig.header     = header;
  hdr.orig.coordsys   = coordsys;
  hdr.orig.positions  = positions;
  hdr.orig.channels   = channels;

  if ~isempty(positions)
    % FIXME construct a grad structure
    hdr.grad.label = positions.name;
    hdr.grad.coilpos = [positions.Px positions.Py positions.Pz];
    hdr.grad.coilori = [positions.Ox positions.Oy positions.Oz];
    hdr.grad.type = 'meg';
    if ~isempty(coordsys)
      hdr.grad.unit = coordsys.MEGCoordinateUnits;
      hdr.grad.coordsys = coordsys.MEGCoordinateSystem;
    end
  end

  % return the header details
  varargout = {hdr};

elseif needdat
  %% read the data, note that it is big endian

  fid = fopen(datafile, 'rb');
  fseek(fid, begsample*samplesize*hdr.nChans, 'bof');
  dat = fread(fid,[hdr.nChans, (endsample-begsample+1)], precision, 0, 'b');
  fclose(fid);

  % take the selection of channels
  dat = dat(chanindx,:);

  % return the data
  varargout = {dat};

elseif needevt
  %% read the events

  % FIXME this does not yet allow the user to override the defaults for ft_read_event, such as detectflank
  event = read_trigger(filename, 'header', hdr, 'dataformat', 'opm_fil', 'chanindx', find(strcmpi(hdr.chantype, 'TRIG')));

  % return the events
  varargout = {event};

end


text:
%     THIS CODE IS FOR PLOTTING METRICS ON WAVEFORM
%     THIS COULD BE ABSORBED INTO PLOT PANELS
%     for arrivalnum=1:numel(arrivalobj.amp)
%         fprintf('.');
%         thisA = arrivalobj.subset(arrivalnum);
%         thisW = detrend(fillgaps(w(arrivalnum),'interp')); % make sure there is no trend or offset
%
%         % plot waveform for arrival
%         fh=plot_panels(thisW, false, thisA);
%         ah=get(fh,'Children');
%         set(fh, 'Position', [0 0 1600 1000]);
%         hold on
%         plot(maxSecs, misc_fields.maxAmp(arrivalnum), 'g*');
%         plot(minSecs, misc_fields.minAmp(arrivalnum), 'r*');
%         teststr = sprintf('maxTime = %s, minTime = %s, timeDiff = %.3f s\namp = %.2e, maxAmp = %.2e, minAmp = %.2e\n rms = %.2e, energy = %.2e',  ...
%             datestr(maxTime,'HH:MM:SS.FFF'), ...
%             datestr(minTime,'HH:MM:SS.FFF'), ...
%             86400*(maxTime-minTime), ...
%             amp, ...
%             maxAmp, ...
%             minAmp, ...
%             stdev, ...
%             energy);
%         text(0.1, 0.1, teststr, 'units', 'normalized')
%         dummy=input('Any key to continue');
%         close
%
%     end

author: geoscience-community-codes

repo: GISMO