text:
function res = pyff(command, varargin)

% PYFF -  wrapper function used to initialize and communicate with Pyff
%         (http://bbci.de/pyff) from Matlab
%
%Usage:
% res = pyff(command, <OPT>)
%
%IN:
% 'command' -  command to be issued: 'startup', 'init',
%              'setdir','set', 'get', 'refresh','play', 'stop','quit',
%              'saveSettings', 'loadSettings'
%
% res = pyff('startup',<OPT>): startup pyff in a separate console window.
% res contains the command string that is executed. For
% this command, OPT is a property/value list or struct of options with
% the following (optional) fields/properties:
%  .Dir      - pyff source directory (default for win: D:\svn\pyff\src;
%              default for unix: ~/svn/pyff/src)
%  .Parport     - port number for parallel port. Default is dec2hex(BTB.Acq.IoAddr),
%              if BTB.Acq.IoAddr exists, otherwise [].
%  .A        - additional feedback directory (default [])
%  .Gui      - if 1, pyff gui is started along with the feedback controller (default 0)
%  .L        - loglevel (default 'debug')
%
% pyff('init',feedback): load and initialize pyff feedback
%  feedback  - strint containing the name of the feedback
%
% pyff('setdir',<OPT>): set directory and filename for EEG recording.
%  .TodayDir - directory for saving EEG data (default BTB.Tp.Dir)
%  .VpCode   - the code of the VP (Versuchsperson) (default BTB.Tp.Code)
%  .Basename  - the basename of the EEG file (default '')
% Special cases: If OPT=='' all entries are set to '', ensuring that no EEG is
% recorded. If OPT is not given at all, all entries are set to default.
%
% pyff('set',OPT): set feedback variables after the feedback has been
% initialized. OPT is a property/value list or struct of with
% fields/properties referring to names and values of variables. The type of
% the variable (string, integer, or float) is automatically checked.
% NOTE: Unlike Python, Matlab automatically turns integers into floats!
% For example, var1 = 1.0 and var1 = 1 both yield a float. This should not be a problem
% in most cases, but if you definitely need an integer, you should provide the
% type along with the value, e.g. pyff('set','var1',int16(1)).
% Alternatively, you can use the 'setint' command (below).
%
% pyff('setint',OPT): use this command to set feedback variables
% explicitly to integers. If you do this, each provided variable is
% cast to an integer.
%
% res = pyff('get',...): get the value of feedback variables.
% Give a list of variables to be inspected. res is a cell array containing
% the respective values of the variables. [wishful thinking, I think it's
% not possible]
%
% pyff('play'): start playing currently initialized feedback
% pyff('play', 'Basename', BASENAME, <PARAM>): start acquisition in BV Recorder, then start playing
%    currently initialized feedback. PARAM can be 'impedances', 0 to avoid
%    impedance measurement.
% pyff('stop'):  stop current feedback
% pyff('quit'):  quit current feedback (and stop acquisition in BV
%    Recorder).
%
% pyff('saveSettings', FILENAME): load or save the parameters of the feedback
%   to FILENAME. The appendix '.json' is automatically appended.
%   If FILENAME does not contain file separators '\' or '/',
%   BTB.Tp.Dir is prepended.
%
%
% General OPT:
% 'Os'       - operating system 'win' or 'unix' (usually you do not need to
%              set this since the script figures out your OS)
% 'ReplaceHtmlEntities' - replaces symbols like '<' in string to be set via
%                    XML by their according HTML (XML compatible) entities
%OUT:
% res        - final command as a string
%
% ISSUES:
% *command 'getvariables' (aka 'refresh') does not make variables
% appear in the GUI

% Matthias Treder 2010

global BTB
%% TODO: get rid of these (change bvr_* functions to more general ones)
global acquire_func general_port_fields
persistent ACQ_STARTED

props = {'Os',                    'win',                  '!CHAR(win unix)';
         'PyffDir'                BTB.PyffDir             'CHAR';
         'ReplaceHtmlEntities',   1,                      '!BOOL';
         'Parport',               dec2hex(BTB.Acq.IoAddr),'CHAR';
         'A',                     [],                     'CHAR';
         'Gui',                   0,                      'BOOL';
         'L',                     'debug',                'CHAR';
         'TodayDir',              BTB.Tp.Dir,             'CHAR';
         'VpCode',                BTB.Tp.Code,            'CHAR';
         'Basename',              '',                     'CHAR';
         'OutputProtocol',        [],                     'CHAR';
         'Host',                 'localhost',             'CHAR';
         'Port',                  12345,                  'INT';
         'Impedances'             1                       'BOOL';

};

if nargin==0,
  dat= props; return
end

misc_checkType(command,'CHAR(startup init set setint setdir play refresh stop quit saveSettings loadSettings)');

%% Case-dependent check of parameters
switch(command)

  case {'stop','quit'}
    nargchk(1,1,nargin);
    opt=[];
  case 'startup'
    opt = opt_proplistToStruct(varargin{:});

  case 'init'
    nargchk(2,2,nargin);
    feedback = varargin{1};
    opt=[];
    misc_checkType(feedback,'!CHAR');
    ACQ_STARTED= 0;

  case 'setdir'
    nargchk(2,inf,nargin);
    if nargin==2
      opt=[];
      opt.TodayDir = '';
      opt.VpCode = '';
    else
      opt = opt_proplistToStruct(varargin{:});
    end

  case {'set','setint'}
    if nargin==2 && isstruct(varargin{1})
      vars= varargin{1};
    else
      vars = opt_proplistToStruct(varargin{:});
    end
    opt = [];
    if isfield(vars,'ReplaceHtmlEntities')
      warning 'Found variable ''ReplaceHtmlEntities'', assuming its a Pyff parameter, not a variable'
      opt.ReplaceHtmlEntities = vars.ReplaceHtmlEntities;
      vars = rmfield(vars,'ReplaceHtmlEntities');
    end

  case 'play'
    nargchk(1,5,nargin);
    opt = opt_proplistToStruct(varargin{:});

  case {'saveSettings','loadSettings'}
    nargchk(2,2,nargin);
    opt=[];
    filename = varargin{1};
    misc_checkType(filename,'!CHAR');
    settings_file= [filename '.json'];
    if ~any(ismember('/\', settings_file,'legacy')),
      settings_file= [BTB.Tp.Dir settings_file];
  %   % Avoid overwriting? - Maybe it is intended, so we don't.
  %    if strcmp(command,'saveSettings') && exists(settings_file, 'file'),
  %      new_str= datestr(now, 'yyyy-mm-dd_HH:MM:SS.FFF');
  %      settings_file= [settings_file, '_', now_str];
  %    end
    end
end

[opt,isdefault] = opt_setDefaults(opt, props);
opt_checkProplist(opt, props);

% Figure out os (unless it was set manually)
if isdefault.Os
  if isunix || ismac
    opt.Os = 'unix';
  else
    opt.Os = 'win';
  end
end

%% Execute command
res = [];
switch(command)

  case 'startup',

    if strcmp(opt.Os,'win')
      % get system path
      curr_path = getenv('PATH');
      % also sets the path back to the normal system variable. Matlab adds a
      % reference to itself to the beginning of the system path which
      % breaks PyQT.QtCore (possibly also other imports that require dll)
      comstr = ['set PATH=' curr_path '& cmd /C "cd ' opt.PyffDir ' & python FeedbackController.py'];
      if ~isempty(opt.A)
        opt.A= strrep(opt.A, '/', filesep);
      end
    elseif strcmp(opt.Os,'unix')
      comstr = ['xterm -e python ' opt.PyffDir  '/FeedbackController.py'];
%       opt.A= strrep(opt.A, '\', filesep); % probably unneccesary
    end

    if ~isempty(opt.Parport)
      comstr = [comstr ' --port=0x' num2str(opt.Parport)];
    end
    if ~isempty(opt.A)
      comstr = [comstr ' -a "' opt.A '"'];
    end
    if opt.Gui==0
      comstr = [comstr ' --nogui'];
    end
    if ~isempty(opt.L)
      comstr = [comstr ' -l ' opt.L];
    end
    if ~isempty(opt.OutputProtocol)
      comstr = [comstr ' --protocol ' opt.OutputProtocol];
    end

    if strcmp(opt.Os,'win')
      comstr = [comstr '" &'];
    elseif strcmp(opt.Os,'unix')
      comstr = [comstr ' &'];
    end
    system(comstr);
    res = comstr;
    pyff_sendUdp('init', opt.Host, opt.Port);
    general_port_fields.feedback_receiver= 'pyff';

  case 'init'
    pyff_sendUdp('interaction-signal', 's:_feedback', feedback,'command','sendinit');

  case 'setdir'
    pyff_sendUdp('interaction-signal', 's:BTB.Tp.Dir',opt.TodayDir, ...
      's:BTB.Tp.Code',opt.VpCode, 's:BASENAME',opt.Basename);

  case 'set'
    settings= {};
    fn= fieldnames(vars);
    for ii= 1:numel(fn)
      val = vars.(fn{ii});
      % Take value or (if it is a cell) the value of its first element
      if isempty(val) && ~ischar(val)
        typ= '';
      elseif ischar(val) || (iscell(val) && ischar(val{1})) || (iscell(val) && iscell(val{1}) && numel(val{1}) && ischar(val{1}{1}))
        % string or nested string
        typ= 's:';
        if opt.ReplaceHtmlEntities
          val = ReplaceHtmlEntities(val);
        end
      elseif isinteger(val) || (iscell(val) && isinteger(val{1}))
        typ= 'i:';
      elseif islogical(val)
        typ= 'b:';
        if val
          val= 'True';
        else
          val= 'False';
        end
      else
        typ= '';
      end
      settings= cat(2, settings, {[typ fn{ii}], val});
    end
    pyff_sendUdp('interaction-signal', settings{:});

  case 'setint'
    settings= {};
    fn= fieldnames(vars);
    typ= 'i:';
    for ii= 1:numel(fn)
      settings= cat(2, settings, {[typ fn{ii}], vars.(fn{ii})});
    end
    pyff_sendUdp('interaction-signal', settings{:});

  case 'play'
    if isempty(varargin),
      ACQ_STARTED= 0;
    else
      ACQ_STARTED= 1;
      bvr_startrecording(varargin{2}, 'AppendTpCode',1, varargin{3:end});
      pause(0.01);
    end
    pyff_sendUdp('interaction-signal', 'command', 'play');

  case 'stop'
    pyff_sendUdp('interaction-signal', 'command', 'stop');

  case 'quit'
    pyff_sendUdp('interaction-signal', 'command', 'quit');
%     if strcmp(func2str(acquire_func), 'acquire_bv') && ACQ_STARTED,
    if ACQ_STARTED
       bvr_sendcommand('stoprecording');
       ACQ_STARTED= 0;
    end

  case 'loadSettings'
    pyff_sendUdp('interaction-signal', 'loadvariables', settings_file);

  case 'saveSettings'
    pyff_sendUdp('interaction-signal', 'savevariables', settings_file);

end

%% HELP FUNCTIONS
function str = ReplaceHtmlEntities(str,direction)

  % REPLACE_HTML_ENTITIES -  replaces special symbols such as '<' by their
  %             according HTML entities for correct display in HTML or XML.
  %             Can also perform the backward substitution (replacing HTML
  %             entities by symbols).
  %
  %Usage:
  % str = pyff(str,<direction>)
  %
  %IN:
  % str - input string or cell array of strings
  % direction - direction of substitution, 'forward' (default) replaces
  %             symbols by HTML entities, 'backward' does the opposite
  %
  %OUT:
  % str - string with special symbols replaced by HTML entities
  %
  %EXAMPLE:
  % replace_html_entities('If A < B then C')

  % Matthias Treder 2010

  if nargin<2, direction = 'forward'; end

  % TO DO ---- REPLACE literal special letters by their ASCII code !!!

  % Specify symbols (ie their ASCII code) and their corresponding entities in matched order
  source = {'´'            'ä'      'Ä'      '<'    '>' ...
    'ö'      'Ö'     };
  target = {'´' 'ä' 'Ä' '<' '>' ...
    'ö' 'Ö'};
%     '^'   'ˆ'   % <- this is not necessary?

  % For backward substitution switch source and target
  if strcmp(direction,'backward')
    dummy = source;
    source = target;
    target = dummy;
  end

  % Replace
  if ischar(str)
    for kk=1:numel(source)
        str = strrep(str,source{kk},target{kk});
    end
  elseif iscell(str)
    for jj=1:numel(str)
      str{jj} = ReplaceHtmlEntities(str{jj});
    end
  end
end

end

author: bbci


text:
function ar=v_lpcim2ar(im)
%V_LPCIM2AR Convert impulse response to AR coefs AR=(IM)

%      Copyright (C) Mike Brookes 1997
%      Version: $Id: v_lpcim2ar.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(im);
ar=zeros(nf,p1);
wz=[1 zeros(1,p1-1)];
for k=1:nf
  ar(k,:)=wz/toeplitz(wz,im(k,:)/im(k,1));
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function plot_PointInfo(params)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% ginput(nPoints);

fYear=params.fTstart;
fMc=params.fMc;
fMc=2.0
[fLon0,fLat0]=ginput(1);
hold on;plot(fLon0,fLat0,'kx','MarkerSize',10);

%calculate nearest grid point
mDistance=distance(repmat(fLat0,size(params.mPolygon,1),1),...
    repmat(fLon0,size(params.mPolygon,1),1),...
    params.mPolygon(:,2),params.mPolygon(:,1));
[Xi,Ni]=sort(mDistance);
nCenter=Ni(1)
vPoly0=params.mPolygon(nCenter,:)
hold on;plot(vPoly0(1),vPoly0(2),'r*','MarkerSize',10);

for i=1:size(params.mNumDeclus,2)
    nIndices=params.caNodeIndices{nCenter}(logical(params.mNumDeclus(:,i)));
    nIndices2=params.caNodeIndices{nCenter};
%     nIndices=params.caNodeIndices{nCenter};
    mSample=params.mCatalog(nIndices,:);
    mSample2=params.mCatalog(nIndices2,:);
    vSel=((mSample(:,3)>=fYear) & (mSample(:,6)>=fMc));
    vSel2=((mSample2(:,3)>=fYear) & (mSample2(:,6)>=fMc));
    mSample=mSample(vSel,:);
    mSample2=mSample2(vSel2,:);
    mSample=mSample(1:params.vN,:);
    mSample2=mSample2(1:params.vN,:);
    % hold on;plot(mSample(:,1),mSample(:,2),'w*')

    if i==1
        figure;
    else
        hold on;
    end
i;
    plot(sort(mSample(:,3)),(1:size(mSample,1)),'LineWidth',2);
    if i==1
        hold on;plot(sort(mSample2(:,3)),(1:size(mSample,1)),...
        'r','LineWidth',2);
    end
end

    plotshape;

   function plotshape
        xlabel('Time [Yrs]','FontSize',14);
        ylabel('Cum # of Earthquakes','FontSize',14);
        set(gca,'FontSize',12);
%         set(gcf,'Renderer','zbuffer');
%         shading interp;

%
%
% for i=1:size(params.mNumDeclus,2)
%     vSel=( (params.mCatalog(:,3)>=fYear) & ...
%     (params.mCatalog(:,6)>=fMc) & ...
%     (params.mNumDeclus(:,i)==1) );
%     if i==1
%         figure;
%         plot(params.mCatalog(vSel,3),...
%             cumsum(params.mNumDeclus(vSel,i)),...
%             '-','LineWidth',1,'Color',[.8 .8 .8]);
%     else
%         hold on;
%         plot(params.mCatalog(vSel,3),...
%             cumsum(params.mNumDeclus(vSel,i)),...
%             '-','LineWidth',1,'Color',[.8 .8 .8]);
%     end
% end
%
% set(gca,'FontSize',16)
% xlabel('Years','fontsize',20)
% ylabel('Cum # Earthquakes','fontsize',20)
% % legend('Reasenberg 1985, Xmeff=3.0',...
% %     'Reasenberg (Helmstetter 2007), Xmeff=3.0',...
% %     'Reasenberg 1985, Xmeff=2.5',...
% %     'Reasenberg 1985, Xmeff=2.0',...
% %     'Reasenberg 1985, Xmeff=1.5',...
% %     'Gardner & Knopoff 1974',...
% %     'Utsu 2002',...
% %     'Uhrhammer 1986');

author: CelsoReyes


text:
function files = findAllFiles(subdir, pattern)
files = {};
if ~exist('subdir','var')
    subdir = pwd;
end
if ~exist('pattern','var')
    pattern = '*';
end

if ~ispathvalid_startup(subdir, 'dir')
    fprintf('Warning: folder %s doesn''t exist under %s\n', subdir, pwd);
    return;
end
if subdir(1) == '.'
    return
end

% If current subjdir is in the exclList then go back to curr dir and exit
subdirFullpath = filesepStandard_startup(subdir,'full');
f = dir([subdirFullpath, '*']);
for ii = 1:length(f)
    if f(ii).name(1)=='.'
        continue
    end

    if ~f(ii).isdir
        if strcmp(pattern,'*') || strcmp(f(ii).name, pattern)
        	files{end+1,1} = filesepStandard_startup(sprintf('%s%s%s', subdirFullpath, f(ii).name), 'nameonly');         %#ok<*AGROW>
        end
    else
        files = [files; findAllFiles([subdirFullpath, f(ii).name], pattern)];
    end
end

author: BUNPC


text:
function a = gen_pss_fo_rom_table(f_search_set)
close all;
clear all;
f_search_set = -60e3:5e3:55e3;
[~, td_pss] = pss_gen;

tmp_td_pss = td_pss./137;
fid = fopen('pss_rom_table.txt', 'w');
fprintf(fid, '__constant float2 td_pss[3][137] = { \\ \n');

for i=1:2
    fprintf(fid, '{');
    for j=1:136
        fprintf(fid, '(float2)(%e,%e), ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));
    end
    j = j + 1;
    fprintf(fid, '(float2)(%e,%e)},\\ \n ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));
end
i = 3;
fprintf(fid, '{');
for j=1:136
    fprintf(fid, '(float2)(%e,%e), ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));
end
j = j + 1;
fprintf(fid, '(float2)(%e,%e)}};\n ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));

fclose(fid);

pss_fo_set = pss_fo_set_gen(td_pss, f_search_set);
pss_fo_set = pss_fo_set.';

% figure;
% subplot(2,3,1); plot(real(pss_fo_set(13,:))); hold on;
% subplot(2,3,2); plot(real(pss_fo_set(end,:))); hold on;
% subplot(2,3,3); plot(real(pss_fo_set(1,:))); hold on;
% subplot(2,3,4); plot(real(pss_fo_set(30,:))); hold on;
% subplot(2,3,5); plot(real(pss_fo_set(50,:))); hold on;
% subplot(2,3,6); plot(real(pss_fo_set(70,:))); hold on;

max_val1 = max(max(abs(real(pss_fo_set))));
max_val2 = max(max(abs(imag(pss_fo_set))));
max_val = max(max_val1, max_val2);

enlarge_ratio = ((2^15)-1)/max_val;

enlarge_ratio = floor( log2(enlarge_ratio) );

enlarge_ratio = 2^enlarge_ratio;

pss_fo_set = round(real(pss_fo_set).*enlarge_ratio) + 1i.*round(imag(pss_fo_set).*enlarge_ratio);

% figure;
% subplot(2,3,1); plot(real(pss_fo_set(13,:))); hold on;
% subplot(2,3,2); plot(imag(pss_fo_set(end,:))); hold on;
% subplot(2,3,3); plot(real(pss_fo_set(1,:))); hold on;
% subplot(2,3,4); plot(imag(pss_fo_set(30,:))); hold on;
% subplot(2,3,5); plot(real(pss_fo_set(50,:))); hold on;
% subplot(2,3,6); plot(imag(pss_fo_set(70,:))); hold on;

enlarge_ratio_log2 = log2(enlarge_ratio);

[num_pss, len_pss] = size(pss_fo_set);

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

fprintf(fid, '#define ENLARGE_RATIO (2^%d)\n\n', enlarge_ratio_log2);

fprintf(fid, '__constant short2 coef[%d] = { \\ \n', num_pss*len_pss);

for i=1:(num_pss-1)
    for j=1:len_pss
        fprintf(fid, '(short2)(%d,%d), ', real(pss_fo_set(i,j)), imag(pss_fo_set(i,j)));
    end
    fprintf(fid, '\\ \n');
end
i = num_pss;
for j=1:(len_pss-1)
    fprintf(fid, '(short2)(%d,%d), ', real(pss_fo_set(i,j)), imag(pss_fo_set(i,j)));
end
j=len_pss;
fprintf(fid, '(short2)(%d,%d)};\n\n', real(pss_fo_set(i,j)), imag(pss_fo_set(i,j)));

fclose(fid);

author: JiaoXianjun

repo: rtl-sdr-LTE


text:
function out = linearlcc(in, quantization)
%  @inproceedings{zhang2017learning,
%    title={Learning Deep CNN Denoiser Prior for Image Restoration},
%    author={Zhang, Kai and Zuo, Wangmeng and Gu, Shuhang and Zhang, Lei},
%    booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
%    pages={3929--3938},
%    year={2017},
%  }
%quantization = 0;
% in : uint8; RGB or Bayer pattern [0~255];
% out: double/uint8: RGB [0~255];

[m,n,ch]=size(in);
% if ch==3
%     B=zeros(m,n);
%     B(1:2:m,1:2:n)=in(1:2:m,1:2:n,2);
%     B(2:2:m,2:2:n)=in(2:2:m,2:2:n,2);
%     B(1:2:m,2:2:n)=in(1:2:m,2:2:n,1);
%     B(2:2:m,1:2:n)=in(2:2:m,1:2:n,3);
%     in=B;
%     clear B;
% end

in = double(in);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% function out = lcc1(in)
% returns the color interpolated image using Laplacian
% second-order color correction I
%
% Assumptions : in has following color patterns
%
%  ------------------> grbg
%  |  G R G R ...
%  |  B G B G ...
%  |  G R G R ...
%  |  B G B G ...
%  |  . . . . .

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

inR = in; inG = in; inB = in;
out = in;
outR = inR; outG = inG; outB = inB;

% G channel
for i=4:2:m-2,
    for j=3:2:n-3,
        delta_H = abs(inB(i,j-2)+inB(i,j+2)-2*inB(i,j))+abs(inG(i,j-1)-inG(i,j+1));
        delta_V = abs(inB(i-2,j)+inB(i+2,j)-2*inB(i,j))+abs(inG(i-1,j)-inG(i+1,j));
        if delta_H < delta_V,
            outG(i,j) = 1/2*(inG(i,j-1)+inG(i,j+1))+1/4*(2*inB(i,j)-inB(i,j-2)-inB(i,j+2));
        elseif delta_H > delta_V,
            outG(i,j) = 1/2*(inG(i-1,j)+inG(i+1,j))+1/4*(2*inB(i,j)-inB(i-2,j)-inB(i+2,j));
        else
            outG(i,j) = 1/4*(inG(i,j-1)+inG(i,j+1)+inG(i-1,j)+inG(i+1,j))+1/8*(4*inB(i,j)-inB(i,j-2)-inB(i,j+2)-inB(i-2,j)-inB(i+2,j));
        end
    end
end

for i=3:2:m-3,
    for j=4:2:n-2,
        delta_H = abs(inR(i,j-2)+inR(i,j+2)-2*inR(i,j))+abs(inG(i,j-1)-inG(i,j+1));
        delta_V = abs(inR(i-2,j)+inR(i+2,j)-2*inR(i,j))+abs(inG(i-1,j)-inG(i+1,j));
        if delta_H < delta_V,
            outG(i,j) = 1/2*(inG(i,j-1)+inG(i,j+1))+1/4*(2*inR(i,j)-inR(i,j-2)-inR(i,j+2));
        elseif delta_H > delta_V,
            outG(i,j) = 1/2*(inG(i-1,j)+inG(i+1,j))+1/4*(2*inR(i,j)-inR(i-2,j)-inR(i+2,j));
        else
            outG(i,j) = 1/4*(inG(i,j-1)+inG(i,j+1)+inG(i-1,j)+inG(i+1,j))+1/8*(4*inR(i,j)-inR(i,j-2)-inR(i,j+2)-inR(i-2,j)-inR(i+2,j));
        end
    end
end

% R channel
for i=1:2:m-1,
    outR(i,3:2:n-1) = 1/2*(inR(i,2:2:n-2)+inR(i,4:2:n))+1/4*(2*outG(i,3:2:n-1)-outG(i,2:2:n-2)-outG(i,4:2:n));
end

for i=2:2:m-2,
    outR(i,2:2:n) = 1/2*(inR(i-1,2:2:n)+inR(i+1,2:2:n))+1/4*(2*outG(i,2:2:n)-outG(i-1,2:2:n)-outG(i+1,2:2:n));
end

for i=2:2:m-2,
    for j=3:2:n-1,
        delta_P = abs(inR(i-1,j+1)-inR(i+1,j-1))+abs(2*outG(i,j)-outG(i-1,j+1)-outG(i+1,j-1));
        delta_N = abs(inR(i-1,j-1)-inR(i+1,j+1))+abs(2*outG(i,j)-outG(i-1,j-1)-outG(i+1,j+1));
        if delta_N < delta_P,
            outR(i,j) = 1/2*(inR(i-1,j-1)+inR(i+1,j+1))+1/2*(2*outG(i,j)-outG(i-1,j-1)-outG(i+1,j+1));
        elseif delta_N > delta_P,
            outR(i,j) = 1/2*(inR(i-1,j+1)+inR(i+1,j-1))+1/2*(2*outG(i,j)-outG(i-1,j+1)-outG(i+1,j-1));
        else
            outR(i,j) = 1/4*(inR(i-1,j-1)+inR(i-1,j+1)+inR(i+1,j-1)+inR(i+1,j+1))+1/4*(4*outG(i,j)-outG(i-1,j-1)-outG(i-1,j+1)-outG(i+1,j-1)-outG(i+1,j+1));
        end
    end
end

% B channel
for i=2:2:m,
    outB(i,2:2:n-2) = 1/2*(inB(i,1:2:n-3)+inB(i,3:2:n-1))+1/4*(2*outG(i,2:2:n-2)-outG(i,1:2:n-3)-outG(i,3:2:n-1));
end

for i=3:2:m-1,
    outB(i,1:2:n-1) =  1/2*(inB(i-1,1:2:n-1)+inB(i+1,1:2:n-1))+1/4*(2*outG(i,1:2:n-1)-outG(i-1,1:2:n-1)-outG(i+1,1:2:n-1));
end

for i=3:2:m-1,
    for j=2:2:n-2,
        delta_P = abs(inB(i-1,j+1)-inB(i+1,j-1))+abs(2*outG(i,j)-outG(i-1,j+1)-outG(i+1,j-1));
        delta_N = abs(inB(i-1,j-1)-inB(i+1,j+1))+abs(2*outG(i,j)-outG(i-1,j-1)-outG(i+1,j+1));
        if delta_N < delta_P,
            outB(i,j) = 1/2*(inB(i-1,j-1)+inB(i+1,j+1))+1/2*(2*outG(i,j)-outG(i-1,j-1)-outG(i+1,j+1));
        elseif delta_N > delta_P,
            outB(i,j) = 1/2*(inB(i-1,j+1)+inB(i+1,j-1))+1/2*(2*outG(i,j)-outG(i-1,j+1)-outG(i+1,j-1));
        else
            outB(i,j) = 1/4*(inB(i-1,j-1)+inB(i-1,j+1)+inB(i+1,j-1)+inB(i+1,j+1))+1/4*(4*outG(i,j)-outG(i-1,j-1)-outG(i-1,j+1)-outG(i+1,j-1)-outG(i+1,j+1));
        end
    end
end

out(:,:,1) = outR;
out(:,:,2) = outG;
out(:,:,3) = outB;

if quantization
    out = uint8(out);
end

author: cszn

repo: IRCNN

save_path: github-repos/MATLAB/cszn-IRCNN


text:
function n = dim(A)
%DIM          Dimension of a square matrix
%
%    n = dim(A)
%

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

  if ( length(A.size)>2 ) | ( A.size(1)~=A.size(2) )
    error('function dim called with non-square matrix')
  end;

  n = A.size(1);

repo: OpenMAS


text:
function r8btree_node_add_binary_test ( )

%*****************************************************************************80
%
%% R8BTREE_NODE_ADD_RANDOM_TEST adds random numbers to a BTREE.
%
%  Discussion:
%
%    Because the data is generated randomly, the tree will not be guaranteeed
%    to be well balanced.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 November 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8BTREE_NODE_ADD_RANDOM_TEST\n' );
  fprintf ( 1, '  Use R8BTEE_NODE_ADD to build a BTREE,\n' );
  fprintf ( 1, '  by adding 33 random numbers, one at a time.\n' );
%
%  Initialize the BTREE.
%
  node_num = 0;
  tree = [];
  data_num = 2;
  tree_data = [];
%
%  Generate 33 nodes in [0,1];
%
  for i = 1 : 33

    x = rand ( );
    fx = x * x;
    node_data = [ x, fx ];

    [ node_num, tree, tree_data ] = r8btree_node_add ( node_num, tree, ...
      data_num, tree_data, node_data );

  end
%
%  Print the BTREE.
%
  r8btree_print ( node_num, tree, data_num, tree_data );

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

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function G = gsp_update_coordinates(G, coords)
%GSP_UPDATE_COORDINATES Updates the coordinates of a graph structure
%   Usage: G = gsp_update_coordinates(G, coords);
%
%   Input parameters
%         G      : Graph
%         coords : New coordinates
%
%   Output parameters
%         G      : Output graph
%
%   Update the coordinates of a graph structure
%
%   See also: gsp_compute_coordinates

% Authors : Dion O. E. Tzamarias
% Date    : 20/11/2015

G.coords = coords;
G = rmfield(G,'plotting');
G = gsp_graph_default_plotting_parameters(G);

end

repo: gspbox


text:
%finds best source and distance to the best source
% if distance is negative, the best source cannot be found (for example, because the propagation was stopped before it reached this point)
% Danil Kirsanov, 09/2007

function [source_id, distance] = geodesic_best_source(algorithm, destination)

global geodesic_library;

if nargin == 2
    d = geodesic_convert_surface_points({destination});

    tmp = 1;
    [source_id, tmp1, distance] = calllib(geodesic_library, 'distance_and_source', algorithm.id, d, tmp);
    source_id = source_id + 1;
else                                    %return distances and sources for all vertices
    tmp = libpointer('doublePtrPtr');
%     tmp = libpointer('int32PtrPtr');
     tmp1 = libpointer('longPtrPtr');
%  tmp1 = libpointer('doublePtr');

    [num_vertices, d, s] = calllib(geodesic_library, 'distance_and_source_for_all_vertices', algorithm.id, tmp, tmp1);

    setdatatype(d, 'doublePtr', num_vertices);
    distance = d.Value;
    setdatatype(s, 'longPtr', num_vertices);
    source_id = s.Value + 1;
end

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function h_new = fd1d_heat_explicit ( x_num, x, t, dt, cfl, rhs, bc, h )

%*****************************************************************************80
%
%% FD1D_HEAT_EXPLICIT: Finite difference solution of 1D heat equation.
%
%  Discussion:
%
%    This program takes one time step to solve the 1D heat equation
%    with an explicit method.
%
%    This program solves
%
%      dUdT - k * d2UdX2 = F(X,T)
%
%    over the interval [A,B] with boundary conditions
%
%      U(A,T) = UA(T),
%      U(B,T) = UB(T),
%
%    over the time interval [T0,T1] with initial conditions
%
%      U(X,T0) = U0(X)
%
%    The code uses the finite difference method to approximate the
%    second derivative in space, and an explicit forward Euler approximation
%    to the first derivative in time.
%
%    The finite difference form can be written as
%
%      U(X,T+dt) - U(X,T)                  ( U(X-dx,T) - 2 U(X,T) + U(X+dx,T) )
%      ------------------  = F(X,T) + k *  ------------------------------------
%               dt                                   dx * dx
%
%    or, assuming we have solved for all values of U at time T, we have
%
%      U(X,T+dt) = U(X,T) + cfl * ( U(X-dx,T) - 2 U(X,T) + U(X+dx,T) ) + dt * F(X,T)
%
%    Here "cfl" is the Courant-Friedrichs-Loewy coefficient:
%
%      cfl = k * dt / dx / dx
%
%    In order for accurate results to be computed by this explicit method,
%    the CFL coefficient must be less than 0.5!
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    George Lindfield, John Penny,
%    Numerical Methods Using MATLAB,
%    Second Edition,
%    Prentice Hall, 1999,
%    ISBN: 0-13-012641-1,
%    LC: QA297.P45.
%
%  Parameters:
%
%    Input, integer X_NUM, the number of points to use in the spatial dimension.
%
%    Input, real X(X_NUM,1), the coordinates of the nodes.
%
%    Input, real T, the current time.
%
%    Input, real DT, the size of the time step.
%
%    Input, real CFL, the Courant-Friedrichs-Loewy coefficient,
%    computed by FD1D_HEAT_EXPLICIT_CFL.
%
%    Input, real H(X_NUM,1), the solution at the current time.
%
%    Input, @RHS, the function which evaluates the right hand side.
%
%    Input, @BC, the function which evaluates the boundary conditions.
%
%    Output, real H_NEW(X_NUM,1), the solution at time T+DT.
%
  h_new = zeros(x_num,1);

  L = 1 : x_num - 2;
  C = 2 : x_num - 1;
  R = 3 : x_num;

  f = rhs ( x_num, x, t );

  h_new(C) = h(C) + cfl * ( h(L) - 2.0 * h(C) + h(R) ) + dt * f(C);

  h_new = bc ( x_num, x, t + dt, h_new );

  return
end


text:
% loadeep_avg() - Load EEProbe average data (*.avr).
%
% Usage:
%   >> [EEG] = loadeep_avg(file);
%
% Inputs:
%            filename    - name of EEProbe averaged file, including extension (*.avr)
%
% Outputs:
%   [EEG]                - data structure holding EEG information and other
%                          relevant information.
%
% Author: Maarten-Jan Hoeve, ANT Software, Enschede, The Netherlands, 8 October 2003
%
% See also: eeglab(), pop_loadeep_avg()
%

%123456789012345678901234567890123456789012345678901234567890123456789012

% Copyright (C) 2003 Maarten-Jan Hoeve, m.hoeve@ieee.org
%
% 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 should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% $Log: loadeep_avg.m,v $
% Revision 1.3  2005/07/21 10:12:51  mvelde
% updated information
%
% Revision 1.2  2005/06/08 08:16:37  mvelde
% converted files to unix format
%
% Revision 1.1  2004/11/26 13:22:22  jwiskerke
% Added eeglab to cvs.
%
% Revision 1.3  2003/10/24 13:34:40  Maarten-Jan Hoeve
% Added GNU Licence and updated revision history
%
% Revision 1.1.1.2  2003/10/17 09:55:20  mvelde
% updated: consistent copyrights, arguments/data labels, fixed some typos
%
% Advanced Neuro Technology (ANT) BV, The Netherlands, www.ant-neuro.com / info@ant-neuro.com
%

function r=loadeep_avg(file)

if nargin < 1
	help loadeep;
	return;
end;

% defaults
if ~any(file=='.'), file=[file '.avr']; end
[datdir,name,ext]=fileparts(file);
disp(['Loading file ' file ' ...'])

eeg=read_eep_avr(file);

r.filename=file;
r.totsamples=eeg.npnt;
r.nchannels=eeg.nchan;
r.rate=eeg.rate;

% Create struct for holding channel labels
for i=1:r.nchannels
    chanlocs(i).labels=char(eeg.label(i));
    chanlocs(i).theta=0;
    chanlocs(i).radius=0;
    chanlocs(i).X=0;
    chanlocs(i).Y=0;
    chanlocs(i).Z=0;
    chanlocs(i).sph_theta=0;
    chanlocs(i).sph_phi=0;
    chanlocs(i).sph_radius=0;
end
r.chanlocs=chanlocs;

r.nsmpl=eeg.npnt;
r.time=eeg.time;
r.dat=eeg.data;
r.nsweeps=eeg.nsweeps;     %number of trials averaged
r.xmin=eeg.xmin;
r.xmax=eeg.xmax;
r.variance=eeg.variance;   % variance (nchan x npnt)
r.condlab=eeg.condlab;     % string with condition label
r.condcol=eeg.condcol;     % string with color code for condition
r.trialc=eeg.trialc;       % total number of trial in original data
r.rejtrialc=eeg.rejtrialc; % number of rejected trials

author: PatternRecognition

repo: OpenBMI


text:
dt = 0.02;
sim_t = 20;
x0 = [0;5;0];

params.v = 1; % velocity
params.u_max = 3; % max yaw rate (left)
params.u_min = -3; % min yaw rate (right)

% Obstacle position
params.xo = 5;
params.yo = 4;
% Obstacle radius
params.d = 2;
params.cbf_gamma0 = 1;
% Desired target point
params.xd = 12;
params.yd = 0;

params.clf.rate = 0.5;
params.weight.slack = 10;

params.cbf.rate = 1;

dubins = DubinsCar(params);

odeFun = @dubins.dynamics;
controller = @dubins.ctrlCbfClfQp;
odeSolver = @ode45;

total_k = ceil(sim_t / dt);
x = x0;
t = 0;
% initialize traces.
xs = zeros(total_k, dubins.xdim);
ts = zeros(total_k, 1);
us = zeros(total_k-1, 1);
Vs = zeros(total_k-1, 1);
hs = zeros(total_k-1, 1);
xs(1, :) = x0';
ts(1) = t;
for k = 1:total_k-1
    t
    % Determine control input.
    % dV_hat: analytic Vdot based on model.
    [u, slack, h, V] = controller(x);
    us(k, :) = u';
    hs(k) = h;
    Vs(k) = V;

    % Run one time step propagation.
    [ts_temp, xs_temp] = odeSolver(@(t, s) odeFun(t, s, u), [t t+dt], x);
    x = xs_temp(end, :)';

    xs(k+1, :) = x';
    ts(k+1) = ts_temp(end);
    t = t + dt;
end

plot_results(ts, xs, us, hs, [params.xo;params.yo], params.d)

function plot_results(t, xs, us, hs, p_o, r_o)

figure
subplot(3,1,1)
plot(t, xs(:,1))
xlabel('t')
ylabel('x [m]')

subplot(3,1,2)
plot(t, xs(:,2))
xlabel('t')
ylabel('y [m]')

subplot(3,1,3)
plot(t, xs(:,3))
xlabel('t')
ylabel('theta [rad]')

figure
plot(t(1:end-1), us)
xlabel('t')
ylabel('u [rad/s]')

lim_min = min(min(xs(:, 1)), min(xs(:, 2)));
lim_max = max(max(xs(:, 1)), max(xs(:, 2)));
lim_min = min([lim_min, p_o(1)-r_o, p_o(2)-r_o]);
lim_max = max([lim_max, p_o(1)+r_o, p_o(2)+r_o]);

figure
plot(xs(:, 1), xs(:, 2));
draw_circle(p_o, r_o);

xlim([lim_min, lim_max]);
ylim([lim_min, lim_max]);
xlabel('x [m]')
ylabel('y [m]')

figure
plot(t(1:end-1), hs)
xlabel('t')
ylabel('cbf h(s)');

end

function h = draw_circle(center,r)
hold on
th = 0:pi/50:2*pi;
xunit = r * cos(th) + center(1);
yunit = r * sin(th) + center(2);
h = plot(xunit, yunit);
hold off

end

author: HybridRobotics

repo: CBF-CLF-Helper


text:
% Copyright 2017 Lime Microsystems Ltd.
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%    http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% just for fun now, uses compressed ASCII (6 bit) and BCH(15,11) FEC
% Note real encoding uses Viterbi over several radio frames!  Viterbi is more efficient than block coding.
% also have not muxed DPCCH into DPDCH
function [y,din,dout]=WCDMADLtxtMsgWrite2( txt, bitsPerFrame )
	m=4;
	n=2^m-1; % also from bchpoly (1)
	k=11; % from bchpoly (2) % 21 maybe better than 16, as gives 14 chars instead of 10, with t=2 bit error correct
	t=1; % from bchpoly (3)
	maxMsg=floor(k*floor(bitsPerFrame/n)/6);
	qpsk=[1+i,1-i,-1+i,-1-i];
	% if message too short, add ' 's
	if length(txt)<maxMsg
		chars=maxMsg-length(txt);
		tmpTxt=[txt,repmat(32,1,chars)];
	% if message too long, cut
	elseif length(txt)>maxMsg
		tmpTxt=txt(1:maxMsg);
	else % length(txt)==maxMsg
		tmpTxt=txt;
	end
	pad1=randint(1,(k*ceil(maxMsg*6/k)-maxMsg*6)); % unused bits prior to encoding
	pad2=randint(1,(bitsPerFrame-n*floor(bitsPerFrame/n))); % unused part of encoded message, pad with random numbers 26
	printf('WCDMAtxtMsgULWrite[%s],BCH(%g,%g)\n', tmpTxt, n, k );
	din=[reshape(de2bi(ASCII6enc(tmpTxt),6,2,"left-msb")',1,[])];
  data=[din,pad1]; % pad to fit FEC
	% convert to ?xk matrix prior to encoding
	data=reshape(data,length(data)/k,k);
	data=bchenco(data,n,k);
	% convert back to linear matrix and pad to bits per frame
	l=size(data);
	data=reshape(data,1,n*l(1));
	idx=[data,pad2]; % pad unused bits with random data
	% interleave to reduce effect of burst errors
%	idx=reshape(reshape(idx,15,40)',1,600); % was 15 10 150
  dout=matintrlv(idx,15,40);
	idx=sum( ( (reshape(dout,2,(length(dout)/2))').*[2,1])' )+1;
	y=qpsk(idx); % convert to qpsk
end

author: myriadrf


text:
function covering = getBestCovering(seg, regions, spseg, do_approx)
% covering = getBestCovering(seg, regions, spseg)
%
% Computes covering of seg by regions, where seg is an image with indices
% denoting a partitioning and regions is a cell array containing indices
% into spseg specifying image regions.
%
% covering.pix = covering weighted by pixel area of seg regions
% covering.unweighted = average covering (unweighted)

if ~exist('do_approx', 'var')
    do_approx = 0;
end

covering.maxov = zeros(max(seg(:)), 1);
covering.maxr = zeros(max(seg(:)), 1);
covering.area = 0;
covering.pix = 0;
covering.unweighted = 0;

rmap = false(max(spseg(:)), 1);
if do_approx % approximates seg with spseg
    s = regionprops(spseg, 'Area');
    area = cat(1, s.Area);  area = area/sum(area);
    lab = transferRegionLabels(seg, spseg);
    for r1 = 1:max(lab)
        region1 = find(lab==r1);
        maxov = 0;
        maxr = 0;
        for r2 = 1:numel(regions)
            ov = regionOverlap(region1, regions{r2}, area);
            if ov > maxov
                maxov = ov;
                maxr = r2;
            end
        end
        if maxr~=0
            rmap(:) = false;
            rmap(regions{maxr}) = true;
            region1 = seg==r1;
            region2 = rmap(spseg);
            ov = sum(region1(:) & region2(:)) / sum(region1(:) | region2(:));
            covering.maxov(r1) = ov;
            covering.pix = covering.pix + ov * mean(region1(:));
            covering.unweighted = covering.unweighted + ov / max(seg(:));
            covering.area (r1) = mean(region1(:));
            covering.maxr(r1) = maxr;
        end

    end
else
    stats = regionprops(spseg, 'Area');
    area = cat(1, stats.Area);
    seg(seg<0) = 0;
    stats = regionprops(seg, 'Area');
    segarea = cat(1, stats.Area);
    nsp = numel(area);
    nseg = max(seg(:));
    count = zeros(nsp, nseg);
    ind = find((spseg > 0) & (seg>0));
    for k = ind(:)'
       s1 = spseg(k);
       s2 = seg(k);
       count(s1, s2) = count(s1, s2)+1;
    end
    for r1 = 1:nseg
        maxr = 0;
        maxov = 0;
        for r2 = 1:numel(regions)
	    region = regions{r2}; region = region(region<nsp);
            intersection = sum(count(region, r1));
            union = sum(area(region)) + segarea(r1) - intersection;
            ov = intersection / union;
            if ov > maxov
                maxr = r2;
                maxov = ov;
            end
        end
        covering.maxr(r1) = maxr;
        covering.regions{r1} = regions{maxr};
        covering.maxov(r1) = maxov;
        covering.area(r1) = segarea(r1)/numel(seg);
        covering.pix = covering.pix + segarea(r1)*maxov/sum(segarea);
        covering.unweighted = covering.unweighted + maxov / nseg;
    end

%     rmap = false(max(spseg(:)), 1);
%     for r1 = 1:max(seg(:))
%         region1 = seg==r1;
%         maxov = 0;
%         for r2 = 1:numel(regions)
%             rmap(:) = false;
%             rmap(regions{r2}) = true;
%             region2 = rmap(spseg);
%             ov = sum(region1(:) & region2(:)) / sum(region1(:) | region2(:));
%             if ov > maxov
%                 maxov = ov;
%             end
%         end
%         covering = covering + mean(region1(:))*maxov;
%     end
end

author: Cloud-CV

repo: object-proposals


text:
function [e1,e2,l1,l2] = perform_tensor_eigendecomposition(e1,e2,l1,l2)

% perform_tensor_eigendecomposition - decompose a tensor field
%
% analysis:
%   [e1,e2,l1,l2] = perform_tensor_eigendecomposition(T);
% synthesis:
%   T = perform_tensor_eigendecomposition(e1,e2,l1,l2);
%
%   Copyright (c) 2007 Gabriel Peyre

if nargin==1
    T = e1;
    n = size(T,1);
    if size(T,3)==3 && size(T,4)==1
        T = cat(3, T(:,:,1), T(:,:,3), T(:,:,3), T(:,:,2)); T = reshape(T, [n n 2 2]);
    end
    [e1,e2,l1,l2] = perform_tensor_decomp(T);
elseif nargin==4
    H = perform_tensor_recomp(e1,e2,l1,l2);
    e1 = cat(3, H(:,:,1,1), H(:,:,2,2), H(:,:,2,1) );
else
    error('1 or 4 arguments');
end

author: gpeyre

repo: matlab-toolboxes


text:
function euler = quatern2euler(q)
%QUATERN2EULER Converts a quaternion orientation to ZYX Euler angles
%
%   q = quatern2euler(q)
%
%   Converts a quaternion orientation to ZYX Euler angles where phi is a
%   rotation around X, theta around Y and psi around Z.
%
%   For more information see:
%   http://www.x-io.co.uk/node/8#quaternions
%
%	Date          Author          Notes
%	27/09/2011    SOH Madgwick    Initial release

    R(1,1,:) = 2.*q(:,1).^2-1+2.*q(:,2).^2;
    R(2,1,:) = 2.*(q(:,2).*q(:,3)-q(:,1).*q(:,4));
    R(3,1,:) = 2.*(q(:,2).*q(:,4)+q(:,1).*q(:,3));
    R(3,2,:) = 2.*(q(:,3).*q(:,4)-q(:,1).*q(:,2));
    R(3,3,:) = 2.*q(:,1).^2-1+2.*q(:,4).^2;

    phi = atan2(R(3,2,:), R(3,3,:) );
    theta = -atan(R(3,1,:) ./ sqrt(1-R(3,1,:).^2) );
    psi = atan2(R(2,1,:), R(1,1,:) );

    euler = [phi(1,:)' theta(1,:)' psi(1,:)'];
end

author: xioTechnologies

repo: Oscillatory-Motion-Tracking-With-x-IMU


text:
%TROT2 SE2 rotation matrix
%
% T = TROT2(THETA) is a homogeneous transformation (3x3) representing a rotation
% of THETA radians.
%
% T = TROT2(THETA, 'deg') as above but THETA is in degrees.
%
% Notes::
% - Translational component is zero.
%
% See also ROT2, TRANSL2, TROTX, TROTY, TROTZ.

% Copyright (C) 1993-2015, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

function T = trot2(t, varargin)
	T = [rot2(t, varargin{:}) [0 0]'; 0 0 1];

author: Allopart

repo: rbpf-gmapping


text:
%  Internal Function
%
%

author: jmaih


text:
function cx = cheby_u_polynomial ( n, x )

%*****************************************************************************80
%
%% CHEBY_U_POLYNOMIAL evaluates the Chebyshev polynomials of the second kind.
%
%  Differential equation:
%
%    (1-X*X) Y'' - 3 X Y' + N (N+2) Y = 0
%
%  First terms:
%
%    U(0)(X) =   1
%    U(1)(X) =   2 X
%    U(2)(X) =   4 X^2 -   1
%    U(3)(X) =   8 X^3 -   4 X
%    U(4)(X) =  16 X^4 -  12 X^2 +  1
%    U(5)(X) =  32 X^5 -  32 X^3 +  6 X
%    U(6)(X) =  64 X^6 -  80 X^4 + 24 X^2 - 1
%    U(7)(X) = 128 X^7 - 192 X^5 + 80 X^3 - 8X
%
%  Recursion:
%
%    U(0)(X) = 1,
%    U(1)(X) = 2 * X,
%    U(N)(X) = 2 * X * U(N-1)(X) - U(N-2)(X)
%
%  Norm:
%
%    Integral ( -1 <= X <= 1 ) ( 1 - X^2 ) * U(N)(X)^2 dX = PI/2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 July 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the highest polynomial to compute.
%
%    Input, real X, the point at which the polynomials are to be computed.
%
%    Output, real CX(1:N+1), the values of the N+1 Chebyshev polynomials.
%
  cx = zeros ( n + 1, 1 );

  if ( n < 0 )
    cx = [];
    return
  end

  cx(1) = 1.0;

  if ( n < 1 )
    return
  end

  cx(2) = 2.0 * x;

  for i = 2 : n
    cx(i+1) = 2.0 * x * cx(i) - cx(i-1);
  end

  return
end


text:
function plot_R_cov(Sigma_R_stat, cov_R, Rs)
Lies = dcm2Lie(Rs).';
mean_Lie = mean(Lies, 2);
colors = linspecer(3);
subplot(2, 2, 1);
plot_cov_linestyle(Sigma_R_stat, {'--', 3, colors(1, :)}, cov_R, {'-', 2, colors(3, :)}, Lies, mean_Lie, '.', 1, 2, 3, 10.5);
xlabel('$\xi_1$', 'Interpreter', 'LaTeX', 'FontSize', 15);
ylabel('$\xi_2$', 'Interpreter', 'LaTeX', 'FontSize', 15);

subplot(2, 2, 2);
plot_cov_linestyle(Sigma_R_stat, {'--', 3, colors(1, :)}, cov_R, {'-', 2, colors(3, :)}, Lies, mean_Lie, '.', 1, 3, 3, 10.5);
xlabel('$\xi_1$', 'Interpreter', 'LaTeX', 'FontSize', 15);
ylabel('$\xi_3$', 'Interpreter', 'LaTeX', 'FontSize', 15);

subplot(2, 2, 4);
plot_cov_linestyle(Sigma_R_stat, {'--', 3, colors(1, :)}, cov_R, {'-', 2, colors(3, :)}, Lies, mean_Lie, '.', 2, 3, 3, 10.5);
xlabel('$\xi_2$', 'Interpreter', 'LaTeX', 'FontSize', 15);
ylabel('$\xi_3$', 'Interpreter', 'LaTeX', 'FontSize', 15);

legend({'Stat Covariance', 'Data Points', 'Nguyen et al. Covariance'}, 'Interpreter', 'LaTeX', 'FontSize', 15);

Sigma_Lie_stat = covx(Lies.', Lies.')
end

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
function browse_topoplotER(cfg, data)

% BROWSE_TOPOPLOTER is a simple helper function for FT_DATABROWSER and shows
% the average topography of the selected data.
%
% See also BROWSE_MOVIEPLOTER, BROWSE_TOPOPLOTER, BROWSE_MULTIPLOTER, BROWSE_TOPOPLOTVAR, BROWSE_SIMPLEFFT

% Copyright (C) 2009, Robert Oostenveld

% convert to an ERP
timelock = ft_timelockanalysis([], data);

default             = [];
default.xlim        = [min(timelock.time) max(timelock.time)];
default.marker      = 'on';
default.interactive = 'no';
cfg = mergeconfig(cfg, default);

figure;
ft_topoplotER(cfg, timelock);

author: spm


text:
function addCERRFigureHandle(handle, name)
%function addCERRFigureHandle(handle, name)
%after creating a new figure within the context of CERR, this function should be called
%so that the program can close the figure if CERR is shut down entirely.
%The handle can also be referenced from any function using global CERRHandlesC.
%-Note that the CloseRequestFcn is modified.  Any changes made to the CloseRequestFcn after this function
% is called should include a call to removeCERRFigureHandle.
%-'name' should be the same as the tag for the figure.
%
% 15 Aug 02, V H Clark
%LM  28 Oct 02, JOD
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

global stateS

CERRHandlesC = stateS.CERRHandlesC

if isfield(CERRHandlesC{end}, name)
  handleLocation = getfield(CERRHandlesC{end}, name);
else
  handleLocation = length(CERRHandlesC);
  CERRHandlesC{end+1} = CERRHandlesC{end}; %move the index structure cell
  CERRHandlesC{end} = setfield(CERRHandlesC{end}, name, handleLocation);
end

CERRHandlesC{handleLocation} = handle;

% fix the figure to call 'removeCERRFigureHandle' on close.  If a CloseRequestFcn is changed in the code,
% it should include a call to 'removeCERRFigureHandle'.
prevCRF = get(handle, 'CloseRequestFcn');
set(handle, 'CloseRequestFcn', [prevCRF ', removeCERRFigureHandle(''' name ''')']);

stateS.CERRHandlesC = CERRHandlesC;

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR