text:
close all; clear all; clc;

[FileName,PathName] = uigetfile({'.wav'}, 'Select cover audio:');
[file.path,file.name,file.ext] = fileparts([PathName FileName]);

wavin = [PathName FileName];
wavout = [file.path '\' file.name '_stego' file.ext];

password = 'mypassword123';

file = 'text.txt';
fid  = fopen(file, 'r');
text = fread(fid,'*char')';
fclose(fid);

lsb_enc(wavin, wavout, text, password);

author: ktekeli

repo: audio-steganography-algorithms


text:
function [u,options,dim] = addConfounds2dcm(X0,u,options,dim)
% this function modifies the i/o of DCM inversion to cope with confounds
% function [u,options,dim] = addConfounds2dcm(X0,u,options,dim)
% This function adds in a dummy input that indexes time, which is used in
% the observation function of DCM to extract the appropriate line of the
% confounds matrix. Required additional parameters and indexes are passed
% to the evolution/observation functions through the inF/inG structures.
% IN:
%   - X0: n_tXn_p0 matrix of confounds (n_t is the nmber of time samples
%   in the data)
%   - u/options/dim: usual input to VBA inversion of a DCM.
% OUT:
%   - u/options/dim: input to VBA inversion of a DCM (augmented with
%   confounds).

if ~isempty(X0)
    nreg = size(options.inF.A,1);
    nu = size(u,1);
    [n_t,n_p0] = size(X0);

    S0 = options.priors.SigmaPhi;
    options.priors.muPhi = [options.priors.muPhi;zeros(nreg*n_p0,1)];
    options.priors.SigmaPhi = eye(dim.n_phi+nreg*n_p0);
    options.priors.SigmaPhi(1:dim.n_phi,1:dim.n_phi) = S0;
    options.inF.confounds.indu = 1:nu;
    options.inG.confounds.indu = 1:nu;
    options.inG.confounds.indt = nu+1;
    options.inG.confounds.X0 = X0;
    options.inG.confounds.indp = dim.n_phi+1:dim.n_phi+nreg*n_p0;
    ux0 = 1:n_t;
    if options.microU && ~isequal(options.decim,1)
        ux0 = kron(ux0,ones(1,options.decim));
    end
    u = [u;[ux0,zeros(size(u,2)-size(ux0,2))]];
    dim.n_phi = dim.n_phi + nreg*n_p0;
end

author: MBB-team

repo: VBA-toolbox


text:
function filum_test03 ( )

%*****************************************************************************80
%
%% TEST03 tests FILE_COLUMN_COUNT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 June 2007
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST03\n' );
  fprintf ( 1, '  FILE_COLUMN_COUNT counts the columns in a file.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  It is assumed that the file contains a number of lines,\n' );
  fprintf ( 1, '  with each line containing the same number of words.\n' );
  fprintf ( 1, '  The task is to determine the number of words in a line,\n' );
  fprintf ( 1, '  that is, the number of "columns" of text.\n' );

  filename = 'filum_prb_4by5.txt';

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Examining the file "%s"\n', filename );

  column_num = file_column_count ( filename );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of columns = %d\n', column_num );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function tag = gettag(item)

% function tag = gettag(item)
% Return the tag of the input item.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: gettag.m 1716 2008-05-23 08:18:45Z volkmar $

rev = '$Rev: 1716 $'; %#ok

tag = item.tag;

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
% Returns a sampling grid for an image (using overlapping window)
%   GRID = SAMPLING_GRID(IMG_SIZE, WINDOW, OVERLAP, BORDER, SCALE)
function grid = sampling_grid(img_size, window, overlap, border, scale)

if nargin < 5
    scale = 1;
end

if nargin < 4
    border = [0 0];
end

if nargin < 3
    overlap = [0 0];
end

% Scale all grid parameters
window = window * scale;
overlap = overlap * scale;
border = border * scale;

% Create sampling grid for overlapping window
index = reshape(1:prod(img_size), img_size);
grid = index(1:window(1), 1:window(2)) - 1;

% Compute offsets for grid's displacement.
skip = window - overlap; % for small overlaps
offset = index(1+border(1):skip(1):img_size(1)-window(1)+1-border(1), ...
               1+border(2):skip(2):img_size(2)-window(2)+1-border(2));
offset = reshape(offset, [1 1 numel(offset)]);

% Prepare 3D grid - should be used as: sampled_img = img(grid);
grid = repmat(grid, [1 1 numel(offset)]) + repmat(offset, [window 1]);

author: thomas-koehler

repo: SupER


text:
function alpha = p03_alpha ( )

%*****************************************************************************80
%
%% P03_ALPHA returns ALPHA for problem 3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 July 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real ALPHA, the value of ALPHA.
%
  alpha = 2.0;

  return
end


text:
function test_suite = test_interval_neighborhood()
% tests for cosmo_interval_neighborhood
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #
    try % assignment of 'localfunctions' is necessary in Matlab >= 2016
        test_functions=localfunctions();
    catch % no problem; early Matlab versions can use initTestSuite fine
    end
    initTestSuite;

function test_interval_neighborhood_basis()
    ds_full=cosmo_synthetic_dataset('type','meeg','size','big');
    ds_full=cosmo_slice(ds_full,ds_full.fa.chan<3,2);
    ds_full=cosmo_dim_prune(ds_full);

    sliceargs={1:7,[1 4 7],[2 6]};
    radii=[0 1 2];
    for k=1:numel(sliceargs)
        slicearg=sliceargs{k};
        narg=numel(slicearg);

        ds=cosmo_slice(ds_full,cosmo_match(ds_full.fa.time,slicearg),2);
        ds=cosmo_dim_prune(ds);
        nf=size(ds.samples,2);
        ds=cosmo_slice(ds,randperm(nf),2);

        for j=1:numel(radii)
            ds=cosmo_slice(ds,randperm(nf),2);
            fa_time=ds.fa.time;

            radius=radii(j);

            nh=cosmo_interval_neighborhood(ds,'time','radius',radius);
            assert(numel(nh.neighbors)==narg);
            assertEqual(nh.fa.time,1:narg);
            assertEqual(nh.a.fdim.values,...
                            {ds_full.a.fdim.values{2}(slicearg)});

            assertEqual(nh.origin.a.fdim,ds.a.fdim);
            assertEqual(nh.origin.fa,ds.fa);

            for m=1:narg
                msk=m-radius<=fa_time & ...
                        fa_time <= m+radius;
                assertEqual(find(msk),nh.neighbors{m});
            end

            % should properly deal with permutations
            ds2=cosmo_slice(ds,randperm(nf),2);
            ds2.a.fdim.values=cellfun(@transpose,ds2.a.fdim.values,...
                                        'UniformOutput',false)';
            nh2=cosmo_interval_neighborhood(ds2,'time','radius',radius);
            assertEqual(nh.fa,nh2.fa);
            assertEqual(nh.a,nh2.a);
            mp=cosmo_align(ds.fa,ds2.fa);
            for m=1:numel(nh.neighbors)
                assertEqual(sort(mp(nh2.neighbors{m})),nh.neighbors{m});
            end
        end
    end

    % test exceptionsclc
    aet=@(x,i)assertExceptionThrown(@()...
                        cosmo_interval_neighborhood(x{:}),i);

    aet({ds},'');
    aet({ds,'time'},'');
    aet({ds,'x',2},'');
    aet({ds,'time',-1},'');
    aet({ds,'time',[2 3]},'');
    aet({ds,'time','radius'},'');
    aet({ds,'time','radius',-1},'');

function test_interval_neighborhood_sa()
    ds=cosmo_synthetic_dataset('type','meeg');
    ds_tr=cosmo_dim_transpose(ds,'time');
    ds_tr=cosmo_slice(ds_tr,randperm(12));
    for radius=0:1
        nbrhood=cosmo_interval_neighborhood(ds_tr,'time','radius',radius);
        unq_time=unique(ds_tr.sa.time);
        for k=1:numel(unq_time)
            msk=abs(ds_tr.sa.time-unq_time(k))<=radius;
            assertEqual(nbrhood.neighbors{k},find(msk)');
        end
    end

function test_interval_neighborhood_fa()
    ds=cosmo_synthetic_dataset('type','meeg','size','big');
    nf=size(ds.samples,2);
    rp=randperm(nf);
    dsp=cosmo_slice(ds,rp,2);

    for radius=0:10
        nhp=cosmo_interval_neighborhood(dsp,'time','radius',radius);
        assertEqual(nhp.a.fdim.values{1},ds.a.fdim.values{2});

        for k=1:numel(nhp.neighbors)
            idx=find(abs(nhp.fa.time(k)-dsp.fa.time)<=radius);
            assertEqual(nhp.neighbors{k},idx);
        end
    end

function test_sparse_interval_neighborhood
    ds=cosmo_synthetic_dataset('size','big');

    % make some holes
    ds=cosmo_slice(ds,ds.fa.i>=4 & ds.fa.i<=16,2);
    ds=cosmo_slice(ds,mod(ds.fa.i,3)<=1,2);

    for radius=0:5
        nh=cosmo_interval_neighborhood(ds,'i','radius',radius);

        n_nbrs=numel(nh.neighbors);

        assert(n_nbrs==numel(ds.a.fdim.values{1}));
        for j=1:n_nbrs
            nbrs=nh.neighbors{j};

            idx=find(j-radius <= ds.fa.i & ds.fa.i <= j+radius);
            assertEqual(nbrs(:),idx(:),sprintf(['not equal with '...
                                        'radius=%d, index=%d'],...
                                        radius,j))
        end
    end

author: CoSMoMVPA

repo: CoSMoMVPA

save_path: github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA


text:
function [ a, seed ] = r8mat_uniform ( m, n, b, c, seed )

%*****************************************************************************80
%
%% R8MAT_UNIFORM returns a scaled pseudorandom R8MAT.
%
%  Modified:
%
%    21 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Paul Bratley, Bennett Fox, Linus Schrage,
%    A Guide to Simulation,
%    Springer Verlag, pages 201-202, 1983.
%
%    Bennett Fox,
%    Algorithm 647:
%    Implementation and Relative Efficiency of Quasirandom
%    Sequence Generators,
%    ACM Transactions on Mathematical Software,
%    Volume 12, Number 4, pages 362-376, 1986.
%
%    Peter Lewis, Allen Goodman, James Miller,
%    A Pseudo-Random Number Generator for the System/360,
%    IBM Systems Journal,
%    Volume 8, pages 136-143, 1969.
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns in the array.
%
%    Input, real B, C, the range of the pseudorandom values.
%
%    Input, integer SEED, the integer "seed" used to generate
%    the output random number.
%
%    Output, real A(M,N), an array of random values between 0 and 1.
%
%    Output, integer SEED, the updated seed.  This would
%    normally be used as the input seed on the next call.
%
  if ( seed == 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_UNIFORM - Fatal error!\n' );
    fprintf ( 1, '  Input SEED = 0!\n' );
    error ( 'R8MAT_UNIFORM - Fatal error!' );
  end

  for j = 1 : n
    for i = 1 : m

      seed = floor ( seed );

      seed = mod ( seed, 2147483647 );

      if ( seed < 0 )
        seed = seed + 2147483647;
      end

      k = floor ( seed / 127773 );

      seed = 16807 * ( seed - k * 127773 ) - k * 2836;

      if ( seed < 0 )
        seed = seed + 2147483647;
      end

      a(i,j) = b + ( c - b ) * seed * 4.656612875E-10;

    end
  end


text:
function ray = bisector(varargin)
%BISECTOR Return the bisector of two lines, or 3 points
%
%   RAY = bisector(LINE1, LINE2);
%   create the bisector of the two lines, given as [x0 y0 dx dy].
%
%   RAY = bisector(P1, P2, P3);
%   create the bisector of lines (P2 P1) and (P2 P3).
%
%   The result has the form [x0 y0 dx dy], with [x0 y0] being the origin
%   point ans [dx dy] being the direction vector, normalized to have unit
%   norm.
%
%   See also:
%   lines2d, rays2d
%
%   ---------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% created the 31/10/2003.
% Copyright 2010 INRA - Cepia Software Platform.

%   HISTORY
%   2005-07-07 add bisector of 3 points
%   2010-11-05 ode cleanup

if length(varargin)==2
    % two lines
    line1 = varargin{1};
    line2 = varargin{2};

    point = intersectLines(line1, line2);

elseif length(varargin)==3
    % three points
    p1 = varargin{1};
    p2 = varargin{2};
    p3 = varargin{3};

    line1 = createLine(p2, p1);
    line2 = createLine(p2, p3);
    point = p2;

elseif length(varargin)==1
    % three points, given in one array
    var = varargin{1};
    p1 = var(1, :);
    p2 = var(2, :);
    p3 = var(3, :);

    line1 = createLine(p2, p1);
    line2 = createLine(p2, p3);
    point = p2;
end

% compute line angles
a1 = lineAngle(line1);
a2 = lineAngle(line2);

% compute bisector angle (angle of first line + half angle between lines)
angle = mod(a1 + mod(a2-a1+2*pi, 2*pi)/2, pi*2);

% create the resulting ray
ray = [point cos(angle) sin(angle)];

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
function a = i4_to_a ( i )

%*****************************************************************************80
%
%% I4_TO_A returns the I-th alphabetic character.
%
%  Example:
%
%    I   A
%
%   -8  ' '
%    0  ' '
%    1  'A'
%    2  'B'
%   ..
%   26  'Z'
%   27  'a'
%   52  'z'
%   53  ' '
%   99  ' '
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer I, the index of the letter to be returned.
%    0 is a space;
%    1 through 26 requests 'A' through 'Z', (ASCII 65:90);
%    27 through 52 requests 'a' through 'z', (ASCII 97:122);
%
%    Output, character A, the requested alphabetic letter.
%
  if ( i <= 0 )
    a = ' ';
  elseif ( 1 <= i && i <= 26 )
    a = 'A' + i - 1;
  elseif ( 27 <= i && i <= 52 )
    a = 'a' + i - 27;
  else
    a = ' ';
  end

  return
end


text:
function pri=getcodepri(sys,code,opt) %#ok

global glc

codepris=glc.codepris;
switch sys
    case glc.SYS_GPS,i=1;optstr='-GL';%#ok
    case glc.SYS_GLO,i=2;optstr='-RL';%#ok
    case glc.SYS_GAL,i=3;optstr='-EL';%#ok
    case glc.SYS_BDS,i=4;optstr='-BL';%#ok
    case glc.SYS_QZS,i=5;optstr='-QL';%#ok
end

pri=0;

[obs,j]=code2obs(code,sys);
if strcmp(obs,'')||j==0,return;end
obs=char(obs);

ind=strfind(char(codepris(i,j)),obs(2)); %i:sys j:freq
if any(ind)
    pri=15-ind;
else
    pri=0;
end

return

repo: GINav


text:
function [node,face,elem]=meshcylinders(c0, v, len, varargin)
%
% [node,face]=meshcylinders(c0, v, len, r,tsize,maxvol,ndiv)
%    or
% [node,face,elem]=meshcylinders(c0, v, len, r, tsize,maxvol,ndiv)
% [nplc,fplc]=meshcylinders(c0, v, len,r,0,0,ndiv);
%
% create the surface and (optionally) tetrahedral mesh of a 3D cylinder
%
% author: Qianqian Fang, <q.fang at neu.edu>
%
% input:
%   c0, cylinder list axis's starting point
%   v: directional vector of the cylinder
%   len: a scalar or a vector denoting the length of each
%        cylinder segment along the direction of v
%   tsize, maxvol, ndiv: please see the help for meshacylinder for details
%
% output:
%   node, face, elem: please see the help for meshacylinder for details
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

len=cumsum(len);
[ncyl,fcyl]=meshacylinder(c0,c0+v*len(1),varargin{:});

if(nargout==2 && length(len)==1)
    node=ncyl;
    face=fcyl;
    return;
end

for i=2:length(len)
   [ncyl1,fcyl1]=meshacylinder(c0+v*len(i-1),c0+v*len(i),varargin{:});
   if(iscell(fcyl1))
       fcyl1=cellfun(@(x) {x{1}+size(ncyl,1),x{2}}, fcyl1, 'UniformOutput', false);
       if(i==1)
           fcyl1=fcyl1(1:end-1);
       else
           fcyl1={fcyl1{1:end-2},fcyl1{end}};
       end
       fcyl=[fcyl(:)' fcyl1(:)'];
   else
       fcyl1=fcyl1+size(ncyl,1);
       fcyl=[fcyl; fcyl1];
   end
   ncyl=[ncyl; ncyl1];
end

[ncyl,I,J]=unique(round(ncyl*1e10),'rows');
ncyl=ncyl*1e-10;
if(iscell(fcyl))
    fcyl=cellfun(@(x) {J(x{1})',x{2}}, fcyl, 'UniformOutput', false);
else
    fcyl=J(fcyl);
end

tsize=varargin{2};
maxvol=varargin{3};

if(nargout==2 && tsize==0.0 && maxvol==0.0)
    node=ncyl;
    face=fcyl;
    return;
end
if(nargin==3)
    tsize=len/10;
end
if(nargin<5)
    maxvol=tsize*tsize*tsize;
end

centroid=cumsum([0 len(1:end-1)])+len/2;   % define the centroids of each cylinder segment
seeds=repmat(c0(:)',length(len),1)+repmat(v(:)',length(len),1).*repmat(centroid(:),1,3);
[node,elem,face]=surf2mesh(ncyl,fcyl,[],[],1,maxvol,seeds,[],0);

author: fangq


text:
% Copyright (C) 2014-2017 Colin B. Macdonald
%
% This file is part of OctSymPy.
%
% OctSymPy is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published
% by the Free Software Foundation; either version 3 of the License,
% or (at your option) any later version.
%
% This software 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 software; see the file COPYING.
% If not, see <http://www.gnu.org/licenses/>.

function extract_tests_for_matlab()

  dirs = {'.', '@sym', '@symfun', '@double', '@logical'};
  dirstr = {'', 'sym', 'symfun', 'double', 'logical'};

  outdir = 'tests_matlab';

  for j=1:length(dirs)
    files = dir(dirs{j});

    for i=1:length(files)
      mfile = files(i).name;
      if ( (~files(i).isdir) && strcmp(mfile(end-1:end), '.m') )
        %str = mfile(1:end-2);
        fprintf('>>> Looking for tests in: %s', mfile);
        tf = proc_file(dirs{j}, dirstr{j}, mfile, outdir);
        if tf
          fprintf('\t[done]\n');
        else
          fprintf('\t[no tests]\n');
        end
      end
    end
  end
endfunction

function r = proc_file(base, basestr, nm, outdir)

  %nm = 'symfun.m';
  %base = '@symfun';

  name_no_m = nm(1:end-2);
  in_name = [base '/' nm];
  body = __extract_test_code(in_name);

  r = true;
  if isempty(body)
    r = false;
    return
  end

  %% process it a bit
  % Chop it up into blocks for evaluation.
  %__lineidx = find (__body == "\n");
  %__blockidx = __lineidx(find (! isspace (__body(__lineidx+1))))+1;

  nl = sprintf('\n');

  % add an extra newline to ensure final line has one
  body = [body nl];

  ddot = 'fprintf(''.'')';
  dskip = 'fprintf(''s'')';
  body = regexprep(body, '^test\n', [nl ddot nl '%test' nl], 'lineanchors');
  body = regexprep(body, '^test ', [nl ddot nl '%test' nl], 'lineanchors');
  body = regexprep(body, '^assert', [nl ddot nl 'assert'], 'lineanchors');
  body = regexprep(body, 'assert', 'octassert');
  body = regexprep(body, '^(shared.*)\n', ['%$1' nl], 'lineanchors', 'dotexceptnewline');
  % FIXME: better to put these inside appropriate try catch end"
  body = regexprep(body, '^xtest\n( [^\n]*\n)*', [nl dskip nl '%xtest' ...
                      ' (**TEST EXPECTED TO FAIL: REMOVE**)' nl], 'lineanchors');
  body = regexprep(body, '^error [^\n]+\n( [^\n]*\n)*', [nl dskip nl '%error' ...
                      ' (**ERROR TEST: NOT SUPPORTED, REMOVED**)' nl], 'lineanchors');
  body = regexprep(body, '^error\n( [^\n]*\n)*', [nl dskip nl '%error' ...
                      ' (**ERROR TEST: NOT SUPPORTED, REMOVED**)' nl], 'lineanchors');
  body = regexprep(body, '^warning [^\n]+\n( [^\n]*\n)*', [nl dskip nl '%warning' ...
                      ' (**WARNING TEST: NOT SUPPORTED, REMOVED**)' nl], 'lineanchors');

  % output it
  out_name = ['tests_' basestr '_' name_no_m];
  full_out_name = [outdir '/' out_name '.m'];
  fid = fopen (full_out_name, 'w');
  fprintf(fid, 'function %s()\n', out_name);
  fprintf(fid, '%%%% Auto extracted tests from %s\n', in_name);
  fprintf(fid, '%% This file autogenerated from the inline Octave tests\n');
  fprintf(fid, '%% in the above file.  Don''t modify directly.\n');
  % FIXME: fprintf better than this schar thing?  its for utf8
  fwrite(fid, body, "schar");
  fprintf(fid, '\n\n\n%%%% End of tests\n');
  fprintf(fid, 'disp(''  Passed'')\n');
  fclose(fid);
endfunction

% This code from Octave source: /scripts/testfun/test.m
% Copyright (C) 2005-2013 Paul Kienzle
% GPL
function body = __extract_test_code (nm)
  fid = fopen (nm, "rt");
  body = '';
  if (fid >= 0)
    while (! feof (fid))
      ln = fgetl (fid);
      if (length (ln) >= 2 && strcmp (ln(1:2), "%!"))
        body = [body, "\n"];
        if (length (ln) > 2)
          body = [body, ln(3:end)];
        endif
      endif
    endwhile
    fclose (fid);
  endif
endfunction

repo: octsympy


text:
function set_visible(hia,v)
for c=1:length(v)
    v1=v(c);
    set(hia(v1),'visible','on');
end

author: Sable

repo: mcbench-benchmarks


text:
%% Transform Compression JPEG

% JPEG Baseline Encoder

% Jorge Calderon <calderonjorge9@gmail.com>
% University Of Antioquia
% Created: November 2012
% Modified: January 2013
% Copyright 2012
% All rights reserved

%% Clean Workplace

clear all;
close all;
clc;

%% Initialize Variables

check = 0;
stream=[];

DCTQ=[...
    16 11 10 16 24 40 51 61;...
    12 12 14 19 26 58 60 55;...
    14 13 16 24 40 57 69 56;...
    14 17 22 29 51 87 80 62;...
    18 22 37 56 68 109 103 77;...
    24 36 55 64 81 194 113 92;...
    49 64 78 87 103 121 120 101;...
    72 92 95 98 112 100 103 99];

z=[...
    9 2 3 10 17 25 18 11 4 5 12 19 26 ...
    33 41 34 27 20 13 6 7 14 21 28 35 ...
    42 49 57 50 43 36 29 22 15 8 16 23 ...
    30 37 44 51 58 59 52 45 38 31 24 32 ...
    39 46 53 60 61 54 47 40 48 55 62 63 56 64];

%% Read Image

while check<1
    [img_in pathname]=uigetfile({'*.bmp;*.tif','Image(*.bmp,*.tif)'},'Select Uncompressed Image','Multiselect','off');
    if img_in>0
        cd(pathname)
        image = double(imread(img_in));
        [row, col, dim] = size(image);
        if col<row
            disp('Error: The image must be horizontal');
            disp('Press any key to continue...');
            pause;
        else
            if (row<720 && col<1280)
                check=1;
            else
                disp('Error: The image size is too large');
                disp('Press any key to continue...');
                pause;
            end
        end
    else
        if img_in==0
            return;
        end
    end
end

%% Check Size

if mod(row,2)~=0
    row = row-1;
end
if mod(col,2)~=0
    col = col-1;
end
image = imresize(image, [row col]);

%% Convert Image To YCBCR

img = rgb2ycbcr(image);

%% Adjust Aspect Ratio

if mod(row,72)~=0
    row_aspect = row+(72-mod(row,72));
else
    row_aspect = row;
end
col_aspect = (row_aspect/9)*16;
image_aspect = zeros(row_aspect, col_aspect, dim);
zig_zag_ac = zeros(row_aspect*col_aspect/64, 63);
zig_zag_dc = zeros(row_aspect*col_aspect/64, 1);

for i=1:col
    for j=1:row
        for k=1:dim
            image_aspect(j+abs(row_aspect-row)/2,i+abs(col_aspect-col)/2,k)=img(j,i,k);
        end
    end
end

% figure(1)
% imshow(uint8(image_aspect));

%% Digitization Scheme 420

comp_blue = image_aspect(:,:,2);
comp_red = image_aspect(:,:,3);
luminance = double(image_aspect(:,:,1))-128;
imgcb_420 = double(comp_blue(1:2:size(comp_blue,1),1:2:size(comp_blue,2)))-128;
imgcr_420 = double(comp_red(1:2:size(comp_red,1),1:2:size(comp_red,2)))-128;

%% Segmenting Image Blocks Of 8x8

k=0;
for i=1:8:row_aspect
    for j=1:8:col_aspect
        f=luminance(i:i+7,j:j+7);
        T=dct2(f);
        TQ=round(T./DCTQ);
        k=k+1;
        zig_zag_dc(k,1) = TQ(1,1);
        zig_zag_ac(k,1:63) = TQ(z);
    end
end

%% Huffman Compression

dpcm(1,1)=zig_zag_dc(1,1);
stream=cat(2,stream,huffman_dc(dpcm(1,1)),huffman_ac(zig_zag_ac(1,1:63)));
for m=2:k
    dpcm(m,1)=zig_zag_dc(m,1)-zig_zag_dc(m-1,1);
    stream=cat(2,stream,huffman_dc(dpcm(m,1)),huffman_ac(zig_zag_ac(m,1:63)));
end

%% Byte Stuffing

p=0;
G=size(stream,2);
for i=1:8:size(stream,2)
    bit_val(1,1:8)=stream(1,i:i+7);
    if strcmp(bit_val(1,1:8),'11111111')==1
        tempbitstream = stream(1,i+8:G+p);
        stream(1,i+8:i+15)='00000000';
        p=p+8;
        temp2_bitstream=stream(1,1:i+15);
        stream(1,1:G+p)=cat(2,temp2_bitstream,tempbitstream);
    end
end

%% Convert String To Decimal

numbytes=floor(length(stream)/8);
diff_stream=length(stream)-numbytes*8;
if diff_stream==0
    matrix_code_decimal= zeros(numbytes+2,8);
else
    matrix_code_decimal= zeros(numbytes+3,8);
end
s=0;
for count2=1:8:numbytes*8
    s=s+1;
    matrix_code_decimal(s,1)=bin2dec(stream(1,count2:count2+7));
end

if diff_stream~=0
    s=s+1;
    matrix_code_decimal(s,1)=bin2dec(stream(1,numbytes*8+1:length(stream)));
end

%% Final Marker

matrix_code_decimal(s+1,1)=255;
matrix_code_decimal(s+2,1)=217;

%% Header JFIF

signal=[255	216	255	224	000	016	074	070	073	070	000	001	002	000	000	096	000	096	000	000	...
        255	219	000	067	000	016	011	012	014	012	010	016	014	013	014	018	017	016	019	024	...
        040	026	024	022	022	024	049	036	037	029	040	058	051	061	060	057	051	056	055	064	...
        072	092	078	064	068	087	069	055	056	080	109	081	087	095	098	103	194	103	062	077	...
        113	121	112	100	120	092	101	103	099	255	219	000	067	001	017	018	018	024	021	024	...
        047	026	026	047	099	066	056	066	099	099	099	099	099	099	099	099	099	099	099	099	...
        099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	...
        099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	099	255	192	...
        000	011	008	000	000	000	000	001	001	034	000	255	196	000	031	000	000	001	005	001	...
        001	001	001	001	001	000	000	000	000	000	000	000	000	001	002	003	004	005	006	007	...
        008	009	010	011	255	196	000	181	016	000	002	001	003	003	002	004	003	005 	005	004	...
        004	000	000	001	125	001	002	003	000	004	017	005	018	033	049	065	006	019	081	097	...
        007	034	113	020	050	129	145	161	008	035	066	177	193	021	082	209	240	036	051	098	...
        114	130	009	010	022	023	024	025	026	037	038	039	040	041	042	052	053	054	055	056	...
        057	058	067	068	069	070	071	072	073	074	083	084	085	086	087	088	089	090	099	100	...
        101	102	103	104	105	106	115	116	117	118	119	120	121	122	131	132	133	134	135	136	...
        137	138	146	147	148	149	150	151	152	153	154	162	163	164	165	166	167	168	169	170	...
        178	179	180	181	182	183	184	185	186	194	195	196	197	198	199	200	201	202	210	211	...
        212	213	214	215	216	217	218	225	226	227	228	229	230	231	232	233	234	241	242	243	...
        244	245	246	247	248	249	250	255	218	000	008	001	001	000	000	063	000];

% Start of Image (SOI) marker:FFD8=255,216
% JFIF marker:FFE0=255,224
%        Length=000,016
%        Identifier:4A46494600=074,070,073,070,000
%        Version=001,002
%        Units=000
%        Xdensity=000,096
%        Ydensity=000,096
%        Xthumbnail=000
%        Ythumbnail=000
%        (RGB)n, n=Xthumbnail*Ythumbnail required 3*n bytes=null

% Define Quantization table marker (luma):FFDB=255,219
%         Length:two bytes that indicate the number of bytes, including the two length bytes, that this header contains=000,067
%         Precision=000 (baseline)
%         Quantization values=016,011,012,014,012,010,016,...,101,103,099 (zigzag)

% Define Quantization table marker (Chroma):FFDB=255,219
%         Length:two bytes that indicate the number of bytes, including the two length bytes, that this header contains=000,067
%         Precision=000 (baseline)
%         Quantization values=017,018,018,024,021,024,047,...,099,099,099 (zigzag)

% Start of frame marker:FFC0=255,192
%         Length:two bytes that indicate the number of bytes, including the two length bytes, that this header contains=000,011
%         Sample precision=008
%         X=000,000 (This will be defined later)
%         Y=000,000 (This will be defined later)
%         Number of components in the image=001
%             * 3 for color baseline
%             * 1 for grayscale baseline
%         Component ID=001
%         H and V sampling factors=034
%         Quantization table number=000

% Define Huffman table marker (DC):FFC4=255,196
%        Length:two bytes that indicate the number of bytes, including the two length bytes, that this header contains=000,031
%        Index=000 (Huffman DC)
%        Bits=The next 16 bytes from an array of unsigned 1-byte integers whose elements give the number of Huffman codes for each possible code length (1-16).
%        Huffman values=000,001,002,...,010,011

% Define Huffman table marker (AC):FFC4=255,196
%        Length:two bytes that indicate the number of bytes, including the two length bytes, that this header contains=000,181
%        Index=016 (Huffman AC)
%        Bits=The next 16 bytes from an array of unsigned 1-byte integers whose elements give the number of Huffman codes for each possible code length (1-16).
%        Huffman values=001,002,003,...,249,250

% Start of Scan marker:FFDA=255,218
%        Length:two bytes that indicate the number of bytes, including the two length bytes, that this header contains=000,008
%        Number of components=001
%        Component ID=001
%        DC and AC table numbers=000
%        Ss=000
%        Se=063
%        Ah and Al=000

%% Define Size Image

Y = dec2hex(row_aspect,4);
X = dec2hex(col_aspect,4);
signal(1,164) = hex2dec(Y(1,1:2));
signal(1,165) = hex2dec(Y(1,3:4));
signal(1,166) = hex2dec(X(1,1:2));
signal(1,167) = hex2dec(X(1,3:4));

%% Concatenate Coding + Header

JP_STREAM(1,1:size(signal,2))=signal(1,1:size(signal,2));
for j=1:1:size(matrix_code_decimal,1)
    JP_STREAM(1,size(signal,2)+j)=matrix_code_decimal(j,1);
end

%% JPG Data Store

JP_STREAM=JP_STREAM';
img_name = regexp(img_in,'\.','split');
img_name = img_name{1};
fid = fopen([img_name '.jpg'], 'wb');
if fid < 0
    error('Failed to open data file for write');
end
fwrite(fid,JP_STREAM,'uint8');
fclose(fid);


text:
function failed_old_fixsource

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY

% this script tests the fixsource function which is part of ft_checkdata

%-------------------------------------
%generate data
rand('twister',20090408);
data = [];
data.fsample = 1000;
data.cfg     = [];

nsmp  = 1000;
nchan = 80;
for k = 1:10
  data.trial{k} = randn(nchan,nsmp);
  data.time{k}  = ([1:nsmp]-1)./data.fsample;
end

%create grad-structure and add to data
[pnt,tri] = mesh_sphere(162);
nrm       = surface_normals(pnt, tri, 'vertex');
pnt       = pnt.*12;
[srt,ind] = sort(pnt(:,3),'descend');
grad      = [];
grad.pnt  = pnt(ind(1:nchan),:);
grad.ori  = nrm(ind(1:nchan),:);
grad.tra  = eye(nchan);
for k = 1:nchan
  grad.label{k} = ['chan',num2str(k,'%03d')];
end
data.grad  = grad;
data.label = grad.label;

%create vol
vol   = [];
vol.o = [0 0 2];
vol.r = 8;

%prepare leadfields and grid
cfg                 = [];
cfg.sourcemodel.resolution = 1.5;
cfg.headmodel       = vol;
cfg.grad            = grad;
grid                = ft_prepare_leadfield(cfg);

%do spectral analysis
cfg        = [];
cfg.method = 'mtmfft';
cfg.output = 'fourier';
cfg.foilim = [2 100];
cfg.pad    = 1;
cfg.tapsmofrq = 3;
freq       = ft_freqanalysis(cfg, data);

%do timelocked analysis
cfg            = [];
cfg.covariance = 'yes';
cfg.covariancewindow = [0 0.999];
cfg.keeptrials = 'yes';
tlck           = ft_timelockanalysis(cfg, data);

%-----------------------------------------------

%-----------------------------------------------
%source reconstruction part

%without fixedori
cfgs           = [];
cfgs.grid      = grid;
cfgs.frequency = 20;
cfgs.method    = 'dics';
cfgs.lambda    = '10%';
cfgs.keepfilter = 'yes';
cfgs.feedback  = 'textbar';
cfgs.vol       = vol;
cfgs.fixedori  = 'no';
cfgs.keepcsd   = 'yes';
cfgs.realfilter = 'yes';
cfgs.keepleadfield = 'yes';
source         = ft_sourceanalysis(cfgs,freq);
sdics          = ft_checkdata(source, 'sourcerepresentation', 'new');

cfgs.sourcemodel.filter = sdics.filter;
cfgs.method      = 'pcc';
cfgs.keepmom     = 'yes';
source           = ft_sourceanalysis(cfgs, freq);
spcc1            = ft_checkdata(source, 'sourcerepresentation', 'new', 'haspow', 'yes');
%this gives a warning

cfgsd            = [];
cfgsd.projectmom = 'yes';
sd               = ft_sourcedescriptives(cfgsd, source);
spcc2            = ft_checkdata(sd, 'sourcerepresentation', 'new', 'haspow', 'yes');

%with fixedori
cfgs.grid     = grid;
cfgs.method   = 'dics';
cfgs.keepmom  = 'no';
cfgs.fixedori = 'yes';
source        = ft_sourceanalysis(cfgs, freq);
sdics2        = ft_checkdata(source, 'sourcerepresentation', 'new');

cfgs.sourcemodel.filter = sdics2.filter;
cfgs.method      = 'pcc';
cfgs.keepmom     = 'yes';

%there are two ways for not crashing the second round of ft_sourceanalysis
%with fixori = 'yes';
if all(islogical(source.inside))
  insidevec = find(source.inside);
else
  insidevec = source.inside;
end
for k = 1:numel(insidevec)
  kk = insidevec(k);
  cfgs.sourcemodel.leadfield{kk} = sdics2.leadfield{kk}*sdics2.ori{kk};
end
source = ft_sourceanalysis(cfgs, freq);
spcc1f = ft_checkdata(source, 'sourcerepresentation', 'new', 'haspow', 'yes');
%FIXME known problem: ori-field is missing here

% alternative
% append a mom to the grid as (3xN) matrix
cfgs.sourcemodel.mom = zeros(size(sourcemodel.pos))';
for k = 1:numel(insidevec)
  kk = insidevec(k);
  cfgs.sourcemodel.mom(:,kk) = sdics2.ori{kk};
end
%FIXME there's an issue here with mom being expected to be Nx3 and 3xN in ft_inverse_pcc
source = ft_sourceanalysis(cfgs, freq);
try,
  spcc2f = ft_checkdata(source, 'sourcerepresentation', 'new', 'haspow', 'yes');
catch
  error('this does not work');
end

%call sourcedescriptives to get a .trial field
cfgsd            = [];
cfgsd.keeptrials = 'yes';
sd               = ft_sourcedescriptives(cfgsd, source);
spcc3f           = ft_checkdata(sd, 'sourcerepresentation', 'new');

%lcmv
cfgs           = [];
cfgs.grid      = grid;
cfgs.frequency = 20;
cfgs.method    = 'lcmv';
cfgs.lambda    = '10%';
cfgs.keepfilter = 'yes';
cfgs.feedback  = 'textbar';
cfgs.vol       = vol;
cfgs.fixedori  = 'no';
cfgs.keepcov   = 'yes';
cfgs.keepleadfield = 'yes';
source         = ft_sourceanalysis(cfgs,tlck);
slcmv          = ft_checkdata(source, 'sourcerepresentation', 'new');

cfgs.sourcemodel.filter = slcmv.filter;
cfgs.rawtrial    = 'yes';
%cfgs.keepfilter  = 'no';
source           = ft_sourceanalysis(cfgs, tlck);
slcmv2           = ft_checkdata(source, 'sourcerepresentation', 'new');


text:
function [oa, pa, K, CM] = USFE_LPP(HSI, Tr, Te, dim, Trees)
[nx,ny,nz]=size(HSI);
data=reshape(HSI,nx*ny,nz);
[mappedX, mapping] = lpp(data, dim);
FE_lpp=reshape(mappedX,nx,ny,dim);
[acc_Mean,acc_std,CM]=RF_ntimes_overal(FE_lpp,Tr,Te,Trees);
pa=acc_Mean(1:dim,1);
oa=acc_Mean(dim+2,1);
K=acc_Mean(dim+3,1);

author: BehnoodRasti


text:
function dendrogramplot(c);

% Private method. See ../plot for details.

% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
% $Date$
% $Revision$

if ~isa(c,'correlation')
    error('First input must be a correlation object');
end;

if isempty(get(c,'LINK'))
    error('LINK field must be filled in input object');
end;

if ~isempty(get(c,'LAG'))
    disp('NOTE: Time corrections from LAG field have not been applied to traces yet.');
end;

% CREATE DENDROGRAM PLOT
[H,tmp,perm] = dendrogram(c.link,length(c.trig),'Orientation','right');
set(gcf,'Color','w','Position',[50 50 680 880]);
ylabel('event number','FontSize',16);
set(gca,'XGrid','on');
box on; hold on;
set(gcf,'Position',[0 0 640 1024]);

% SWITCH X AXIS LABELS
set(gca,'XDir','reverse');
% Fix by GT based on email by Kyle Brill, July 2016, see Issue 51
%label = 1- str2num(get(gca,'XTickLabel'));
label = 1- str2double(get(gca,'XTickLabel'));
set(gca,'XTickLabel',label);
%xlabel('distance (dissimilarlity)','FontSize',16);
xlabel('inter-cluster correlation','FontSize',16);

% MODIFY Y AXIS LABELS
if ~isempty(c.clust)
    YT = (get(gca,'YTickLabel'));
	%YT = strcat(YT,' (',num2str(c.clust(perm)),')');
    set(gca,'YTickLabel',YT);
    ylabel('event number (and cluster)','FontSize',16);
end

% PREP PRINT OUT
set(gcf, 'paperorientation', 'portrait');
set(gcf, 'paperposition', [.25 .25 8 10.5] );

% ADD WIGGLE PLOT
perm = fliplr(perm);
if length(perm)>=100
    plot(c,'sha',1,perm);
else
    plot(c,'wig',1,perm);
end

set(gcf,'Position',[641 0 640 1024]);

author: geoscience-community-codes

repo: GISMO


text:
function [ x,y ] = latlong2xy( lat, long, ref_lat, ref_long )
% converts lat/long coordinates to cartesian x,y, output in km
% ref_lat and ref_long is the geodetic reference point for plane approximation of the earth surface

earth_circumf = 40074; % km

y = (lat - ref_lat)/360 * earth_circumf;
x = (long - ref_long)/360 * cos(ref_lat*pi/180) * earth_circumf;

end

repo: tdoa-evaluation-rtlsdr


text:
function model = ml_trainrvm(varargin)
% Learn a probabilistic (non-)linear model, via the Relevance Vector Machine.
% Model = ml_trainrvm(Trials, Targets, Options...)
%
% The Relevance Vector Machine [1] is a Bayesian equivalent to the popular Support Vector Machines
% (SVMs) [2]. RVMs can be used for general-purpose linear or non-linear (kernelized) classification
% or regression, and produce state-of-the-art results in most cases. Various kernels are supplied,
% where the rbf kernel is usually the best initial choice. In the non-linear case, the kernel
% scaling parameter should be found via parameter search, which can be time-consuming. In contrast
% to SVMs, Relevance Vector Machines give probablistic outputs, which can be practical when multiple
% uncertain predictions are to be fused, etc. In the future, an implementation of RVMs using convex
% optimization will be provided, which is assumed to give better optimality guarantees than the
% current implementation [3,4,5].
%
% RVMs (as well as kernel SVMs) are the most versatile general-purpose classifiers currently
% available in the toolbox, and are a good default choice if very little is known about the data.
% For best results, care must be taken to search over the respective regularization parameter(s)
% appropriately. If more is known about the structure of the data (e.g. that it should be linearly
% separable, or that that sparsity can be exploited across features), specialized methods may be
% more appropriate (and give similar results faster or reach better performance by overfitting less
% strongly).
%
% In:
%   Trials       : training data, as in ml_train
%
%   Targets      : target variable, as in ml_train
%
%   Options  : optional name-value parameters to control the training details:
%              'ptype': problem type: 'classification' (default) or 'regression'
%
%              'kernel': one of several kernel types:
%                         * 'linear':   Linear
%                         * 'rbf':      Gaussian / radial basis functions (default)
%                         * 'laplace':  Laplacian
%                         * 'poly':		Polynomial
%                         * 'cauchy':	Cauchy
%
%              'gamma': scaling parameter of the kernel (for regularization); if multiple values
%                       are given, the optimal gamma will be searched via evidence maximization
%                       default: 2.^(-16:0.2:10)
%
%              'degree': degree of the polynomial kernel, if used (default: 3)
%
%              'bias': whether to add a bias to the data (default: 1)
%
%              misc options:
%              'iterations': Number of interations to run for
%              'time':       time limit to run for, e.g. '1.5 hours', '30 minutes', '1 second'
%              'fixednoise': whether the gaussian noise is to be fixed 0/1
%              'beta':       (Gaussian) noise precision (inverse variance)
%              'noisestd':   (Gaussian) noise standard deviation
%              'scaling':    pre-scaling of the data (see hlp_findscaling for options) (default: 'std')
%              'diagnosticlevel':   verbosity level, 0-4
%
% Out:
%   Model   : the computed model...
%             classes indicates the class labels which the model predicts
%             additional parameters determine a posterior distribution over the weights
%
% Examples:
%   % learn a standard Relevance Vector Machine classifier
%   model = ml_trainrvm(trials,targets)
%
%   % as before, but this time use a regression approach
%   model = ml_trainrvm(trials,targets,'ptype','regression')
%
%   % use a Laplacian kernel
%   model = ml_trainrvm(trials,targets,'kernel','laplace')
%
%   % find the optimal kernel scale using parameter search
%   model = utl_searchmodel({trials,targets},'args',{{'rvm','gamma',seach(2.^(-16:2:4)))
%
%
% See also:
%   ml_predictrvm, SparseBayes
%
% References:
%  [1] Vladimir Vapnik. "The Nature of Statistical Learning Theory."
%      Springer-Verlag, 1995
%  [2] Michael E. Tipping and Alex Smola, "Sparse Bayesian Learning and the Relevance Vector Machine".
%      Journal of Machine Learning Research 1: 211?244. (2001)
%  [3] Michael E. Tipping and A. C. Faul. "Fast marginal likelihood maximisation for sparse Bayesian models."
%      In C. M. Bishop and B. J. Frey (Eds.), Proceedings of the Ninth International Workshop on Artificial Intelligence and Statistics, Key West, FL, Jan 3-6 (2003)
%  [4] David P. Wipf and Srikantan Nagarajan, "A New View of Automatic Relevance Determination,"
%      In J.C. Platt, D. Koller, Y. Singer, and S. Roweis, editors, Advances in Neural Information Processing Systems 20, MIT Press, 2008.
%  [5] David P. Wipf and Srikantan Nagarajan, "Sparse Estimation Using General Likelihoods and Non-Factorial Priors,"
%      In Advances in Neural Information Processing Systems 22, 2009.
%
%                           Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                           2010-04-06
dp;

opts = arg_define([0 2],varargin, ...
    arg_norep('trials'), ...
    arg_norep('targets'), ...
    arg({'ptype','Type'}, 'classification', {'classification','regression'}, 'Type of problem to solve.','cat','Core Parameters'), ...
    arg({'kernel','Kernel'}, 'rbf', {'linear','rbf','laplace','poly','cauchy'}, 'Kernel type. Linear, or Non-linear kernel types: Radial Basis Functions (general-purpose), Laplace (sparse), Polynomial (rarely preferred), and Cauchy (slightly experimental).','cat','Core Parameters'), ...
    arg({'gammap','KernelScale','gamma'}, 2.^(-16:0.5:10), [0 2^-20 2^10 Inf], 'Scaling of the kernel functions. Should match the size of structures in the data. A reasonable range is 2.^(-16:2:4).','cat','Core Parameters','shape','row'), ...
    arg({'polydegree','PolyDegree','degree'}, 3, uint32([1 100]), 'Degree of the polynomial kernel, if chosen.','cat','Core Parameters'), ...
    arg({'bias','Bias'}, true, [], 'Include a bias term in the model.','cat','Core Parameters'), ...
    arg({'scaling','Scaling'}, 'std', {'none','center','std','minmax','whiten'}, 'Pre-scaling of the data. For the regulariation to work best, the features should either be naturally scaled well, or be artificially scaled.','cat','Core Parameters'), ...
    ...
    arg({'iterations','MaxIterations'}, 100, uint32([1 100000]), 'Number of iterations to run.','cat','Miscellaneous'), ...
    arg({'time','MaxTime'}, '1000 seconds', [], 'Maximum time to run. Can use ''seconds'', ''minutes'', ''hours'' in the string.','cat','Miscellaneous'), ...
    arg({'fixednoise','NoiseFixed'}, false, [], 'Keep the Gaussian noise estimate fixed.','cat','Miscellaneous'), ...
    arg({'noiseinvvar','NoiseInvVariance','beta'}, [], [], 'Inverse variance of the Gaussian noise term.','cat','Miscellaneous','shape','scalar'), ...
    arg({'noisestd','NoiseVariance'}, [], [], 'Variance of the Gaussian noise term.','cat','Miscellaneous','shape','scalar'), ...
    arg({'diagnosticlevel','Verbosity'}, 'none', {'none','minimal','low','medium','high','ultra'}, 'Verbosity level.','cat','Miscellaneous'),...
    arg({'votingScheme','VotingScheme'},'1vR',{'1v1','1vR'},'Voting scheme. If multi-class classification is used, this determine how binary classifiers are arranged to solve the multi-class problem. 1v1 gets slow for large numbers of classes (as all pairs are tested), but can be more accurate than 1vR.'), ...
    arg({'monitor','DisplayInterval'}, uint32(0), [], 'Iterations between diagnostic outputs.','cat','Miscellaneous'));

arg_toworkspace(opts);

if is_search(gammap)
    gammap = 0.3; end

% pre-process arguments
ptype = hlp_rewrite(ptype,'classification','c','regression','r'); %#ok<*NODEF>
likelihood = hlp_rewrite(ptype,'c','bernoulli','r','gaussian');
args1 = [hlp_struct2varargin(opts,'restrict',{'iterations','time','monitor','fixednoise','freebasis','callback','callbackdata'}),{'diagnosticlevel',hlp_rewrite(opts.diagnosticlevel,'minimal','none')}];
args2 = hlp_struct2varargin(opts,'restrict',{'beta','noisestd','relevant','weights','alpha'},'rewrite',{'beta','noiseinvvar'});

% remap targets for classification
if strcmp(ptype,'c')
    classes = unique(targets);
    if length(classes) > 2
        % multiclass case: use the voter
        model = ml_trainvote(trials,targets,votingScheme,@ml_trainrvm,@ml_predictrvm,varargin{:});
        return;
    elseif length(classes) == 1
        error('BCILAB:only_one_class','Your training data set has no trials for one of your classes; you need at least two classes to train a classifier.\n\nThe most likely reasons are that one of your target markers does not occur in the data, or that all your trials of a particular class are concentrated in a single short segment of your data (10 or 20 percent). The latter would be a problem with the experiment design.');
    end
    % remap target labels to 0/1
    targets(targets==classes(1)) = 0;
    targets(targets==classes(2)) = 1;
else
    classes = [];
end

% prescale the data
sc_info = hlp_findscaling(trials,scaling);
trials = hlp_applyscaling(trials,sc_info);
basis = trials;

if length(gammap)>1
    if ~strcmp(opts.diagnosticlevel,'none')
        disp('Now optimizing gamma parameter using evidence maximization...'); end
    % optimize gamma parameter using marginal log-likelihood
    bestgam = NaN;      % best gamma parameter so far
    likelihoods = nan(length(gammap),1);
    bestlike = -Inf;    % best likelihood so far
    for k=1:length(gammap)
        gam = gammap(k);
        if ~strcmp(opts.diagnosticlevel,'none')
            fprintf('gamma=%.3f\n',gam); end
        % kernelize the data and add bias
        ktrials = utl_kernelize(trials,basis,kernel,gam,polydegree);
        ktrials = quickif(bias,[ones(size(ktrials,1),1) ktrials],ktrials);
        % run the RVM
        [param, hyperparam, diag] = hlp_diskcache('predictivemodels',@SparseBayes,likelihood,ktrials,targets,SB2_UserOptions(args1{:}),SB2_ParameterSettings(args2{:})); %#ok<ASGLU>
        if ~isempty(diag.Likelihood)
            likelihoods(k) = diag.Likelihood(end);
            if diag.Likelihood(end) > bestlike
                bestlike = diag.Likelihood(end);
                bestgam = gam;
            end
        end
    end
    gammap = bestgam;
else
    likelihoods = [];
end

% kernelize the data and add bias
ktrials = utl_kernelize(trials,basis,kernel,gammap,polydegree);
ktrials = quickif(bias,[ones(size(ktrials,1),1) ktrials],ktrials);
% run the RVM
[param, hyperparam, diag] = hlp_diskcache('predictivemodels',@SparseBayes,likelihood,ktrials,targets,SB2_UserOptions(args1{:}),SB2_ParameterSettings(args2{:}));

% preselect relevant basis vectors
if ~strcmp(kernel,'linear')
    if bias
        feature_sel = param.Relevant-1;
        if feature_sel(1) == 0
            % bias was relevant, remove it from the basis vector selection (it will be added after kernelization)
            feature_sel = feature_sel(2:end);
        else
            % bias was not relevant, forget about it
            bias = 0;
        end
    else
        feature_sel = param.Relevant;
    end
    basis = basis(feature_sel,:);
else
    feature_sel = param.Relevant;
end

model = struct('sc_info',{sc_info},'classes',{classes},'basis',{basis},'param',{param},'hyperparam',{hyperparam},...
               'diag',{diag},'ptype',{ptype},'feature_sel',{feature_sel},'bias',{bias}, ...
               'kernel',{kernel},'gamma',{gammap},'gamma_likelihoods',likelihoods,'degree',{polydegree});

repo: REST


text:
function cell2csv(C,filename)
%CELL2CSV Output a cell array to a CSV file
%
%   IOSR.GENERAL.CELL2CSV(C,FILENAME) writes the cell array C to a CSV file
%   specified by filename.

%   Copyright 2016 University of Surrey.

    %% make sure filename has a .csv extension

    [pathstr, name, ext] = fileparts(filename);
    if ~strcmp(ext,'.csv')
        filename = [pathstr filesep name '.csv'];
    end

    %% write data

    [nrows,ncols]= size(C);

    % trap and remove cell arrays of strings
    IX = cell2mat(cellfun(@iscell,C,'UniformOutput',false));
    C(IX) = cellfun(@char,C(IX),'UniformOutput',false);

    % create file
    fid = fopen(filename, 'w');

    % create format string
    format = cell(1,ncols);
    ind = cellfun(@ischar,C(2,:));
    format(ind) = {'%s,'};
    format(~ind) = {'%f,'};
    format = wrap(format);

    if any(cellfun(@ischar,C(1,:))~=cellfun(@ischar,C(2,:)))
        % the cell array has a heading line
        header = repmat({'%s,'},[1,ncols]);
        header = wrap(header);
        start = 2;
        fprintf(fid, header, C{1,:});
    else
        % the cell array does not have a heading line
        start = 1;
    end

    for row=start:nrows
        fprintf(fid, format, C{row,:});
    end

    fclose(fid);

end

function y = wrap(x)
%WRAP Concatenate cells and add end EOL

    y = cell2mat(x);
    i = strfind(y,',');
    y = [y(1:i(end)-1) '\n'];

end

author: IoSR-Surrey

repo: MatlabToolbox


text:
function x = rot2quat (R, tol)
% Use:  q = rot2quat(R)
%
% Computes the unit quaternion corresponding to the 3x3 rotation matrix R
% tol controls the tolerance to check is R == identity(3)
% Note: quaternion is q = [qw qx qy qz], where qw is the scalar part of q
%
% From Luca Carlone's
% https://bitbucket.org/lucacarlone/pgo3d-duality-opencode/annotate/ebb6e1b8cebaad7f2aaf581b1d0c0bad737faebb/lib/rot2quat.m?at=master&fileviewer=file-view-default

if nargin < 2
  tol =  1.0e-5;
end

if isrot(R, tol) == 0
  s(4) = .5 * sqrt( 1 + R(1,1) + R(2,2) + R(3,3) );
  if norm(s(4)) <= tol
    %disp ('rotation = 180 degrees')
    [u,teta]=rot2uth(R);
    s(1)=u(1);
    s(2)=u(2);
    s(3)=u(3);
  elseif norm(s(4)-1) <= tol
    % disp ('rotation = 0 degrees')
    s(1) = 0;
    s(2) = 0;
    s(3) = 0;
  else
    s(1) = (R(3,2) - R(2,3))/(4 * s(4));
    s(2) = (R(1,3) - R(3,1))/(4 * s(4));
    s(3) = (R(2,1) - R(1,2))/(4 * s(4));
  end
  x(1) = s(4);
  x(2) = s(1);
  x(3) = s(2);
  x(4) = s(3);
else
  disp ('Error in input matrix')
  x=[1 0 0 0]';
end

author: uzh-rpg


text:
% GREP EXAMPLES
%
% - note only selected output is shown for the sake of brevity
% - note clicking on any underlined text
%	file name
%	line number
%   will open the file at the matching line

% create a line separator
	sep=@(x) disp(sprintf(repmat('-',1,75)));

% assume GREP.TXT is in your current working folder
	fnam='grep.txt';
% - show contents (note all spaces are TABs!)
	type(fnam);

% simple case insensitive [-i] string search in GREP.M for instances of
%		Version
% listing file name [def] and the line number [-n] of occurrences
%-------------------------------------------------------------------------------
	grep -i -n Version grep.m
	sep();

% regular expression search [-R] in GREP.M for instances of
%		=true or =false
% listing line number [-n] but not the file name [-Q]
%-------------------------------------------------------------------------------
	grep -Q -n -R =true|=false grep.m
	sep();

% simple string search in GREP.M for exactly matching [-x] instances of
%		\t\tmsg=true;
% listing the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	TAB=sprintf('\t');
	fl=grep('-x -n',[TAB,TAB,'msg=true;'],'grep.m');
	sep();

% simple string search in GREP.TXT for
%		every line of itself in turn
% using the pattern-file [-f] option and
% listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] for each occurrence
%-------------------------------------------------------------------------------
	fl=grep('-l -f',fnam,fnam);
	sep();

% simple string search in GREP.TXT for instances of
%		-n
% using the [-e] option since -n itself is an option flag (listing line number!)
% and listing the file name [def] for each non-matching line [-v] only
% - compare with previous example!
%-------------------------------------------------------------------------------
	fl=grep('-v -e',{'-n'},fnam);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
% listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	fpat=[matlabroot,'/toolbox/matlab/elfun'];
	fl=grep('-r -l -n',{'sign','cosine','atan'},fpat);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
% using the two versions of the [-e] option and
% listing the full file name and pattern for each file with matches [-l]
% as well as the count [-c] of all instances
%-------------------------------------------------------------------------------
	fl=grep('-r -l -c -e sign -e',{'cosine','atan'},fpat);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
%	only including files with a regular expression pattern [-If]
%		[Cc]ont
% using the two versions of the [-e] option and
% listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	fl=grep('-r -l -n -If [Cc]ont -e sign -e',{'cosine','atan'},fpat);
	sep();

% full depth search [-r] of the entire ELFUN TOOLBOX for instances of
%		sign or cosine or atan
%	only including files with a regular expression pattern [-If]
%		[Cc]ont
%	and excluding folders with a pattern [-Xd]
%		/ja
% - using the two versions of the [-e] option,
% and listing the full file name and pattern for each file with matches [-l]
% as well as the file name [def] and the line number [-n] for each occurrence
%-------------------------------------------------------------------------------
	fl=grep('-r -l -n -If [Cc]ont -e sign -e',{'cosine','atan'},'-Xd','/ja',fpat);
	sep();

author: opencobra

repo: cobratoolbox


text:
function phi = basis_brick8 ( n, p )

%*****************************************************************************80
%
%% BASIS_BRICK8: BRICK8 basis functions at natural coordinates.
%
%  Discussion:
%
%      8------7        t  s
%     /|     /|        | /
%    5------6 |        |/
%    | |    | |        0-------r
%    | 4----|-3
%    |/     |/
%    1------2
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 March 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of evaluation points.
%
%    Input, real P(3,N), natural coordinates of evaluation
%    points.
%
%    Output, real PHI(8,N), the basis function values.
%
  phi(1,1:n) =  ( 1.0 - p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 - p(3,1:n) );
  phi(2,1:n) =  ( 1.0 + p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 - p(3,1:n) );
  phi(3,1:n) =  ( 1.0 + p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 - p(3,1:n) );
  phi(4,1:n) =  ( 1.0 - p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 - p(3,1:n) );
  phi(5,1:n) =  ( 1.0 - p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 + p(3,1:n) );
  phi(6,1:n) =  ( 1.0 + p(1,1:n) ) .* ( 1.0 - p(2,1:n) ) .* ( 1.0 + p(3,1:n) );
  phi(7,1:n) =  ( 1.0 + p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 + p(3,1:n) );
  phi(8,1:n) =  ( 1.0 - p(1,1:n) ) .* ( 1.0 + p(2,1:n) ) .* ( 1.0 + p(3,1:n) );

  phi(1:8,1:n) = phi(1:8,1:n) / 8.0;

  return
end


text:
function [V,dV] = dss_sphere(X, dim, symmetric, params)
%   [V,dV] = dss_sphere(X)
%   [V,dV] = dss_sphere(X, dim)
%   [V,dV] = dss_sphere(X, dim, symmetric)
%     X          Data to be sphered
%     dim        Requested result data dimension, 0 for no reduction
%     symmetric  Boolean, perform symmetric sphering
%     V          Sphering matrix
%     dV         De-sphering matrix

% Copyright (C) 2004, 2005 DSS MATLAB package team (dss@cis.hut.fi).
% Distributed by Laboratory of Computer and Information Science,
% Helsinki University of Technology. http://www.cis.hut.fi/projects/dss/.
% $Id: dss_sphere.m,v 1.2 2005/11/30 08:29:40 jaakkos Exp $

if nargin<4
  params = [];
end
if nargin<3 || isempty(symmetric)
  symmetric = false;
end
if ~isfield(params, 'absthreshold')
  params.absthreshold=true;
end
if params.absthreshold && ~isfield(params, 'thresholdEig')
  % Treshold for eigenvalues that are treated zero
  params.thresholdEig=1e-12;
elseif ~params.absthreshold && ~isfield(params, 'thresholdEig')
  params.thresholdEig=0.99; % keep the components that explain up to 99% of variance
end
if ~isfield(params, 'thresholdSphered')
  % Treshold for maximum covariance for treating data already sphered
  params.tresholdSphered=1e-12;
end

if nargin>=2 && dim~=0
  if iscell(X)
    dim = min(dim, size(X{1}, 1));
  else
    dim = min(dim, size(X, 1));
  end
elseif iscell(X)
  dim = size(X{1}, 1);
else
  dim = size(X, 1);
end

fprintf('Sphering the data\n');
% data covariance
if iscell(X)
  C = cellcov(X, 2, 1);
  I = diag(ones(size(X{1},1),1));
else
  C = cov(X', 1);
  I = diag(ones(size(X,1),1));
end

% check if data is already sphered
maxCov = max(max(C-I));
if maxCov<params.tresholdSphered
    fprintf('SPHERING: Maximum data covariance %d below treshold (%d), assume pre-sphered data.\n', maxCov, params.tresholdSphered);
    V = diag(ones(dim,1));
    dV = V;
else

    % eigenvectors and eigenvalues
    [E,D] = eig(C);
    D = diag(D);

    % sort eigenvalues in descending order
    [D,order] = sort(-D);
    D=-D;
    E=E(:,order);

    % reduce dimension based on matrix rank
    if params.absthreshold
      values = sum(D>=params.thresholdEig);
      if values<length(D)
        fprintf('SPHERING: %d values (%d negative) below eigenvalue treshold (%d).\n', length(D)-values, sum(D<0), params.thresholdEig);
      end
    else
      values = sum(cumsum(D)./sum(D)<=params.thresholdEig);
      if values<length(D)
        fprintf('SPHERING: %d values (%d negative) below cumulative eigenvalue treshold (%d).\n', length(D)-values, sum(D<0), params.thresholdEig);
      end
    end
    % reduce dimension
    dim = min(dim, values);
    if iscell(X) && dim < size(X{1},1)
      fprintf('SPHERING: Reducing data dimension: %d -> %d.\n', size(X{1},1), dim);
    end
    if ~iscell(X) && dim < size(X,1)
      fprintf('SPHERING: Reducing data dimension: %d -> %d.\n', size(X,1), dim);
    end
    E = E(:,1:dim);
    D = D(1:dim);

    % calculate sphering matrices
    D = sqrt(D);
    V = diag(1./D) * E' ;
    dV = E * diag(D);
    if symmetric
        % symmetric sphering
        V = E * V;
        dV = dV *E';
    end

end


text:
function r8_atanh_test ( )

%*****************************************************************************80
%
%% R8_ATANH_TEST tests R8_ATANH.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 October 2008
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8_ATANH_TEST\n' );
  fprintf ( 1, '  R8_ATANH computes the inverse hyperbolic tangent\n' );
  fprintf ( 1, '  of a given value.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '        X        R8_ATANH(X)  TANH(R8_ATANH(X))\n' );
  fprintf ( 1, '\n' );

  for i = -2 : 9
    x = i / 10.0;
    a = r8_atanh ( x );
    x2 = tanh ( a );
    fprintf ( 1, '  %12f  %12f  %12f\n', x, a, x2 );
  end

  return
end


text:
function out = numSources(D)
    % D is the diagonal eigen value matrix of the matrix of empirical
    % covariance of the antenna data
    num = NaN;
    for i = size(D, 1):-1:3

        if (D(i-1, i-1)-D(i-2, i-2))/(D(i, i)-D(i-1, i-1))<=0.1
            num = i-1;
        end

    end

    out = num;
end

author: msamsami

repo: doa-estimation-music


text:
classdef ABC < ALGORITHM
% <single> <real/integer> <large/none> <constrained/none>
% Artificial bee colony algorithm
% limit --- 20 --- The number of trials for releasing a food source

%------------------------------- Reference --------------------------------
% D. Karaboga, An idea based on honey bee swarm for numerical optimization,
% Erciyes University, Tech. Rep. tr06, 2005.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            limit = Algorithm.ParameterSet(20);

            %% Generate random population
            Population = Problem.Initialization();
            Limit      = zeros(1,Problem.N);

            %% Optimization
            while Algorithm.NotTerminated(Population)
                % Employed bees
                Pdec      = Population.decs;
                Odec      = Pdec + (rand(size(Pdec))*2-1).*(Pdec-Pdec(randi(end,1,end),:));
                Offspring = Problem.Evaluation(Odec);
                replace             = FitnessSingle(Population) > FitnessSingle(Offspring);
                Population(replace) = Offspring(replace);
                Limit(~replace)     = Limit(~replace) + 1;

                % Onlooker bees
                Q         = RouletteWheelSelection(Problem.N,exp(Population.objs/mean(abs(Population.objs+1e-6))));
                Pdec      = Population.decs;
                Odec      = Pdec(Q,:) + (rand(size(Pdec))*2-1).*(Pdec(Q,:)-Pdec(randi(end,1,end),:));
                Offspring = Problem.Evaluation(Odec);
                replace             = FitnessSingle(Population) > FitnessSingle(Offspring);
                Population(replace) = Offspring(replace);
                Limit(~replace)     = Limit(~replace) + 1;

                % Scout bees
                Q = Limit > limit;
                if any(Q)
                    Population(Q) = Problem.Initialization(sum(Q));
                    Limit(Q)      = 0;
                end
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function add_rx_io(hRD)

% add AXI4 and AXI4-Lite slave interfaces
hRD.addAXI4SlaveInterface( ...
    'InterfaceConnection', 'axi_cpu_interconnect/M11_AXI', ...
    'BaseAddress',         '0x43C00000', ...
    'MasterAddressSpace',  'sys_ps7/Data');

% Control Status Pins
hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 CTRL OUT', ...
    'InterfaceType',  'IN', ...
    'PortName',       'read_status_ctrl', ...
    'PortWidth',      8, ...
    'InterfaceConnection', 'gpio_status', ...
    'IsRequired',     false);

% AGC Control Pin
hRD.addInternalIOInterface( ...
    'InterfaceID',    'Enable AGC', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'en_agc', ...
    'PortWidth',      1, ...
    'InterfaceConnection', 'gpio_en_agc', ...
    'IsRequired',     false);

% DMA Ready signal
hRD.addInternalIOInterface( ...
    'InterfaceID',    'DMA Ready', ...
    'InterfaceType',  'IN', ...
    'PortName',       'dma_rdy', ...
    'PortWidth',      1, ...
    'InterfaceConnection', 'axi_ad9361_adc_dma/s_axis_ready', ...
    'IsRequired',     false);

% Reference design interfaces
hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data Valid OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_valid', ...
    'PortWidth',      1, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_valid_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 0 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_0', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 1 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_1', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_1', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 2 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_2', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_2', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'IP Data 3 OUT', ...
    'InterfaceType',  'OUT', ...
    'PortName',       'dut_data_3', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_pack/adc_data_3', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data I0', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_0_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_0', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data Q0', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_1_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_1', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data I1', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_2_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_2', ...
    'IsRequired',     false);

hRD.addInternalIOInterface( ...
    'InterfaceID',    'AD9361 ADC Data Q1', ...
    'InterfaceType',  'IN', ...
    'PortName',       'sys_wfifo_3_dma_wdata', ...
    'PortWidth',      16, ...
    'InterfaceConnection', 'util_ad9361_adc_fifo/dout_data_3', ...
    'IsRequired',     false);

author: analogdevicesinc


text:
function [y,L] = midwt(x,h,L);
%    [x,L] = midwt(y,h,L);
%
%    Function computes the inverse discrete wavelet transform x for a 1D or
%    2D input signal y using the scaling filter h.
%
%    Input:
%	y : finite length 1D or 2D input signal (implicitly periodized)
%           (see function mdwt to find the structure of y)
%       h : scaling filter
%       L : number of levels. In the case of a 1D signal, length(x) must be
%           divisible by 2^L; in the case of a 2D signal, the row and the
%           column dimension must be divisible by 2^L.  If no argument is
%           specified, a full inverse DWT is returned for maximal possible
%           L.
%
%    Output:
%       x : periodic reconstructed signal
%       L : number of decomposition levels
%
%    1D Example:
%       xin = makesig('LinChirp',8);
%       h = daubcqf(4,'min');
%       L = 1;
%       [y,L] = mdwt(xin,h,L);
%       [x,L] = midwt(y,h,L)
%
%    1D Example's  output:
%
%       x = 0.0491 0.1951 0.4276 0.7071 0.9415 0.9808 0.6716 0.0000
%       L = 1
%
%    See also: mdwt, mrdwt, mirdwt
%

%
%
%File Name: midwt.m
%Last Modification Date: 08/07/95	15:13:52
%Current Version: midwt.m	2.4
%File Creation Date: Wed Oct 19 10:51:58 1994
%Author: Markus Lang  <lang@jazz.rice.edu>
%
%Copyright (c) 2000 RICE UNIVERSITY. All rights reserved.
%Created by Markus Lang, Department of ECE, Rice University.
%
%This software is distributed and licensed to you on a non-exclusive
%basis, free-of-charge. Redistribution and use in source and binary forms,
%with or without modification, are permitted provided that the following
%conditions are met:
%
%1. Redistribution of source code must retain the above copyright notice,
%   this list of conditions and the following disclaimer.
%2. Redistribution in binary form must reproduce the above copyright notice,
%   this list of conditions and the following disclaimer in the
%   documentation and/or other materials provided with the distribution.
%3. All advertising materials mentioning features or use of this software
%   must display the following acknowledgment: This product includes
%   software developed by Rice University, Houston, Texas and its contributors.
%4. Neither the name of the University nor the names of its contributors
%   may be used to endorse or promote products derived from this software
%   without specific prior written permission.
%
%THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON, TEXAS,
%AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
%BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
%FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RICE UNIVERSITY
%OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
%EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
%PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
%OR BUSINESS INTERRUPTIONS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
%WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
%OTHERWISE), PRODUCT LIABILITY, OR OTHERWISE ARISING IN ANY WAY OUT OF THE
%USE OF THIS SOFTWARE,  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
%For information on commercial licenses, contact Rice University's Office of
%Technology Transfer at techtran@rice.edu or (713) 348-6173
%
%Change History:
%
%Modification #1
%Mon Aug  7 11:52:33 CDT 1995
%Rebecca Hindman <hindman@ece.rice.edu>
%Added L to function line so that it can be displayed as an output
%
%Thu Mar  2 13:07:11 CDT 2000
%Ramesh Neelamani<neelsh@ece.rice.edu>
%Revamped the help file
%

author: thomaskuestner


text:
% PRELP  Loads and preprocesses LP from an MPS file.
%
% > [A,b,c,lenx,lbounds] = PRELP('problemname')
%    The above command results in an LP in standard form,
%    - Instead of specifying the problemname, you can also use PRELP([]), to
%    get the problem from the file /tmp/default.mat.
%    - Also, you may type PRELP without any input arguments, and get prompted
%    for a name.
%
% MINIMIZE  c'*x SUCH THAT  A*x = b AND  x>= 0.
%
%   So, you can solve it with SeDuMi:
% > [x,y,info] = SEDUMI(A,b,c);
%
% After solving, post-process it with
% > [x,objp] = POSTPROCESS(x(1:lenx),lbounds).
%
% REMARK  x(lenx+1:length(x)) will contain upper-bound slacks.
%
% IMPORTANT works only if LIPSOL is installed on your system.
%
% See also sedumi, getproblem, postprocess (LIPSOL), frompack, lipsol.

function [A,b,c,lenx,lbounds,times] = prelp(pname)
%
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA%

global OUTFID
global Ubounds_exist
if ~exist('loadata','file') || ~exist('preprocess','file')
    error('To use PRELP, you need to have LIPSOL installed.')
end

%--------------------------------------------------
% LOAD LP PROBLEM INTO MEMORY
%--------------------------------------------------
if (nargin == 0)
    pname = input('Enter problem name: ','s');
end
t0 = cputime;
[A,b,c,lbounds,ubounds,BIG,NAME] = loadata(pname);
times(1) = cputime - t0;

%--------------------------------------------------
% PREPROCESS LP PROBLEM
% NB: Y.Zhang's preprocess returns lbounds for post-
% processing; the pre-processed problem has x>=0.
%--------------------------------------------------
t0 = cputime;
[A,b,c,lbounds,ubounds,FEASIBLE] = ...
    preprocess(A,b,c,lbounds,ubounds,BIG);
if ~FEASIBLE
    fprintf('\n');
    if isempty(OUTFID)
        return;
    end;
    msginf =  'Infeasibility detected in preprocessing';
    fprintf(OUTFID, [pname '  0   ' msginf '\n']);
    return;
end;
%[A,b,c,ubounds] = scaling(A,b,c,ubounds);
%--------------------------------------------------
% INSERT UBOUND- CONSTRAINTS IN THE A-MATRIX
%--------------------------------------------------
b = full(b); c = full(c);
[m,lenx] = size(A);
if Ubounds_exist
    nub = nnz(ubounds);
    A= [ A sparse(m,nub); sparse(1:nub,find(ubounds),1,nub,lenx) speye(nub) ];
    b = [b; nonzeros(ubounds)];
    c = [c; zeros(nub,1)];
else
    ubounds = [];
end
%--------------------------------------------------
% LOCATE DENSE COLUMNS
%--------------------------------------------------
%checkdense(A);
times(2) = cputime - t0;

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
function s = polyline_arclength_nd ( dim_num, n, p )

%*****************************************************************************80
%
%% POLYLINE_LENGTH_ND computes the length of a polyline in ND.
%
%  Discussion:
%
%    A polyline of order M is the geometric structure consisting of
%    the M-1 line segments that lie between successive elements of a list
%    of M points.
%
%    An ordinary line segment is a polyline of order 2.
%    The letter "V" is a polyline of order 3.
%    The letter "N" is a polyline of order 4, and so on.
%
%    DIST(I+1,I) = sqrt ( sum ( 1 <= J <= DIM_NUM ) ( X(I+1) - X(I) )**2 )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 February 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, real P(DIM_NUM,N), the points.
%
%    Output, real S(N), the arclength coordinates
%    of each point.  The first point has S(1) = 0 and the
%    last point has S(N) = arclength of the entire polyline.
%
  s(1) = 0.0;

  for i = 2 : n

    s(i) = s(i-1) + sqrt ( sum ( ( p(1:dim_num,i) - p(1:dim_num,i-1) ).^2 ) );

  end

  return
end

author: johannesgerer


text:
function gamsWrite(prob,filename)
%gamsWrite  Write a GAMS Model from MATLAB data
%
% gamsWrite(prob,filename) writes the OPTI problem to a GAMS model (.gms)
% and optionally a GDX file if SCIP is not used.
%
% You may specify a full path to the file, or if you specify a filename
% only, it will be written to the current directory.

%   Copyright (C) 2013 Jonathan Currie (IPL)

ext = 'gms';

%Quick Checks
if(~ischar(filename))
    error('Filename must be a char array!');
end
if(~isempty(prob.sdcone))
    error('Semidefinite problems cannot be written by this interface');
end
% Make sure we have file extension for GAMS model
if(isempty(strfind(lower(filename),['.' ext])))
    gdxname = filename;
    filename = [filename '.' ext];
else
    % Remove file extension for GDX file
    ind = strfind(lower(filename),['.' ext]);
    gdxname = filename(1:ind-1);
end

% Check for full filepath
if(isempty(strfind(filename,':')))
    filename = [cd filesep filename];
    gdxname = [cd filesep gdxname];
end

%If we have SCIP installed, use that (much easier, and does nonlinear models)
if(optiSolver('scip',0))
    opts = optiset('solver','scip','warnings','none','display','off','solverOpts',scipset('gamsfile',filename));
    if(isstruct(prob.int) && isfield(prob.int,'str'))
        prob.int = prob.int.str;
    end
    if(isempty(prob.x0) || all(isnan(prob.x0))), prob.x0 = randn(prob.sizes.ndec,1); end
    Opt = opti(prob,opts);
    try
        solve(Opt);
    catch ME
        if(strcmpi(ME.identifier,'OPTI:SCIPVAR'))
            throwAsCaller(MException('OPTI:SCIPVAR','AN ERROR OCCURED WHILE PRE-PROCESSING YOUR MATLAB FUNCTION(S) - PLEASE EXAMINE THE SCIP ERROR BELOW:\n\n%s',ME.message));
        else
            throw(ME);
        end
    end
    return;
end

%Check not nonlinear
if(~isempty(prob.fun) && isa(prob.fun,'function_handle'))
    error('The OPTI GAMS Writer only works for problems up to MIQCQP complexity.\n\nFor general nonlinear problems you must have %s installed to write nonlinear GAMS problems','SCIP');
end

%Check GAMS routines are available
if(~exist(['rgdx.' mexext],'file') || ~exist(['wgdx.' mexext],'file'))
    error('Could not find the required GAMS routines on your PC [wgdx,rgdx]!\n\n%s',...
          'Please download a current GAMS distribution from "http://www.gams.com/download/", then add the GAMS install folder to the MATLAB path.');
end

%Check for SOS constraints (not yet implemented)
if(~isempty(prob.sos))
    optiwarn('OPTI:GamsWriteSOS','SOS constraints are not currently supported by this interface, so they will be skipped!');
end

%Determine number of decision variables
if(isfield(prob,'sizes'))
    ndec = prob.sizes.ndec;
elseif(~isempty(prob.f))
    ndec = numel(prob.f);
elseif(~isempty(prob.x0))
    ndec = numel(prob.x0);
elseif(~isempty(prob.H))
    ndec = size(prob.H,1);
else
    error('Could not determine the number of decision variables!');
end

%Convert linear constraints to row format
if(~isempty(prob.b) || ~isempty(prob.beq))
    [prob.A,prob.rl,prob.ru] = gen2row(prob.A,prob.b,prob.Aeq,prob.beq);
end

%Convert integer constraints to string
if(~isempty(prob.int) && ~isstruct(prob.int))
    if(ischar(prob.int))
        str = prob.int;
        prob.int = struct('str',str);
    elseif(isnumeric(prob.int))
        str = repmat('C',1,ndec);
        str(prob.int) = 'I';
        prob.int = struct('str',str);
    else
        error('Unknown integer format');
    end
elseif(isempty(prob.int))
    prob.int.str = [];
end
prob.int.str = upper(prob.int.str);
nint = sum(prob.int.str == 'I');
nbin = sum(prob.int.str == 'B');

%Starting writing GAMS Model File
fid = fopen(filename,'w');
if(fid < 0), error('Error creating GAMS Model: %s',filename); end

name = regexprep(prob.Name,' ','_');

fprintf(fid,'* OPTI Generated GAMS Model (%s)\n',datestr(now));
fprintf(fid,'*   Model Name             : %s\n',name);
if(isfield(prob,'type') && ~isempty(prob.type))
    fprintf(fid,'*   Model Classification   : %s\n',prob.type);
end
fprintf(fid,'*   Variables              : %d (%d Integer, %d Binary)\n',ndec,nint,nbin);
if(~isempty(prob.rl)),  fprintf(fid,'*   Linear Constraints     : %d\n',numel(prob.rl)); end
if(~isempty(prob.qrl)), fprintf(fid,'*   Quadratic Constraints  : %d\n',numel(prob.qrl)); end
if(~isempty(prob.cl)),  fprintf(fid,'*   Nonlinear Constraints  : %d\n',numel(prob.cl)); end
fprintf(fid,'\n');

try
    model = 'lp';
    %Check for integer and binary constraints
    if(~all(prob.int.str == 'C'))
        int = struct('name','int','type','set','dim',1,'uels',{{find(prob.int.str ~= 'C')}},'form','full','ts','integer and binary indices');
        if(any(prob.int.str == 'B'))
            %Force binary bounds
            ind = (prob.int.str == 'B')';
            if(isempty(prob.lb)), prob.lb = -Inf(ndec,1); end
            if(isempty(prob.ub)), prob.ub = Inf(ndec,1); end
            %Set bin indicies which are infinite or bounds > 1 or < 0 to 1/0
            prob.lb((isinf(prob.lb) | (prob.lb < 0)) & ind) = 0;
            prob.ub((isinf(prob.ub) | (prob.ub > 1)) & ind) = 1;
        end
    else
        int = [];
    end
    %Check for bounds
    if(~isempty(prob.lb))
        lb = struct('name','lb','type','parameter','dim',1,'val',full(prob.lb),'form','full','ts','decision variable lower bound');
    else
        lb = [];
    end
    if(~isempty(prob.ub))
        ub = struct('name','ub','type','parameter','dim',1,'val',full(prob.ub),'form','full','ts','decision variable upper bound');
    else
        ub = [];
    end
    %Check for initial guess
    if(~isempty(prob.x0) && all(~isnan(prob.x0)))
        x0 = struct('name','x0','type','parameter','dim',1,'val',full(prob.x0),'form','full','ts','decision variable initial guess');
    else
        x0 = [];
    end
    %Check for linear objective
    if(~isempty(prob.f) && isnumeric(prob.f))
        f = struct('name','f','type','parameter','dim',1,'val',full(prob.f),'form','full','ts','linear objective vector');
    else
        f = [];
    end
    %Check for quadratic objective
    if(~isempty(prob.H) && isnumeric(prob.H))
        %We require all elements of H, see if we have a saved copy before
        %triu/tril
        if(isfield(prob,'save') && isfield(prob.save,'H') && ~isempty(prob.save.H) && isnumeric(prob.save.H))
            H = prob.save.H;
        else
            H = prob.H;
        end
        [i,j,v] = find(sparse(H));
        H = struct('name','H','type','parameter','dim',2,'val',[i j v],'form','sparse','ts','quadratic objective matrix');
        model = 'qp';
    else
        H = [];
    end
    %Check for linear constraints
    if(~isempty(prob.A))
        [i,j,v] = find(sparse(prob.A));
        A = struct('name','A','type','parameter','dim',2,'val',[i j v],'form','sparse','ts','linear constraint matrix');
        rl = struct('name','rl','type','parameter','dim',1,'val',full(prob.rl),'form','full','ts','linear constraint lower bound');
        ru = struct('name','ru','type','parameter','dim',1,'val',full(prob.ru),'form','full','ts','linear constraint upper bound');
    else
        A = []; rl = []; ru = [];
    end
    %Check for quadratic constraints
    if(~isempty(prob.Q))
        %Concatenate each Q matrix into a 3D array
        if(iscell(prob.Q))
            i = []; j = []; k = []; v = [];
            for n = 1:length(prob.Q) %could preallocate...
                [I,J,V] = find(sparse(prob.Q{n}));
                i = [i;I]; %#ok<AGROW>
                j = [j;J]; %#ok<AGROW>
                k = [k;n*ones(size(I))]; %#ok<AGROW>
                v = [v;V]; %#ok<AGROW>
            end
        else
            [i,j,v] = find(sparse(prob.Q));
            k = ones(size(i));
        end
        Q = struct('name','Q','type','parameter','dim',3,'val',[i j k v],'form','sparse','ts','quadratic constraint matrix');
        [i,j,v] = find(sparse(prob.l));
        l = struct('name','l','type','parameter','dim',2,'val',[i j v],'form','sparse','ts','quadratic constraint linear matrix');
        qrl = struct('name','qrl','type','parameter','dim',1,'val',full(prob.qrl),'form','full','ts','quadratic constraint lower bound');
        qru = struct('name','qru','type','parameter','dim',1,'val',full(prob.qru),'form','full','ts','quadratic constraint upper bound');
        model = 'qcqp';
    else
        Q = []; l = []; qrl = []; qru = [];
    end

    %Write GAMS Data
    writeGDX(gdxname,H,f,lb,ub,x0,int,A,rl,ru,Q,l,qrl,qru);

    %Write set definitions
    fprintf(fid,'Sets\n');
    fprintf(fid,' n /1*%d/\n',ndec);
    if(~isempty(int)), fprintf(fid,' ni(n)\n'); end
    if(~isempty(prob.rl)), fprintf(fid,' mlin /1*%d/\n',numel(prob.rl)); end
    if(~isempty(prob.qrl)), fprintf(fid,' mquad /1*%d/\n',numel(prob.qrl)); end
    if(~isempty(prob.cl)), fprintf(fid,' mnlin /1*%d/\n',numel(prob.cl)); end
    fprintf(fid,';\n');

    %Alias for QP, QC
    if(~isempty(H)), fprintf(fid,'Alias (n,n1);\n\n'); end

    %Write parameter definitions
    fprintf(fid,'Parameters\n');
    if(~isempty(H)), fprintf(fid,' H(n,n1)\n'); end
    if(~isempty(f)), fprintf(fid,' f(n)\n'); end
    if(~isempty(lb) && ~isempty(ub))
        fprintf(fid,' lb(n), ub(n)\n');
    elseif(~isempty(lb))
        fprintf(fid,' lb(n)\n');
    elseif(~isempty(ub))
        fprintf(fid,' ub(n)\n');
    end
    if(~isempty(x0)), fprintf(fid,' x0(n)\n'); end
    if(~isempty(A)), fprintf(fid,' A(mlin,n), rl(mlin), ru(mlin)\n'); end
    if(~isempty(Q)), fprintf(fid,' Q(n,n1,mquad), l(n,mquad), qrl(mquad), qru(mquad)\n'); end
    fprintf(fid,';\n');

    %Enter Variables to Import
    fprintf(fid,'* Load Parameters from GDX\n');
    fprintf(fid,'$gdxin %s.gdx\n',gdxname);
    if(~isempty(H)), fprintf(fid,'$load H\n'); end
    if(~isempty(f)), fprintf(fid,'$load f\n'); end
    if(~isempty(lb) && ~isempty(ub))
        fprintf(fid,'$load lb,ub\n');
    elseif(~isempty(lb))
        fprintf(fid,'$load lb\n');
    elseif(~isempty(ub))
        fprintf(fid,'$load ub\n');
    end
    if(~isempty(int)), fprintf(fid,'$load ni = int\n'); end
    if(~isempty(x0)), fprintf(fid,'$load x0\n'); end
    if(~isempty(A)), fprintf(fid,'$load A,rl,ru\n'); end
    if(~isempty(Q)), fprintf(fid,'$load Q,l,qrl,qru\n'); end
    fprintf(fid,'$gdxin\n\n');

    %Complete GAMS file
    %Variable Definition
    fprintf(fid, 'Variables\n x(n)\n');
    fprintf(fid, ' obj;\n\n');

    %Integer and binary def
    if(~isempty(int))
        fprintf(fid,'Integer Variables\n x;\n');
        fprintf(fid,' x.prior(n) = inf;\n');
        fprintf(fid,' x.prior(ni) = 1;\n\n');
    end

    %Equations
    fprintf(fid, 'Equations\n');
    if(~isempty(A))
        fprintf(fid, ' linconLB(mlin)\n');
        fprintf(fid, ' linconUB(mlin)\n');
    end
    if(~isempty(Q))
        fprintf(fid, ' quadconLB(mquad)\n');
        fprintf(fid, ' quadconUB(mquad)\n');
    end
    fprintf(fid, ' cost;\n\n');

    %Objective
    fprintf(fid, '* Cost Function\n');
    switch(model)
        case 'lp'
            fprintf(fid, ' cost.. obj =e= sum(n, f(n)*x(n));\n\n');
        case {'qp','qcqp'}
            fprintf(fid, ' cost.. obj =e= 0.5*sum(n,x(n)*sum(n1,H(n,n1)*x(n1))) + sum(n,f(n)*x(n));\n\n');
        otherwise
            error('Problem type ''%s'' not yet supported',prob.type);
    end

    %Bounds
    if(~isempty(lb) || ~isempty(ub))
        fprintf(fid, '* Decision Variable Bounds\n');
        if(~isempty(lb)), fprintf(fid, ' x.lo(n) = lb(n);\n'); end
        if(~isempty(ub)), fprintf(fid, ' x.up(n) = ub(n);\n'); end
        fprintf(fid,'\n');
    end

    %Initial Guess
    if(~isempty(x0))
        fprintf(fid, '* Initial Solution Guess\n');
        fprintf(fid, ' x.l(n) = x0(n);\n\n');
    end

    %Linear Constraints
    if(~isempty(A))
        fprintf(fid,'* Linear Constraints\n');
        fprintf(fid,' linconLB(mlin).. rl(mlin) =l= sum(n, A(mlin,n)*x(n));\n');
        fprintf(fid,' linconUB(mlin).. sum(n, A(mlin,n)*x(n)) =l= ru(mlin);\n\n');
    end

    %Quadratic Constraints
    if(~isempty(Q))
        fprintf(fid,'* Quadratic Constraints\n');
        fprintf(fid,' quadconLB(mquad).. qrl(mquad) =l= sum(n,x(n)*sum(n1,Q(n,n1,mquad)*x(n1))) + sum(n,l(n,mquad)*x(n));\n');
        fprintf(fid,' quadconUB(mquad).. sum(n,x(n)*sum(n1,Q(n,n1,mquad)*x(n1))) + sum(n,l(n,mquad)*x(n)) =l= qru(mquad);\n\n');
    end

    %Write model declaration
    fprintf(fid,'\nModel %s / all /;\n\n',name);

    %Determine which GAMS solver type to use
    switch(model)
        case 'lp'
            if(isempty(int))
                fprintf(fid,'Solve %s using %s minimizing obj;\n',name,'LP');
            else
                fprintf(fid,'Solve %s using %s minimizing obj;\n',name,'MIP');
            end
        case {'qp','qcqp'}
            if(isempty(int))
                fprintf(fid,'Solve %s using %s minimizing obj;\n',name,'QCP');
            else
                fprintf(fid,'Solve %s using %s minimizing obj;\n',name,'MIQCP');
            end
    end

catch ME
    fclose(fid);
    rethrow(ME);
end

fclose(fid);

function writeGDX(name,H,f,lb,ub,x0,int,A,rl,ru,Q,l,qrl,qru)

args = {};
if(~isempty(H)),    args = [args H]; end
if(~isempty(f)),    args = [args f]; end
if(~isempty(lb)),   args = [args lb]; end
if(~isempty(ub)),   args = [args ub]; end
if(~isempty(x0)),   args = [args x0]; end
if(~isempty(int)),  args = [args int]; end
if(~isempty(A)),    args = [args A]; end
if(~isempty(rl)),   args = [args rl]; end
if(~isempty(ru)),   args = [args ru]; end
if(~isempty(Q)),    args = [args Q]; end
if(~isempty(l)),    args = [args l]; end
if(~isempty(qrl)),  args = [args qrl]; end
if(~isempty(qru)),  args = [args qru]; end

if(~isempty(args))
    wgdx(name,args{:});
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function z = crossp(x,y)

% crossp - compute cross product
%
%   z = crossp(x,y);
%
% x and y are (m,3) dimensional
%
%   Copyright (c) 2007 Gabriel Peyre

z = x;
z(:,1) = x(:,2).*y(:,3) - x(:,3).*y(:,2);
z(:,2) = x(:,3).*y(:,1) - x(:,1).*y(:,3);
z(:,3) = x(:,1).*y(:,2) - x(:,2).*y(:,1);

author: gpeyre

repo: matlab-toolboxes


text:
classdef ADXL345busDataBaseClass < TimeSeriesDataBaseClass

    %% Abstract public 'read-only' properties
    properties (Abstract, SetAccess = private)
        FileNameAppendage;
    end

    %% Public 'read-only' properties
    properties (SetAccess = private)
        ADXL345A = struct('X', [], 'Y', [], 'Z', []);
        ADXL345B = struct('X', [], 'Y', [], 'Z', []);
        ADXL345C = struct('X', [], 'Y', [], 'Z', []);
        ADXL345D = struct('X', [], 'Y', [], 'Z', []);
    end

    %% Abstract protected properties
    properties (Access = protected)
        AccelerometerUnits;
    end

    %% Protected methods
    methods (Access = protected)
        function obj = Import(obj, fileNamePrefix)
            data = obj.ImportCSVnumeric(fileNamePrefix);
            obj.ADXL345A.X = data(:,2);
            obj.ADXL345A.Y = data(:,3);
            obj.ADXL345A.Z = data(:,4);
            obj.ADXL345B.X = data(:,5);
            obj.ADXL345B.Y = data(:,6);
            obj.ADXL345B.Z = data(:,7);
            obj.ADXL345C.X = data(:,8);
            obj.ADXL345C.Y = data(:,9);
            obj.ADXL345C.Z = data(:,10);
            obj.ADXL345D.X = data(:,11);
            obj.ADXL345D.Y = data(:,12);
            obj.ADXL345D.Z = data(:,13);
            obj.SampleRate = obj.SampleRate;    % call set method to create time vector
        end
    end

    %% Public methods
    methods (Access = public)
        function fig = Plot(obj)
            if(obj.NumPackets == 0)
                error('No data to plot.');
            else
                if(isempty(obj.Time))
                    time = 1:obj.NumPackets;
                else
                    time = obj.Time;
                end
                fig = figure('Name', obj.CreateFigName());
                ax(1) = subplot(4,1,1);
                hold on;
                plot(time, obj.ADXL345A.X, 'r');
                plot(time, obj.ADXL345A.Y, 'g');
                plot(time, obj.ADXL345A.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 A');
                hold off;
                ax(2) = subplot(4,1,2);
                hold on;
                plot(time, obj.ADXL345B.X, 'r');
                plot(time, obj.ADXL345B.Y, 'g');
                plot(time, obj.ADXL345B.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 B');
                hold off;
                ax(3) = subplot(4,1,3);
                hold on;
                plot(time, obj.ADXL345C.X, 'r');
                plot(time, obj.ADXL345C.Y, 'g');
                plot(time, obj.ADXL345C.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 C');
                hold off;
                ax(4) = subplot(4,1,4);
                hold on;
                plot(time, obj.ADXL345D.X, 'r');
                plot(time, obj.ADXL345D.Y, 'g');
                plot(time, obj.ADXL345D.Z, 'b');
                legend('X', 'Y', 'Z');
                xlabel(obj.TimeAxis);
                ylabel(strcat('Acceleration (', obj.AccelerometerUnits, ')'));
                title('ADXL345 D');
                hold off;
                linkaxes(ax,'x');
            end
        end
    end
end

author: xioTechnologies

repo: Gait-Tracking-With-x-IMU