function c = inf_(a)
%INF_         Implements  inf(a)  (cures problems with inf)
%
%   c = inf(a)
%
% On return, inf(a) <= alpha for all entries alpha in a
%
%************************************************************************
%********  due to conflict with internal variable inf (infinity)  *******
%********                    use function inf_                    *******
%************************************************************************
%

% written  10/05/99     S.M. Rump
% modified 09/02/00     S.M. Rump  rounding unchanged after use
% modified 04/04/04     S.M. Rump  set round to nearest for safety
%                                    take care of huge arrays
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 09/10/07     S.M. Rump  performance, huge arrays
%

  if a.complex
    if isequal(a.rad,0)                  % faster for sparse matrices
      c = a.mid;
    else
      e = 1e-30;
      if 1+e==1-e                        % fast check for rounding to nearest
        rndold = 0;
      else
        rndold = getround;
      end
      setround(-1)
      if issparse(a.rad)
        [m,n] = size(a.rad);
        [I,J,arad] = find(a.rad);
        c = a.mid - sparse(I,J,complex(arad,arad),m,n);
      else
        c = a.mid - complex(a.rad,a.rad);
      end
      setround(rndold)
    end
  else
    c = a.inf;
  end


% OCEANSITES_DEMO Plot all time series variables that have a certain
% 'standard_name' in a specified bounding box and time period

% WHOI GI-CAT catalog server, which harvests data from multiple
% THREDDS Servers:
open_url='http://geoport.whoi.edu/gi-cat/services/opensearch';

% can search for any text, not just variable 'standard_names':
%var='relative_humidity'; %free text search string
var='sea_water_temperature';
%var='sea_water_salinity';

% time_var='time'; %time coordinate variable
bbox =[-180 180 -70 80];  % [lon_min lon_max lat_min lat_max]

% specify a certain search range.  Like this...
start=[1990 1 1 0 0 0]; % specified start
stop =[2000 1 1 0 0 0]; % specified stop

% or like this....
start=now_utc-28;  % last 28 days
stop=now_utc;          % now

%%%%%%%%%%%%%%%%%%%% end of user defined input %%%%%%%%%%%%%%%%
% opensearch query
q.endpoint=open_url;
q.bbox=bbox;
q.time_start=datestr(start);% convert to ISO
q.time_end=datestr(stop);% convert to ISO
q.string_text=var

disp(['Querying ' q.endpoint ' via OpenSearch']);
[links,params]=opensearch(q);
dap=links2dap(links); % find only the OPeNDAP links
char(dap)
disp('Accessing data via OPeNDAP');
for i=1:length(dap);
    figure(i);
    nc=ncgeodataset(dap{i});
    vars=nc.variables;
    for j=1:length(vars); %loop through variables to find standard_names
        vart=nc.geovariable(vars{j});
        std_name=vart.attribute('standard_name');
        if strcmp(std_name,var),
            jd= vart.timewindowij(start, stop);
            t=vart.data(jd.index);  %extact these indices from dataset
            plot(jd.time,t);datetick;grid;...
            ylabel(sprintf('%s [%s]',var,vart.attribute('units')),...
                'interpreter','none');...
            title(nc.attribute('title'));...
            drawnow
        end
    end
end


%% Display several images on the same figure
%  Changed: Dec 9th, 2011
%
function showimage(varargin)

    % Check parameters
    nb_args   = size(varargin,2);
    nb_images = nb_args;
    nb_cols   = 0;
    nb_rows   = 1;
    row       = 1;
    crange    = [0 1]; % default image intensities

    for i=1:nb_args
        if ischar(varargin{i})
            if isequal(varargin{i},'lim')
                lim       = varargin{i+1};
                nb_images = nb_images-2;
            elseif isequal(varargin{i},'nbcols')
                nb_cols   = varargin{i+1};
                nb_images = nb_images-2;
            elseif isequal(varargin{i},'nbrows')
                nb_rows   = varargin{i+1};
                nb_images = nb_images-2;
            elseif isequal(varargin{i},'row')
                row       = varargin{i+1};
                if row>nb_rows; nb_rows = row; end;
                nb_images = nb_images-2;
            elseif isequal(varargin{i},'caxis')
                crange    = varargin{i+1};
                nb_images = nb_images-2;
            else
                nb_images = nb_images-1;
            end
        end
    end

    if nb_cols==0; nb_cols = nb_images; end;

    % Display images
    iter_image = 1;
    for iter_arg=1:nb_args
        if ~ischar(varargin{iter_arg})
            I = varargin{iter_arg};

            % Use mid slice as image
            slice = ceil(size(I,3)/2);
            I = I(:,:,slice);

            subplot(nb_rows,nb_cols,(row-1)*nb_cols + iter_image);
            imagesc(I,crange);
            daspect([1 1 1]);
            if exist('lim'); axis([lim(3)-0.5 lim(4)+0.5 lim(1)-0.5 lim(2)+0.5]); end
            axis off;
            if iter_arg+1<=nb_args && ischar(varargin{iter_arg+1})
                title(varargin{iter_arg+1});
            end
            iter_image = iter_image+1;
        end
        if iter_image>nb_images
            break;
        end
    end

end


function c = times(a,b,dummy)
%TIMES        Implements  a .* b  for intervals
%

% written  10/16/98     S.M. Rump
% modified 09/02/00     S.M. Rump  rounding unchanged after use
% modified 04/04/04     S.M. Rump  set round to nearest for safety
%                                    remove check for 'double'
%                                    extra argument for non-interval output (internal use only)
%                                    take care of Matlab sparse Inf/NaN bug
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 11/20/05     S.M. Rump  fast check for rounding to nearest
% modified 02/11/06     S.M. Rump  SparseInfNanFlag removed
%                                    sparse radius for complex data
% modified 05/23/06     S.M. Rump  sparse Inf/NaN bug corrected in Version 7.2+
% modified 12/03/06     S.M. Rump  Sparse Bug global flag (thanks to Arnold)
% modified 12/05/06     S.M. Rump  0*infsup(0,inf) (thanks to Arnold)
% modified 01/19/07     S.M. Rump  zero radius for huge arrays
% modified 05/22/07     S.M. Rump  check for sparse zero factor
% modified 10/21/07     S.M. Rump  Matlab bug for sparse(0)*inf
% modified 10/18/08     S.M. Rump  abss replaced by mag, improved performance
% modified 08/26/12     S.M. Rump  global variables removed
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
  end
  huge = ( max(prod(size(a)),prod(size(b)))>1e9 );

  if ~isa(a,'intval')                     % a is double
    if ~isreal(a) | b.complex             % complex case
      if ~b.complex
        setround(1)
        b.mid = b.inf + 0.5*(b.sup-b.inf);
        b.rad = b.mid - b.inf;
      end
      c.complex = 1;
      c.inf = [];
      c.sup = [];
      if isreal(a) | ~b.complex           % R .* IC  or  C .* IC
        setround(-1)
        c1 = a .* b.mid;
        setround(1)
        c2 = a .* b.mid;
      else                                % C .* IC
        setround(-1)
        c1 = real(a) .* real(b.mid) + (-imag(a)) .* imag(b.mid) + ...
             ( real(a) .* imag(b.mid) + imag(a) .* real(b.mid) ) * j;
        setround(1)
        c2 = real(a) .* real(b.mid) + (-imag(a)) .* imag(b.mid) + ...
             ( real(a) .* imag(b.mid) + imag(a) .* real(b.mid) ) * j;
      end
      c.mid = c1 + 0.5*(c2-c1);           % R .* IC  or  C .* IC
      c.rad = abs(c.mid-c1);
      if ~isequal(b.rad,0)                % make sure c.rad remains sparse
        c.rad = c.rad + abs(a) .* b.rad;
      end
      % too rare, improvement doesn't pay
%       if huge
%         [cradi,cradj] = find(c.rad);
%         if ~any(find(cradi))              % take care of huge arrays
%           c.rad = 0;
%         end
%       else
%         if ~any(find(c.rad))
%           c.rad = 0;
%         end
%       end
    else                                  % real case  R .* IR
      c.complex = 0;
      if ( prod(size(a))==1 ) & isequal(a(1,1),0)    % careful with 0*inf and sparse a
        if isinf(b.inf) | isinf(b.sup)
          c.inf = repmat(NaN,size(b.inf));
        else
          if issparse(b.inf)
            [mb,nb] = size(b.inf);
            c.inf = sparse([],[],[],mb,nb);
          else
            c.inf = zeros(size(b.inf));
          end
        end
        c.sup = c.inf;
      else
        setround(-1)
        c.inf = min( a .* b.inf , a .* b.sup );
        setround(1)
        c.sup = max( a .* b.inf , a .* b.sup );
      end
      c.mid = [];
      c.rad = [];
    end
  elseif ~isa(b,'intval')                 % b is double
    if a.complex | ~isreal(b)             % complex case
      if ~a.complex
        setround(1)
        a.mid = a.inf + 0.5*(a.sup-a.inf);
        a.rad = a.mid - a.inf;
      end
      c.complex = 1;
      c.inf = [];
      c.sup = [];
      if ~a.complex | isreal(b)           % IC .* R  or  IC .* C
        setround(-1)
        c1 = a.mid .* b;
        setround(1)
        c2 = a.mid .* b;
      else                                % IC .* C
        setround(-1)
        c1 = real(a.mid) .* real(b) + (-imag(a.mid)) .* imag(b) + ...
             ( real(a.mid) .* imag(b) + imag(a.mid) .* real(b) ) * j;
        setround(1)
        c2 = real(a.mid) .* real(b) + (-imag(a.mid)) .* imag(b) + ...
             ( real(a.mid) .* imag(b) + imag(a.mid) .* real(b) ) * j;
      end
      c.mid = c1 + 0.5*(c2-c1);           % R .* IC  or  C .* IC
      c.rad = abs(c.mid-c1);
      if ~isequal(a.rad,0)                % make sure c.rad remains sparse
        c.rad = c.rad + a.rad .* abs(b) ;
      end
      % too rare, improvement doesn't pay
%       if huge
%         [cradi,cradj] = find(c.rad);
%         if ~any(find(cradi))              % take care of huge arrays
%           c.rad = 0;
%         end
%       else
%         if ~any(find(c.rad))
%           c.rad = 0;
%         end
%       end
    else                                  % real case  IR .* R
      c.complex = 0;
      setround(-1)
      c.inf = min( a.inf .* b , a.sup .* b );
      setround(1)
      c.sup = max( a.inf .* b , a.sup .* b );
      c.mid = [];
      c.rad = [];
    end
  else                                    % both a and b interval
    if a.complex | b.complex              % complex case
      if ~a.complex
        setround(1)
        a.mid = a.inf + 0.5*(a.sup-a.inf);
        a.rad = a.mid - a.inf;
      end
      if ~b.complex
        setround(1)
        b.mid = b.inf + 0.5*(b.sup-b.inf);
        b.rad = b.mid - b.inf;
      end
      c.complex = 1;
      c.inf = [];
      c.sup = [];
      if ~a.complex | ~b.complex          % one real factor
        setround(-1)
        c1 = a.mid .* b.mid;
        setround(1)
        c2 = a.mid .* b.mid;
      else
        setround(-1)
        c1 = real(a.mid) .* real(b.mid) + (-imag(a.mid)) .* imag(b.mid) + ...
             ( real(a.mid) .* imag(b.mid) + imag(a.mid) .* real(b.mid) ) * j;
        setround(1)
        c2 = real(a.mid) .* real(b.mid) + (-imag(a.mid)) .* imag(b.mid) + ...
             ( real(a.mid) .* imag(b.mid) + imag(a.mid) .* real(b.mid) ) * j;
      end
      c.mid = c1 + 0.5*(c2-c1);           % IR .* IC  or  IC .* IC
      c.rad = abs(c.mid-c1);
      if ~isequal(a.rad,0)                % make sure c.rad remains sparse
        if ~isequal(b.rad,0)
          c.rad = c.rad + a.rad .* ( abs(b.mid) + b.rad );
        else
          c.rad = c.rad + a.rad .* abs(b.mid);
        end
      end
      if ~isequal(b.rad,0)
        c.rad = c.rad + abs(a.mid) .* b.rad;
      end
      % too rare, improvement doesn't pay
%       if huge
%         [cradi,cradj] = find(c.rad);
%         if ~any(find(cradi))              % take care of huge arrays
%           c.rad = 0;
%         end
%       else
%         if ~any(find(c.rad))
%           c.rad = 0;
%         end
%       end
    else                                  % real case  IR .* IR
      c.complex = 0;
      %setround(-1)
      c.inf = min( a.inf .* b.inf , a.inf .* b.sup );
      c.inf = min( c.inf , a.sup .* b.inf );
      c.inf = min( c.inf , a.sup .* b.sup );
      %setround(1)
      c.sup = max( a.inf .* b.inf , a.inf .* b.sup );
      c.sup = max( c.sup , a.sup .* b.inf );
      c.sup = max( c.sup , a.sup .* b.sup );
      c.mid = [];
      c.rad = [];
    end
  end

  INTLAB_SPARSE_BUG = getappdata(0,'INTLAB_SPARSE_BUG');
  if INTLAB_SPARSE_BUG
    % take care of Matlab sparse NaN bug
    if huge                                       % huge linear indices, for simplicity inf*x=NaN
      if c.complex
        [m,n] = size(c.mid);
      else
        [m,n] = size(c.inf);
      end
      if issparse(a)
        index = any( isnan(b) | isinf(b) );
        if any(index(:))                          % keep linear index small
          [indexi,indexj] = find(isnan(b));
          cNaN = sparse(indexi,indexj,NaN,m,n);
          [ia,ja,aa] = find(mag(a));
          [ib,jb,bb] = find(mag(b));
          ab = sparse([ia;ib],[ja;jb],[complex(aa(:),0);complex(0,bb(:))],m,n);
          [indexi,indexj,ab] = find(ab);
          index = isinf(imag(ab));
          ab = real(ab);
          ab(index & (ab==0)) = NaN;
          ab(~isnan(ab)) = 0;
          cNaN = cNaN + sparse(indexi,indexj,ab,m,n);
          if c.complex
            c.mid = c.mid + cNaN;
            if isequal(c.rad,0)
              c.rad = cNaN;                       % scalar + sparse = full also for scalar=0
            else
              c.rad = c.rad + cNaN;
            end
          else
            c.inf = c.inf + cNaN;
            c.sup = c.sup + cNaN;
          end
        end
      end
      if issparse(b)
        index = any( isnan(a) | isinf(a) );
        if any(index(:))                          % keep linear index small
          [indexi,indexj] = find(isnan(a));
          cNaN = sparse(indexi,indexj,NaN,m,n);
          [ia,ja,aa] = find(mag(a));
          [ib,jb,bb] = find(mag(b));
          ab = sparse([ia;ib],[ja;jb],[complex(0,aa(:));complex(bb(:),0)],m,n);
          [indexi,indexj,ab] = find(ab);
          index = isinf(imag(ab));
          ab = real(ab);
          ab(index & (ab==0)) = NaN;
          ab(~isnan(ab)) = 0;
          cNaN = cNaN + sparse(indexi,indexj,ab,m,n);
          if c.complex
            c.mid = c.mid + cNaN;
            if isequal(c.rad,0)
              c.rad = cNaN;                       % scalar + sparse = full also for scalar=0
            else
              c.rad = c.rad + cNaN;
            end
          else
            c.inf = c.inf + cNaN;
            c.sup = c.sup + cNaN;
          end
        end
      end
    else
      Index = logical(0);
      if issparse(a) & ( prod(size(a))~=1 )     % sparse scalar is handled correctly by Matlab
        Index = isnan(b);
        if any(Index(:))
          if prod(size(b))==1
            Index = find( a==0 );					      % may be almost full
          end
        end
        index = find(isinf(b));
        if any(index)
          if prod(size(b))==1                   % a is scalar
            index = find( a==0 );               % may be almost full
          else                                  % a and b not scalar, same size
            if isa(a,'intval')
              if a.complex
                if isequal(a.rad,0)
                  index( a.mid(index)~=0 ) = [];
                else
                  index( ( a.mid(index)~=0 ) | ( a.rad(index)~=0 ) ) = [];
                end
              else
                index( ( a.inf(index)~=0 ) | ( a.sup(index)~=0 ) ) = [];
              end
            else
              index( a(index)~=0 ) = [];
            end
          end
          Index(index) = 1;
        end
      end
      if issparse(b) & ( prod(size(b))~=1 )     % sparse scalar is handled correctly by Matlab
        Index = Index | isnan(a);
        if any(Index(:))
          if prod(size(a))==1
            Index = find( b==0 );					      % may be almost full
          end
        end
        index = find(isinf(a));
        if any(index)
          if prod(size(a))==1                   % a is scalar
            index = find( b==0 );               % may be almost full
          else                                  % a and b not scalar, same size
            if isa(b,'intval')
              if b.complex
                if isequal(b.rad,0)
                  index( b.mid(index)==0 ) = [];
                else
                  index( ( b.mid(index)~=0 ) | ( b.rad(index)~=0 ) ) = [];
                end
              else
                index( ( b.inf(index)~=0 ) | ( b.sup(index)~=0 ) ) = [];
              end
            else
              index( b(index)~=0 ) = [];
            end
          end
          Index(index) = 1;
        end
      end
      if any(Index(:))
        if c.complex
          c.mid(Index) = NaN;
          if isequal(c.rad,0)
            [m,n] = size(c.mid);
            c.rad = sparse([],[],[],m,n);
          end
          c.rad(Index) = NaN;
        else
          c.inf(Index) = NaN;
          c.sup(Index) = NaN;
        end
      end
    end
  end

  % non-interval output for performance improvement for hessians
  if nargin==2
    c = class(c,'intval');
  end

  setround(rndold)


validationMatrix = [1     1     0     0     0
                    1     0     1     0     0
                    0     0     0     0     0
                    0     0     0     1     0
                    0     0     0     0     1
                    0     0     0     0     0
                    0     0     0     0     1
                    0     0     0     0     0];

clusterer = NaiveClustererX();

clusters_test = clusterer.cluster(validationMatrix);

load('eval.mat');
assert(isequaln(clusters_test,clusters_eval));


function s = stdmv(X, dim);
% handles missing values (NaN).

error(nargchk(1,2,nargin));

if nargin < 2
  dim = min(find(size(X)~=1));
  if isempty(dim), dim = 1; end
end

sz = ones(length(size(X)), 1);
sz(dim) = size(X,dim);

% NaNs to zero
Imv = isnan(X);
X0 = X - repmat(meanmv(X,dim), sz);
X0(Imv) = 0;

% Sum and divide by the number of non-missing values
s = sum(X0.^2, dim) ./ sum(~Imv, dim);
%mu(isinf(xmean)) = NaN;


function [rot,zoom,frustum,origin] = mrmGetRotation(id)
% Get rotation and zoom
%
%   [rot,zoom,frustum] = mrmGetRotation(id)
%

p.actor=0; p.get_all=1;
[id,stat,r] = mrMesh('localhost', id, 'get', p);
zoom = diag(chol(r.rotation'*r.rotation))';
rotMat = r.rotation/diag(zoom);
frustum = r.frustum;
origin = r.origin;
% Note- there may be slight rounding errors allowing the inputs to
% asin/atan go outside of the range (-1,1). May want to clip those.
rot(2) = asin(rotMat(1,3));
if (abs(rot(2))-pi/2).^2 < 1e-9,
    rot(1) = 0;
    rot(3) = atan2(-rotMat(2,1), -rotMat(3,1)/rotMat(1,3));
else
    c      = cos(rot(2));
    rot(1) = atan2(rotMat(2,3)/c, rotMat(3,3)/c);
    rot(3) = atan2(rotMat(1,2)/c, rotMat(1,1)/c);
end
rot(1) = -rot(1); % flipped OpenGL Y-axis.
%fprintf('rot=[%0.6f %0.6f %0.6f];\nzoom=[%0.3f %0.3f %0.3f];\nfrustum=[%0.6f %0.6f %0.6f %0.6f];\n',rot,zoom,r.frustum);

return


function r = mpower(u,p)

%tstoolbox/@unit/mpower
%   Syntax:
%     * mpower(u,p)
%
%   take unit u to power p, p must be a scalar.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt

if ~isa(p, 'double')
	help(mfilename)
	return
end

if (u.exponents == [0 0 0 0 0 0 0 0]) & (~isempty(u.label))
	r = unit;
	r.factor = (u.factor)^(p);
	r.label = [u.label '^(' num2str(p) ')'];
else
	r.exponents = u.exponents * p;
	r.factor = (u.factor)^(p);
	r = unit([(u.factor)^(p) (u.exponents * p)]);
end


% Fig. 9.9  Feedback Control of Dynamic Systems, 5e
%             Franklin, Powell, Emami
% script to generate figure 9.9
% using the general simulation nonsim
clf;
N=0.4;
a=2.5;
r=0;
num=[1 1];
den=[1 0 0 ];
nf=1;
df=1;
hold on
grid on
for k=1:6
   r=r+2;
   sim('nonsim',30)
   plot(yn(:,1),yn(:,2))
end
title('Figure 9.9 Step responses of the nonlinear system')
xlabel('Time (sec)');
ylabel('y(t)');
gtext('r=2')
gtext('r=4')
gtext('r=6')
gtext('r=8')
gtext('r=10')
gtext('r=12')
hold off


function varargout = rank(varargin)
%RANK   Rank of a DISKFUN.
%   RANK(F) produces an estimate of the rank of F.
%
%   RANK(F, TOL) is the number of singular values of F greater than TOL*N,
%   where N is the first singular value of F.
%
% See also DISKFUN/LENGTH.

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

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

end


function [x,y]=wfmread(filename,mode)
% wfmread   :   Reads binary *.WFM file from a Tektronix TDS digitizer
% Usage:
% [x,y]=wfmread(filename,mode);
% x and y are one dimensional arrays containing the horizontal and vertical
% data from the signal contained in filename.
%
% filename is a character string name of a *.WFM file.  If filename is
% omitted or empty, a graphical window is launched to help the user choose
% the desired file.
%
% mode allows the user to get some extra information about the digitizer
% settings.  This feature is disabled by default, but can be activated by
% setting mode to 'verbose'.
%
%
% Notes:
% I wrote this a number of years ago as a graduate student so I could store
% many digitizer signals on a 3.5" floppy disk.  I cannot guarantee that
% this will work on more modern digitizers as Tektronix might change their
% format.  As with any function, use at your own risk
%
% Created 6/10/2000 by Daniel Dolan
% Last updated 9/14/2004
%

%%%%%%%%%%%%%%%%%%%%%
% argument checking %
%%%%%%%%%%%%%%%%%%%%%
if nargout<2
   error('Two outputs required');
end

switch nargin
case 0
   filename='';
   mode='quiet';
case 1
   mode='quiet';
case 2
   if ~strcmp(mode,'verbose')& ~strcmp(mode,'quiet')
      error('Invalid mode');
   end
otherwise
   error('Too many arguments');
end

if isempty(filename)
    [fname,pname]=uigetfile('*.wfm;*.WFM','Choose Tektronix WFM file');
    filename=[pname fname];
end

if exist(filename)~=2
   error('Invalid file name');
end

%%%%%%%%%%%%%%%%
% main program %
%%%%%%%%%%%%%%%%
[fp,message]=fopen(filename,'rb','b'); % big-endian format
if fp==-1
    error(['Unable to open file: ' filename]);
end

% main header
a=fread(fp,1,'uchar');
if char(a)==':'
   start=fread(fp,7,'uchar');
else
   start=fread(fp,6,'uchar');
end
start=char([a start']);
count_bytes=str2num(char(fread(fp,1,'uchar'))'); % number of bytes in count
bytes=str2num(char(fread(fp,count_bytes,'uchar'))'); % bytes to end of file
magic_num=fread(fp,1,'int32'); % "magic number"
length=fread(fp,1,'int32'); % length of header+curve data

% reference header
vertPos=fread(fp,1,'double');
horzPos=fread(fp,1,'double');
vertZoom=fread(fp,1,'double');
horzZoom=fread(fp,1,'double');

% waveform header
acqmode=fread(fp,1,'int16');
minMaxFormat=fread(fp,1,'int16');
duration=fread(fp,1,'double');
vertCpl=fread(fp,1,'int16');
horzUnit=fread(fp,1,'int16');
horzScalePerPoint=fread(fp,1,'double');
vertUnit=fread(fp,1,'int16');
vertOffset=fread(fp,1,'double');
vertPos=fread(fp,1,'double');
vertGain=fread(fp,1,'double');
%recordLength=fread(fp,1,'uint64');
recordLength=fread(fp,1,'uint32');
trigPos=fread(fp,1,'int16');
wfmHeaderVersion=fread(fp,1,'int16');
sampleDensity=fread(fp,1,'int16');
burstSegmentLength=fread(fp,1,'int16');
sourceWfm=fread(fp,1,'int16');
video1=fread(fp,3,'int16');
video2=fread(fp,1,'double');
video3=fread(fp,1,'int16');

% check to see extended header is present
if (length-2*recordLength-2*32)==196
   % stuff
end

% print some important info for the user
if strcmp(mode,'verbose')
   switch acqmode
   case 285
      fprintf('Sample Mode (number of data points= %d)\n',recordLength);
   end

   switch horzUnit
   case 609
      fprintf('Horizontal units are volts \n');
   case 610
      fprintf('Horizontal units are seconds \n');
      fprintf('\t Sampling rate= %g Hz \n',horzScalePerPoint)
      fprintf('\t Duration of sweep= %g s\n',duration);
   end

   switch vertUnit
   case 609
      fprintf('Vertical units are volts \n');
   case 610
      fprintf('Vertical units are seconds \n');
   end

   switch vertCpl
   case 565
      fprintf('DC coupling \n');
   case 566
      fprintf('AC coupling \n');
   end

end

% extract the data
preamble=fread(fp,16,'int16');
data=fread(fp,recordLength,'int16');
postamble=fread(fp,16,'int16');
checksum=fread(fp,1,'int16');
fclose(fp);

% calculate the x and y data series
ii=0:(recordLength-1);
x=(ii'-recordLength*trigPos/100)*horzScalePerPoint;
y=data*vertGain/25/256+vertOffset-vertPos*vertGain;


 function Xk = nufft_table_adj(st, X, order, flips, om)
%function Xk = nufft_table_adj(st, X, order, flips, om)
%| adjoint of table-based nufft interpolation.
%|
%| in
%|	st		structure from nufft_init
%|	X [M,nc]	DTFT values (usually nc=1)
%|	order	0|1	0th or 1st-order interpolation
%|			default is 0 for backward compatability
%|	flips	0|1	sign flips? (for real table with even N)
%|	om [M,1]	optional (default st.om)
%|
%| out
%|	Xk [*Kd,nc]	DFT coefficients
%|
%| Copyright 2004-3-30, Jeff Fessler and Yingying Zhang, University of Michigan

if nargin < 2, ir_usage, end

if ~isvar('order') || isempty(order)
	order = 0; % default 0th order for backward compatability
end

if ~isvar('flips') || isempty(flips)
	flips = zeros(size(st.Nd)); % default no flips for backward compatability
end

if nargin < 4
	om = st.om;
end

dd = length(st.Kd);

tm = zeros(size(om)); % must be double for mex file!
for id=1:dd
	gam = 2*pi / st.Kd(id);
	tm(:,id) = om(:,id) / gam; % t = omega / gamma
end

if size(X,1) ~= size(om,1)
	fail 'X size problem'
end

nc = size(X,2);

% adjoint of phase shift
class_X = class(X);
if isfield(st, 'phase_shift') && ~isempty(st.phase_shift)
	X = X .* repmat(conj(st.phase_shift), [1 nc]);
end

% convert X to complex double for mex file
if ~isa(X, 'double'), X = double(X); end

arg = {int32(st.Jd), int32(st.Ld), double(tm), int32(st.Kd(1:dd)), ...
	int32(order), int32(flips)};

X = complexify(X);

switch dd
case 1
	Xk = interp1_table_adj_mex(X, st.h{1}, arg{:});

case 2
	Xk = interp2_table_adj_mex(X, st.h{1}, st.h{2}, arg{:});

case 3
	Xk = interp3_table_adj_mex(X, st.h{1}, st.h{2}, st.h{3}, arg{:});

case 4
	Xk = interp4_table_adj_mex(X, st.h{1}, st.h{2}, st.h{3}, st.h{4}, arg{:});

otherwise
	fail '> 4d not done'
end
Xk = cast(Xk, class_X);


function out=prod(x,dim)

if ~isempty(x)

 precision=x(1).precision;
 % can only handle up to 2 dimensions
 s=size(x);
 if nargin==1
  if any(s==1)
   out=mp(1,precision);
   for ii=1:numel(x)
    out=out*x(ii);
   end
  else
   out=mp(ones(1,s(2)),precision);
   for j=1:s(2)
    for i=1:s(1)
     out(1,j)=out(1,j)*x(i,j);
    end
   end
  end
 elseif nargin==2
  if dim==1
   out=mp(ones(1,s(2)),precision);
   for j=1:s(2)
    for i=1:s(1)
     out(1,j)=out(1,j)*x(i,j);
    end
   end
  elseif dim==2
   out=mp(ones(s(1),1),precision);
   for j=1:s(2)
    for i=1:s(1)
     out(i,1)=out(i,1)*x(i,j);
    end
   end
  else
   error('mp prod can only handle up to 2-D arrays (11/04)');
  end
 end

else
 out=mp(1);
end


function outsig=comp_frsyn_fusion(F,insig)

W=size(insig,2);
L=size(insig,1)/framered(F);

outsig=zeros(L,W);

idx=0;
for ii=1:F.Nframes
    coeflen=L*framered(F.frames{ii});
    outsig=outsig+frsyn(F.frames{ii},insig(idx+1:idx+coeflen,:))*F.w(ii);
    idx=idx+coeflen;
end;


function K = covSum(cov, hyp, x, z, i)

% covSum - compose a covariance function as the sum of other covariance
% functions. This function doesn't actually compute very much on its own, it
% merely does some bookkeeping, and calls other covariance functions to do the
% actual work.
%
% Copyright (c) by Carl Edward Rasmussen & Hannes Nickisch 2010-09-10.
%
% See also COVFUNCTIONS.M.

if ~isempty(cov)==0, error('We require at least one summand.'), end
for ii = 1:numel(cov)                        % iterate over covariance functions
  f = cov(ii); if iscell(f{:}), f = f{:}; end   % expand cell array if necessary
  j(ii) = cellstr(feval(f{:}));                          % collect number hypers
end

if nargin<3                                        % report number of parameters
  K = char(j(1)); for ii=2:length(cov), K = [K, '+', char(j(ii))]; end, return
end
if nargin<4, z = []; end                                   % make sure, z exists
[n,D] = size(x);

v = [];               % v vector indicates to which covariance parameters belong
for ii = 1:length(cov), v = [v repmat(ii, 1, eval(char(j(ii))))]; end

if nargin<5                                                        % covariances
  K = 0; if nargin==3, z = []; end                                 % set default
  for ii = 1:length(cov)                      % iteration over summand functions
    f = cov(ii); if iscell(f{:}), f = f{:}; end % expand cell array if necessary
    K = K + feval(f{:}, hyp(v==ii), x, z);              % accumulate covariances
  end
else                                                               % derivatives
  if i<=length(v)
    vi = v(i);                                       % which covariance function
    j = sum(v(1:i)==vi);                    % which parameter in that covariance
    f  = cov(vi);
    if iscell(f{:}), f = f{:}; end         % dereference cell array if necessary
    K = feval(f{:}, hyp(v==vi), x, z, j);                   % compute derivative
  else
    error('Unknown hyperparameter')
  end
end


function VO = spm_smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = spm_smoothto8bit(V,fwhm)
% V     - mapped image to be smoothed
% fwhm  - FWHM of Guassian filter width in mm
% VO    - smoothed volume in a form that can be used by the
%         spm_*_vol.mex* functions.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_smoothto8bit.m 4310 2011-04-18 16:07:35Z guillaume $

if nargin>1 && fwhm>0,
    VO = smoothto8bit(V,fwhm);
else
    VO = V;
end
return;
%_______________________________________________________________________

%_______________________________________________________________________
function VO = smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = smoothto8bit(V,fwhm)
% V     - mapped image to be smoothed
% fwhm  - FWHM of Guassian filter width in mm
% VO    - smoothed volume in a form that can be used by the
%         spm_*_vol.mex* functions.
%_______________________________________________________________________

vx   = sqrt(sum(V.mat(1:3,1:3).^2));
s    = (fwhm./vx./sqrt(8*log(2)) + eps).^2;
r    = cell(1,3);
for i=1:3,
    r{i}.s = ceil(3.5*sqrt(s(i)));
    x      = -r{i}.s:r{i}.s;
    r{i}.k = exp(-0.5 * (x.*x)/s(i))/sqrt(2*pi*s(i));
    r{i}.k = r{i}.k/sum(r{i}.k);
end

buff = zeros([V.dim(1:2) r{3}.s*2+1]);

VO        = V;
VO.dt     = [spm_type('uint8') spm_platform('bigend')];
V0.dat    = uint8(0);
V0.dat(VO.dim(1:3)) = uint8(0);
VO.pinfo  = [];

for i=1:V.dim(3)+r{3}.s,
    if i<=V.dim(3),
        img      = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);
        msk      = find(~isfinite(img));
        img(msk) = 0;
        buff(:,:,rem(i-1,r{3}.s*2+1)+1) = ...
            conv2(conv2(img,r{1}.k,'same'),r{2}.k','same');
    else
        buff(:,:,rem(i-1,r{3}.s*2+1)+1) = 0;
    end

    if i>r{3}.s,
        kern    = zeros(size(r{3}.k'));
        kern(rem((i:(i+r{3}.s*2))',r{3}.s*2+1)+1) = r{3}.k';
        img     = reshape(buff,[prod(V.dim(1:2)) r{3}.s*2+1])*kern;
        img     = reshape(img,V.dim(1:2));
        ii      = i-r{3}.s;
        mx      = max(img(:));
        mn      = min(img(:));
        if mx==mn, mx=mn+eps; end
        VO.pinfo(1:2,ii) = [(mx-mn)/255 mn]';
        VO.dat(:,:,ii)   = uint8(round((img-mn)*(255/(mx-mn))));
    end
end


% Script to find valve actuator parameters that match frequency response
% using the direct method (time domain).
% Copyright 2010 MathWorks, Inc.

% This script file is designed to find three parameters of the
% valve actuator: Gain, Time Constant, and Saturation, by directly
% measuring its frequency response to sinusoidal signal at frequency
% at which the phase shift of the real actuator equals -90 deg.
% The script analyzes the valve actuator at two input signals: 100% and
% The script invokes the optimization procedure which is set to find match
% between the required and actual frequency characteristics. The
% characteristics are compared by the phase shift values at specified
% frequencies.
% After the optimization is completed, the check of the
% obtained parameters is performed with the same direct measurement method.

% Specifying required frequencies at which -90 deg phase shift occurs
frequency_20 = 25;      % Frequency (Hz) at -90 deg shift angle and 20% input
frequency_100 = 10;     % Frequency (Hz) at -90 deg shift angle and 100% input

% Set initial value. x0 =[gain, time_const, saturation]
x0 = [300, 0.01, 0.8];

[x,fval,exitflag,output] = ...
    fminsearch(@obj_actuator_param_direct_method,x0, ...
    optimset('Tolx',1e-3,'Display','iter'),frequency_20,frequency_100);

check_frequency_response(x,frequency_20,frequency_100,'Direct');


A = regressor;

An=bsxfun(@minus,A,mean(A,1));
Bn=bsxfun(@minus,M_0,mean(M_0,1));
tic
An=bsxfun(@times,An,1./sqrt(sum(An.^2,1)));
Bn=bsxfun(@times,Bn,1./sqrt(sum(Bn.^2,1)));
C=sum(An.*Bn,1);
toc

A = rand(3,3);
B = rand(3,3);


function test_ft_freqdescriptives

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_freqdescriptives
% DATATYPE freq

freq.label = {'1';'2'};
freq.freq  = 1:10;
freq.time  = 1:5;
freq.dimord = 'rpt_chan_freq_time';
freq.powspctrm = randn(100,2,10,5);

cfg = [];
cfg.variance = 'yes';
freqout = ft_freqdescriptives(cfg, freq);


function [S] = co2_sw(x)
% co2_sw.m
% Downloaded from the personal page of Professor Sigurd Skogestad
% http://www.nt.ntnu.no/users/skoge/diplom/prosjekt03/wold/MatLab/
[S] = Helmholtz_anonymous_23829804(x);

function [S] = Helmholtz_anonymous_23829804(x)

[S] = StandardState_anonymous_23817360(x);

function [S] = StandardState_anonymous_23817360(x)

[S]      = EquationOfState_anonymous_23031408(x);
i        = [3];
[S_1]    = MuT_cp_dippr_23809380(x(1));
S.g(1)   = S.g(1) + S_1.dmudT'*x(i);
S.g(i)   = S.g(i) + S_1.mu;
S.H(1,1) = S.H(1,1) + S_1.d2mudTdT'*x(i);
S.H(i,1) = S.H(i,1) + S_1.dmudT;
S.H(1,i) = S.H(i,1)';

function [S] = EquationOfState_anonymous_23031408(x)

[S]   = EquationOfState_anonymous_22908308(x);
[S_1] = ModTVN_ideal_idealgas_23028984(x);
S.g   = S.g + S_1.g;
S.H   = S.H + S_1.H;

function [S] = EquationOfState_anonymous_22908308(x)

[S] = ModTVN_sw_0_5_7_0_23818404(x);

function [S] = ModTVN_sw_0_5_7_0_23818404(x)

R               = 8.314511984;
T_c             = 304.1282;
rho_c           = 10624.90627;
tau             = T_c/x(1);
delta           = x(3)/x(2)/rho_c;
N               = x(3);
a_1             = [0.89875108;-2.1281985;-0.06819032;0.076355306;0.00022053253];
t_1             = [0.25;1.25;1.5;0.25;0.875];
d_1             = [1.0;1.0;1.0;3.0;7.0];
a_2             = [0.41541823;0.71335657;0.00030354234;-0.36643143;-0.0014407781;-0.089166707;-0.023699887];
t_2             = [2.375;2.0;2.125;3.5;6.5;4.75;12.5];
d_2             = [1.0;2.0;5.0;1.0;1.0;4.0;2.0];
p_2             = [1.0;1.0;1.0;2.0;2.0;2.0;3.0];
u_2             = d_2 - p_2.*delta.^p_2;
v_2             = exp(-delta.^p_2);
phir            = a_1'*(delta.^d_1.*tau.^t_1) + a_2'*(v_2.*delta.^d_2.*tau.^t_2);
phi_taur        = a_1'*(delta.^d_1.*t_1.*tau.^(t_1 - 1)) + a_2'*(v_2.*delta.^d_2.*t_2.*tau.^(t_2 - 1));
phi_deltar      = a_1'*(d_1.*delta.^(d_1 - 1).*tau.^t_1) + a_2'*(v_2.*delta.^(d_2 - 1).*u_2.*tau.^t_2);
phi_tautaur     = a_1'*(delta.^d_1.*t_1.*(t_1 - 1).*tau.^(t_1 - 2)) + a_2'*(v_2.*delta.^d_2.*t_2.*(t_2 - 1).*tau.^(t_2 - 2));
phi_deltadeltar = a_1'*(d_1.*(d_1 - 1).*delta.^(d_1 - 2).*tau.^t_1) + a_2'*(v_2.*delta.^(d_2 - 2).*(u_2.*(u_2 - 1) - p_2.^2.*delta.^p_2).*tau.^t_2);
phi_deltataur   = a_1'*(d_1.*delta.^(d_1 - 1).*t_1.*tau.^(t_1 - 1)) + a_2'*(v_2.*delta.^(d_2 - 1).*t_2.*u_2.*tau.^(t_2 - 1));
g_1             = N*R*(phir - tau*phi_taur);
g_2             = -R*T_c*rho_c*delta^2*phi_deltar/tau;
g_i             = R*T_c*(phir + delta*phi_deltar)/tau;
H_11            = N*R*tau^3*phi_tautaur/T_c;
H_21            = -R*delta^2*rho_c*(phi_deltar - tau*phi_deltataur);
H_i1            = R*(phir - tau*phi_taur + delta*(phi_deltar - tau*phi_deltataur));
H_22            = R*T_c*rho_c^2*delta^3*(delta*phi_deltadeltar + 2*phi_deltar)/(tau*N);
H_i2            = -R*T_c*rho_c*delta^2*(delta*phi_deltadeltar + 2*phi_deltar)/(tau*N);
H_ii            = R*T_c*delta*(delta*phi_deltadeltar + 2*phi_deltar)/(tau*N);
S.g             = [g_1;g_2;g_i];
S.H             = [H_11,H_21,H_i1;H_21,H_22,H_i2;H_i1,H_i2,H_ii];

function [S] = ModTVN_ideal_idealgas_23028984(x)

R     = 8.314511984;
pcirc = [101325.0];
xcirc = [1.0];
T     = x(1);
V     = x(2);
i     = [3];
n     = x(i);
NR    = sum(n)*R;
NRT   = NR*T;
e     = [1];
p     = R*log(R*T*(n./pcirc)/V);
g_1   = n'*p;
g_2   = -NRT/V;
g_i   = T*p;
H_11  = NR/T;
H_21  = -NR/V;
H_i1  = p + R*e;
H_22  = NRT/V^2;
H_i2  = -R*(T/V)*e;
H_ii  = R*T*diag(e./n);
S.g   = [g_1;g_2;g_i];
S.H   = [H_11,H_21',H_i1';H_21,H_22,H_i2';H_i1,H_i2,H_ii];

function [S] = MuT_cp_dippr_23809380(T)

t_0        = [298.15];
t_min      = [50.0];
t_max      = [5000.0];
C          = [29.37,34.54,1428.0,26.4,588.0];
c_1        = C(:,1);
c_2        = C(:,2);
c_3        = C(:,3);
c_4        = C(:,4);
c_5        = C(:,5);
c_p        = c_1 + c_2.*c_3.^2./(T^2*sinh(c_3/T).^2) + c_4.*c_5.^2./(T^2*cosh(c_5/T).^2);
h          = c_1*T + c_2.*c_3.*cosh(c_3/T)./sinh(c_3/T) - c_4.*c_5.*sinh(c_5/T)./cosh(c_5/T) - c_1.*t_0 - c_2.*c_3.*cosh(c_3./t_0)./sinh(c_3./t_0) + c_4.*c_5.*sinh(c_5./t_0)./cosh(c_5./t_0);
s          = c_1*log(T) + c_4.*(log(cosh(c_5/T)) - c_5.*sinh(c_5/T)./cosh(c_5/T)/T) + c_2.*(c_3.*cosh(c_3/T)./sinh(c_3/T)/T - log(sinh(c_3/T))) - c_1.*log(t_0) - c_4.*(log(cosh(c_5./t_0)) - c_5.*sinh(c_5./t_0)./cosh(c_5./t_0)./t_0) - c_2.*(c_3.*cosh(c_3./t_0)./sinh(c_3./t_0)./t_0 - log(sinh(c_3./t_0)));
S.mu       = h - T*s;
S.dmudT    = -s;
S.d2mudTdT = -(c_p/T);
i          = [1];
[S_1]      = MuT_hs_h0_23796420(T);
S.mu(i)    = S.mu(i) + S_1.mu;
S.dmudT(i) = S.dmudT(i) + S_1.dmudT;

function [S] = MuT_hs_h0_23796420(T)

hcirc   = [-393510.0];
[S]     = MuT_hs_s0_23790264(T);
S.mu    = S.mu + hcirc;
S.dmudT = S.dmudT + [0];

function [S] = MuT_hs_s0_23790264(T)

scirc   = [213.677];
S.mu    = -(T*scirc);
S.dmudT = -scirc;


function varargout = plotlattice(varargin)
%PLOTLATTICE  Plots an integer lattice
%
% p = plotlattice(C,which,c,size,options)
%
% Note that only convex sets C in R^2 are supported.
%
% C    :  Constraint object
% which:  'inner' or 'outer'
% color:  color [double] ([r g b] format) or char from 'rymcgbk'
% size :  Size of marker
% options: options structure from sdpsettings

varargin{1} = lmi(varargin{1});
if nargout == 0
     plotlattice(varargin{:});
else
    varargout{1} = plotlattice(varargin{:});
end


% DESCRIPTION:
%       subscript to scale source terms to the correct units
%
% ABOUT:
%       author      - Bradley Treeby
%       date        - 15th February 2012
%       last update - 20th January 2014
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

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

% get the dimension size
N = kgrid.dim;

% check for non-uniform grid and give error for source terms that haven't
% yet been implemented
if (nonuniform_grid && ( uy_source || uz_source || transducer_source))
    disp('WARNING: source scaling not implemented for non-uniform grids with given source condition');
    return
end

% Scale the input pressure by 1/c^2 (to convert to units of density), then
% by 1/N (to split the input across the split density field). If the
% pressure is injected as a mass source, also scale the pressure by
% 2*dt*c/dx to account for the time step and convert to units of
% [kg/(m^3 s)]
if p_source
    if strcmp(source.p_mode, 'dirichlet')
        if numel(c) == 1
            % compute the scale parameter based on the homogeneous
            % sound speed
            source.p = source.p ./ (N*c^2);
        else
            % compute the scale parameter seperately for each source
            % position based on the sound speed at that position
            for p_index = 1:length(source.p(:,1))
                source.p(p_index, :) = source.p(p_index, :) ./ (N*c(p_source_index(p_index))^2);
            end
        end
    else
        if nonuniform_grid

            % create empty matrix
            grid_point_sep = zeros(size(kgrid.x));

            % compute averaged grid point seperation map, the interior
            % points are calculated using the average distance to all
            % connected grid points (the edge values are not calculated
            % assuming there are no source points in the PML)
            switch kgrid.dim
                case 1
                    grid_point_sep(2:end-1) = kgrid.x_size*(kgrid.xn(3:end, 1) - kgrid.xn(1:end-2, 1))/2;
                case 2
                    grid_point_sep(2:end-1, 2:end-1) = ...
                        kgrid.x_size*(kgrid.xn(3:end, 2:end-1) - kgrid.xn(1:end-2, 2:end-1))/4 + ...
                        kgrid.y_size*(kgrid.yn(2:end-1, 3:end) - kgrid.yn(2:end-1, 1:end-2))/4;
                case 3
                    grid_point_sep(2:end-1, 2:end-1, 2:end-1) = ...
                        kgrid.x_size*(kgrid.xn(3:end, 2:end-1, 2:end-1) - kgrid.xn(1:end-2, 2:end-1, 2:end-1))/6 + ...
                        kgrid.y_size*(kgrid.yn(2:end-1, 3:end, 2:end-1) - kgrid.yn(2:end-1, 1:end-2, 2:end-1))/6 + ...
                        kgrid.z_size*(kgrid.zn(2:end-1, 2:end-1, 3:end) - kgrid.zn(2:end-1, 2:end-1, 1:end-2))/6;
            end

            % compute and apply scale parameter
            for p_index = 1:length(source.p(:,1))
                if numel(c) == 1
                    % compute the scale parameter based on the homogeneous sound speed
                    source.p(p_index, :) = source.p(p_index, :) .* (2.*dt./(N*c*grid_point_sep(p_source_index(p_index))));
                else
                    % compute the scale parameter based on the sound speed at that position
                    source.p(p_index, :) = source.p(p_index, :) .* (2.*dt./(N*c(p_source_index(p_index)).*grid_point_sep(p_source_index(p_index))));
                end
            end

            % clear unused variables
            clear grid_point_sep;

        else
            if numel(c) == 1
                % compute the scale parameter based on the homogeneous
                % sound speed
                source.p = source.p .* (2*dt./(N*c*kgrid.dx));
            else
                % compute the scale parameter seperately for each source
                % position based on the sound speed at that position
                for p_index = 1:length(source.p(:,1))
                    source.p(p_index, :) = source.p(p_index, :) .* (2.*dt./(N*c(p_source_index(p_index)).*kgrid.dx));
                end
            end
        end
    end
end

% scale the stress source by 1/N to divide amoungst the split field
% components, and if source.s_mode is not set to 'dirichlet', also scale by
% 2*dt*c/dx to account for the time step and convert to units of
% [kg/(m^3 s)]
if sxx_source
    if strcmp(source.s_mode, 'dirichlet') || p0_source
        source.sxx = source.sxx ./ N;
    else
        if numel(c) == 1
            % compute the scale parameter based on the homogeneous sound
            % speed
            source.sxx = source.sxx .* (2*dt*c./(N*kgrid.dx));
        else
            % compute the scale parameter seperately for each source
            % position based on the sound speed at that position
            for s_index = 1:length(source.sxx(:,1))
                source.sxx(s_index, :) = source.sxx(s_index, :) .* (2.*dt.*c(s_source_index(s_index))./(N*kgrid.dx));
            end
        end
    end
end
if syy_source
    if strcmp(source.s_mode, 'dirichlet') || p0_source
        source.syy = source.syy ./ N;
    else
        if numel(c) == 1
            % compute the scale parameter based on the homogeneous sound
            % speed
            source.syy = source.syy .* (2*dt*c./(N*kgrid.dx));
        else
            % compute the scale parameter seperately for each source
            % position based on the sound speed at that position
            for s_index = 1:length(source.syy(:,1))
                source.syy(s_index, :) = source.syy(s_index, :) .* (2.*dt.*c(s_source_index(s_index))./(N*kgrid.dx));
            end
        end
    end
end
if szz_source
    if strcmp(source.s_mode, 'dirichlet') || p0_source
        source.szz = source.szz ./ N;
    else
        if numel(c) == 1
            % compute the scale parameter based on the homogeneous sound
            % speed
            source.szz = source.szz .* (2*dt*c./(N*kgrid.dx));
        else
            % compute the scale parameter seperately for each source
            % position based on the sound speed at that position
            for s_index = 1:length(source.szz(:,1))
                source.szz(s_index, :) = source.szz(s_index, :) .* (2.*dt.*c(s_source_index(s_index))./(N*kgrid.dx));
            end
        end
    end
end
if sxy_source
    if strcmp(source.s_mode, 'dirichlet')
        source.sxy = source.sxy ./ N;
    else
        if numel(c) == 1
            % compute the scale parameter based on the homogeneous sound
            % speed
            source.sxy = source.sxy .* (2*dt*c./(N*kgrid.dx));
        else
            % compute the scale parameter seperately for each source
            % position based on the sound speed at that position
            for s_index = 1:length(source.sxy(:,1))
                source.sxy(s_index, :) = source.sxy(s_index, :) .* (2.*dt.*c(s_source_index(s_index))./(N*kgrid.dx));
            end
        end
    end
end
if sxz_source
    if strcmp(source.s_mode, 'dirichlet')
        source.sxz = source.sxz ./ N;
    else
        if numel(c) == 1
            % compute the scale parameter based on the homogeneous sound
            % speed
            source.sxz = source.sxz .* (2*dt*c./(N*kgrid.dx));
        else
            % compute the scale parameter seperately for each source
            % position based on the sound speed at that position
            for s_index = 1:length(source.sxz(:,1))
                source.sxz(s_index, :) = source.sxz(s_index, :) .* (2.*dt.*c(s_source_index(s_index))./(N*kgrid.dx));
            end
        end
    end
end
if syz_source
    if strcmp(source.s_mode, 'dirichlet')
        source.syz = source.syz ./ N;
    else
        if numel(c) == 1
            % compute the scale parameter based on the homogeneous sound
            % speed
            source.syz = source.syz .* (2*dt*c./(N*kgrid.dx));
        else
            % compute the scale parameter seperately for each source
            % position based on the sound speed at that position
            for s_index = 1:length(source.syz(:,1))
                source.syz(s_index, :) = source.syz(s_index, :) .* (2.*dt.*c(s_source_index(s_index))./(N*kgrid.dx));
            end
        end
    end
end

% if source.u_mode is not set to 'dirichlet', scale the x-direction
% velocity source terms by 2*dt*c/dx to account for the time step and
% convert to units of [m/s^2]
if ux_source && ~strcmp(source.u_mode, 'dirichlet')

    if nonuniform_grid

        % create empty matrix
        grid_point_sep = zeros(size(kgrid.x));

        % compute averaged grid point seperation map, the interior
        % points are calculated using the average distance to all
        % connected grid points (the edge values are not calculated
        % assuming there are no source points in the PML)
        grid_point_sep(2:end-1, :, :) = kgrid.x_size*(kgrid.xn(3:end, :, :) - kgrid.xn(1:end-2, :, :))/2;

        % compute and apply scale parameter
        for u_index = 1:length(source.ux(:,1))
            if numel(c) == 1
                % compute the scale parameter based on the homogeneous sound speed
                source.ux(u_index, :) = source.ux(u_index, :) .* (2*c*dt./(grid_point_sep(u_source_index(u_index))));
            else
                % compute the scale parameter based on the sound speed at that position
                source.ux(u_index, :) = source.ux(u_index, :) .* (2*c(u_source_index(u_index))*dt./(grid_point_sep(u_source_index(u_index))));
            end
        end

        % clear unused variables
        clear grid_point_sep;

    else

        if numel(c) == 1
            % compute the scale parameter based on the homogeneous sound speed
            source.ux = source.ux .* (2*c*dt./kgrid.dx);
        else
            % compute the scale parameter seperately for each source position
            % based on the sound speed at that position
            for u_index = 1:length(source.ux(:,1))
                source.ux(u_index, :) = source.ux(u_index, :) .* (2.*c(u_source_index(u_index)).*dt./kgrid.dx);
            end
        end
    end
end

% if source.u_mode is not set to 'dirichlet', scale the y-direction
% velocity source terms by 2*dt*c/dy to account for the time step and
% convert to units of [m/s^2]
if uy_source && ~strcmp(source.u_mode, 'dirichlet')
    if numel(c) == 1
        % compute the scale parameter based on the homogeneous sound speed
        source.uy = source.uy .* (2*c*dt./kgrid.dy);
    else
        % compute the scale parameter seperately for each source position
        % based on the sound speed at that position
        for u_index = 1:length(source.uy(:,1))
            source.uy(u_index, :) = source.uy(u_index, :) .* (2.*c(u_source_index(u_index)).*dt./kgrid.dy);
        end
    end
end

% if source.u_mode is not set to 'dirichlet', scale the z-direction
% velocity source terms by 2*dt*c/dz to account for the time step and
% convert to units of [m/s^2]
if uz_source && ~strcmp(source.u_mode, 'dirichlet')
    if numel(c) == 1
        % compute the scale parameter based on the homogeneous sound speed
        source.uz = source.uz .* (2*c*dt./kgrid.dz);
    else
        % compute the scale parameter seperately for each source position
        % based on the sound speed at that position
        for u_index = 1:length(source.uz(:,1))
            source.uz(u_index, :) = source.uz(u_index, :) .* (2.*c(u_source_index(u_index)).*dt./kgrid.dz);
        end
    end
end

% scale the transducer source term by 2*dt*c/dx to account for the time
% step and convert to units of [m/s^2]
if transducer_source
    if numel(c) == 1
        transducer_input_signal = transducer_input_signal .* (2*c*dt./kgrid.dx);
    else
        % compute the scale parameter based on the average sound speed at the
        % transducer positions (only one input signal is used to drive the
        % transducer)
        transducer_input_signal = transducer_input_signal.* (2*(mean(c(u_source_index)))*dt./kgrid.dx);
    end
end

% clear subscript variables
clear N;


function x=make_odd(x)
if(~mod(x,2)), x=x-1; end


%%%
%
% For attention-based models, given:
%   grad_contextVecs: lstmSize * batchSize
%   alignWeights: numPositions * batchSize.
%   srcHidVecs: lstmSize * batchSize * numPositions.
% compute the following grads:
%   grad_srcHidVecs: lstmSize * batchSize * numPositions
%   grad_alignWeights: numPositions * batchSize
%
% Thang Luong @ 2015, <lmthang@stanford.edu>
%
%%%
function [grad_alignWeights, grad_srcHidVecs] = contextLayerBackprop(grad_contextVecs, alignWeights, srcHidVecs, unmaskedIds, params)
  % change from grad_contextVecs lstmSize*batchSize -> lstmSize*batchSize*1
  grad_contextVecs = permute(grad_contextVecs, [1, 2, 3]);

  %% Grad formulae:
  %   contextVecs = H_src* a_t
  %   grad_srcHidVecs: outGrad * alignWeights'
  %   grad_alignWeights = H_src' * contexGrad (per example, to scale over multiple examples, i.e., batchSize, need to use bsxfun)

  %% grad_srcHidVecs
  grad_srcHidVecs = zeroMatrix(size(srcHidVecs), params.isGPU, params.dataType);
  grad_srcHidVecs(:, unmaskedIds, :) = bsxfun(@times, grad_contextVecs(:, unmaskedIds), permute(alignWeights(:, unmaskedIds), [3, 2, 1])); % change alignWeights -> 1 * batchSize * numPositions

  %% grad_alignWeights
  grad_alignWeights = zeroMatrix(size(alignWeights), params.isGPU, params.dataType);
  if size(srcHidVecs, 3)==1
    grad_alignWeights(:, unmaskedIds) = sum(bsxfun(@times, srcHidVecs(:, unmaskedIds, :), grad_contextVecs(:, unmaskedIds)), 1); % sum across lstmSize: numPositions * batchSize
  else
    grad_alignWeights(:, unmaskedIds) = squeeze(sum(bsxfun(@times, srcHidVecs(:, unmaskedIds, :), grad_contextVecs(:, unmaskedIds)), 1))'; % sum across lstmSize: numPositions * batchSize
  end

  %% assert
  if params.assert
    assert(isequal(size(grad_alignWeights), size(alignWeights)));

    % compute grad_srcHidVec in a different way
    grad_srcHidVecs1 = zeroMatrix(size(grad_srcHidVecs), params.isGPU, params.dataType);
    for jj=1:length(unmaskedIds)
      ii = unmaskedIds(jj);
      grad_srcHidVecs1(:, ii, :) = grad_contextVecs(:, ii, 1) * alignWeights(:, ii)';
    end
    assert(computeSum(grad_srcHidVecs1-grad_srcHidVecs, params.isGPU)==0);
  end
end


function [nconds,cforecast_record,cforecast_estimates]=...
    panel2cf(N,n,m,p,k,q,cfconds,cfshocks,cfblocks,data_endo_a,data_exo_a,data_exo_p,It,Bu,Fperiods,const,beta_gibbs,D_record,gamma_record,CFt,Fband)

% initiate the cell recording the Gibbs sampler draws
cforecast_record={};
cforecast_estimates={};

% because conditional forecasts can be computed for many (potentially all) units, loop over units
for ii=1:N
% check wether there are any conditions on unit ii
temp=cfconds(:,:,ii);
nconds(ii,1)=numel(temp(cellfun(@(x) any(~isempty(x)),temp)));

   % if there are conditions
   if nconds(ii,1)~=0
   % prepare the elements for conditional forecast estimation, depending on the type of conditional forecasts
   temp1=cfconds(:,:,ii);
      if CFt==1
      temp2={};
      temp3=[];
      elseif CFt==2
      temp2=cfshocks(:,:,ii);
      temp3=cfblocks(:,:,ii);
      end
   % run the Gibbs sampler for unit ii
   cforecast_record(:,:,ii)=bear.cforecast(data_endo_a(:,:,ii),data_exo_a,data_exo_p,It,Bu,Fperiods,temp1,temp2,temp3,CFt,const,beta_gibbs,D_record,gamma_record,n,m,p,k,q);
   % then obtain point estimates and credibility intervals
   cforecast_estimates(:,:,ii)=bear.festimates(cforecast_record(:,:,ii),n,Fperiods,Fband);

   % if there are no conditions, return empty elements
   elseif nconds(ii,1)==0
   cforecast_record(:,:,ii)=cell(n,1);
   cforecast_estimates(:,:,ii)=cell(n,1);
   end
end


%==================================================================
%                        General Data File
% Title: Default_title
% Units: SI
% Dimensions: 2D
% Type of problem: Plane_Stress
% Type of Phisics: Stokes
% Micro/Macro: MACRO
%
%==================================================================

%% Data

Data_prb = {
'TRIANGLE';
'SI';
'2D';
'Plane_Stress';
'Stokes';
'MACRO';
};

%% Coordinates
% Node                X                Y                Z

coord = [
1            0            0            0
2            0         0.25            0
3         0.25            0            0
4         0.25         0.25            0
5            0          0.5            0
6          0.5            0            0
7         0.25          0.5            0
8          0.5         0.25            0
9          0.5          0.5            0
10         0.75            0            0
11            0         0.75            0
12         0.75         0.25            0
13         0.25         0.75            0
14         0.75          0.5            0
15          0.5         0.75            0
16            1            0            0
17            0            1            0
18            1         0.25            0
19         0.25            1            0
20         0.75         0.75            0
21            1          0.5            0
22          0.5            1            0
23         0.75            1            0
24            1         0.75            0
25            1            1            0
];

%% Conectivities
% Element        Node(1)                Node(2)                Node(3)                Material

connec = [
1 6 8 3 0
2 8 9 4 0
3 3 4 1 0
4 8 4 3 0
5 9 7 4 0
6 7 5 2 0
7 4 2 1 0
8 7 2 4 0
9 16 18 10 0
10 18 21 12 0
11 10 12 6 0
12 18 12 10 0
13 21 14 12 0
14 14 9 8 0
15 12 8 6 0
16 14 8 12 0
17 9 15 7 0
18 15 22 13 0
19 7 13 5 0
20 15 13 7 0
21 22 19 13 0
22 19 17 11 0
23 13 11 5 0
24 19 11 13 0
25 21 24 14 0
26 24 25 20 0
27 14 20 9 0
28 24 20 14 0
29 25 23 20 0
30 23 22 15 0
31 20 15 9 0
32 23 15 20 0
];

%% Variable Prescribed
% Node            Dimension                Value

velocity = [
1 1 0
1 2 0
5 1 0
5 2 0
6 1 0
6 2 0
16 1 0
16 2 0
17 1 0
17 2 0
21 1 0
21 2 0
22 1 0
22 2 0
25 1 0
25 2 0
];

pressure = [
25 1 0
];

nu=1;
Vol_force = @(x,y){nu*4*(x^3*((6 - 12*y)) + x^4*((-3 + 6*y)) + y*(1 - 3*y + 2*y^2)-6*x*y*(1 - 3*y + 2*y^2)...
+ 3*x^2*((-1 + 4*y - 6*y^2 + 4*y^3)))+(2*x-1)*(y-1);
-4*nu*(-3*((-1 + y)^2)*y^2 - 3*x^2*((1 - 6*y + 6*y^2))+2*x^3*((1 - 6*y + 6*y^2)) +...
x*(1 - 6*y + 12*y^2 - 12*y^3 + 6*y^4))+x*(x-1)};

% nu=1;
% Vol_force = @(x,y){nu*4*(x^3*((6 - 12*y)) + x^4*((-3 + 6*y)) + y*(1 - 3*y + 2*y^2)-6*x*y*(1 - 3*y + 2*y^2)...
% + 3*x^2*((-1 + 4*y - 6*y^2 + 4*y^3)))+nu*y*(1 - y)*(1 - 2*x);
% -4*nu*(-3*((-1 + y)^2)*y^2 - 3*x^2*((1 - 6*y + 6*y^2))+2*x^3*((1 - 6*y + 6*y^2)) +...
% x*(1 - 6*y + 12*y^2 - 12*y^3 + 6*y^4)+x*(1 - x)*(1 - 2*y))};

%% Group Elements
% Element        Group_num

Group = [
];

%% Initial Holes
% Elements that are considered holes initially
% Element

Initial_holes = [
];

%% Boundary Elements
% Elements that can not be removed
% Element

Boundary_elements = [
];

%% Micro gauss post
%
% Element

Micro_gauss_post = [
];

%% Micro Slave-Master
% Nodes that are Slaves
% Nodes             Value (1-Slave,0-Master)

Micro_slave = [
];

%% Nodes solid
% Nodes that must remain
% Nodes

% nodesolid = unique(pointload_complete(:,1));

%% External border Elements
% Detect the elements that define the edge of the domain
% Element               Node(1)           Node(2)

External_border_elements = [
1 3 6
3 1 3
6 5 2
7 2 1
9 16 18
9 10 16
10 18 21
11 6 10
21 22 19
22 17 11
22 19 17
23 11 5
25 21 24
26 24 25
29 25 23
30 23 22
];

%% External border Nodes
% Detect the nodes that define the edge of the domain
% Node

External_border_nodes = [
];

%% Materials
% Materials that have been used
% Material_Num              Mat_density        Young_Modulus        Poisson

Materials = [
];


function [I,J,K,IND]=logic2subind(L)

[J,I,K]=meshgrid(1:1:size(L,2),1:1:size(L,1),1:1:size(L,3));
I=I(L); J=J(L); K=K(L);
IND = sub2ind(size(L),I,J,K);

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% 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 3 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, see <http://www.gnu.org/licenses/>.


function meandpth() % autogenerated function wrapper
    %  meandpth  finds the average depth for a predefined running
    %  window in terms of number of events, and a selected step
    %  and plots the results.
    %                                                     R.Z. 6/94
    %                          Operates on ZG.newcat
    %
    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals
    report_this_filefun(mfilename('fullpath'));

    if ic == 1 || ic == 0
        if isempty(ZG.newcat) ZG.newcat = ZG.primeCatalog; end
        ZG.newcat = ZG.primeCatalog;
        iwln = 100;
        step = 28;
        winlen_days = 2;

        figure_w_normalized_uicontrolunits(...
            'Name','MeanDepth Input Parameters',...
            'visible','off',...
            'NumberTitle','off', ...
            'NextPlot','new', ...
            'Units','Pixel',  'Position',[ZG.welcome_pos 550 200'])
        axis off
        set(gca,'visible','off');

        % creates a dialog box to input some parameters
        %

        freq_field=uicontrol('Style','edit',...
            'Position',[.70 .60 .17 .10],...
            'Units','normalized','String',num2str(iwln),...
            'callback',@callbackfun_001);

        inp2_field=uicontrol('Style','edit',...
            'Position',[.70 .40 .17 .10],...
            'Units','normalized','String',num2str(step),...
            'callback',@callbackfun_002);

        close_button=uicontrol('Style','Pushbutton',...
            'Position', [.60 .05 .15 .15 ],...
            'Units','normalized','callback',@callbackfun_003,'String','Cancel');

        go_button=uicontrol('Style','Pushbutton',...
            'Position',[.25 .05 .15 .15 ],...
            'Units','normalized',...
            'callback',@callbackfun_004,...
            'String','Go');

        txt1 = text(...
            'Position',[0. 0.65 0 ],...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold' ,...
            'String','Number of events in averaging window:');

        txt2 = text(...
            'Position',[0. 0.40 0 ],...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold' ,...
            'String','Time-step in days:');

        set(gcf,'visible','on')

    elseif ic == 2

        step = days(step);
        if isempty(ZG.newcat) ZG.newcat = ZG.primeCatalog; end
        len = ZG.newcat.Count;
        xt2  = [ ];
        meand = [ ];
        er = [];
        [t0b, teb] = ZG.newcat.DateRange() ;
        ind = 0;

        me = [];
        b = ZG.primeCatalog;

        sta = ZG.primeCatalog.Date(iwln+1);
        sto = max(ZG.primeCatalog.Date);
        for it=sta+step:step:sto
            ind = ind + 1;
            t = find( abs(b.Date-it)  == min(abs(b.Date-it)));
            if t <= iwln ; t = iwln+1; end
            meand(ind) =  mean(ZG.newcat(t-iwln:t,7)) ;
            er(ind) =  std(ZG.newcat(t-iwln:t,7)) ;
            xt2(ind) = it;        % time is end of window
        end    % for it

        meand = -meand;

        % Find out if figure already exists
        %
        depfg=findobj('Type','Figure','-and','Name','Mean Depth');

        % Set up the Seismicity Map window Enviroment
        %
        if isempty(depfg)

            depfg=figure_w_normalized_uicontrolunits(...
                'Name','Mean Depth',...
                'visible','off',...
                'NumberTitle','off', ...
                'NextPlot','new', ...
                'Units','Pixel',  'Position',[ZG.welcome_pos 550 400']);
            hold on
            axis off

            uicontrol('Style','Pushbutton',...
                'Position',[.9 .80 .10 .05],...
                'Units','normalized',...
                'callback',@(~,~)medispas1('ast'),'String','AS');
            uicontrol('Style','Pushbutton',...
                'Position',[.9 .70 .10 .05],...
                'Units','normalized',...
                'callback',@(~,~)medispas1('lta'),'String','LTA');
            uicontrol('Style','Pushbutton',...
                'Position',[.9 .90 .10 .05],...
                'Units','normalized',...
                'callback',@callbackfun_007,'String','Com');

            new = uicontrol('style','edit','value',winlen_days,...
                'string',num2str(winlen_days), 'background','y',...
                'callback',@callbackfun_008,...
                'units','norm','pos',[.90 .30 .10 .06],'min',0.1,'max',100);

            newlabel = uicontrol('style','text','units','norm','pos',[.85 .30 .05 .06]);
            set(newlabel,'string','winlen_days:','background',color_fbg);

            uicontrol('Units','normal',...
                'Position',[.90 .25 .08 .06],'String','Go',...
                'callback',@callbackfun_009)

        end  % if figure exist

        figure(depfg);
        delete(findobj(depfg,'Type','axes'));
        set(gca,'visible','off');

        %orient tall
        set(gcf,'Units','centimeter','PaperPosition',[1 1 7 8])
        rect = [0.15, 0.15, 0.65, 0.30];
        axes('position',rect)
        p5 = gca;

        % plot errbar
        errorbar(xt2,meand,er)
        hold on
        plot(xt2,meand,'co')
        pl = plot(xt2,meand,'-r')
        hold on
        set(pl,'LineWidth',1.0)
        if ~isempty(ZG.maepi)
            pl =   plot(ZG.maepi.Date,ZG.maepi.Date*0+mean(meand),'xm');
            set(pl,'LineWidth',2.0)
        end

        axis([min(ZG.newcat.Date) max(ZG.newcat.Date+0.1) min(meand*1.1)  max(meand*0.9)])
        v = axis;
        xlabel('Time (years)','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')
        ylabel('Mean Depth (km)','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')
        stri = ['Mean Depths and standard deviation ( ' file1 ')'];
        %title(' Mean depths and mean depth error ',...
        %        'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')
        set(gca,'box','on',...
            'SortMethod','childorder','TickDir','out','FontWeight',...
            'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2)

        grid
        hold off

        rect = [0.15,  0.45, 0.65, 0.30];
        axes('position',rect)
        pl =plot(ZG.newcat.Date,-ZG.newcat.Depth,'.b')
        set(pl,'MarkerSize',3')
        set(pl,'LineWidth',1.0)
        hold on
        if ~isempty(ZG.maepi)
            pl =  plot(ZG.maepi.Date,-ZG.maepi.Depth,'xm');
            set(pl,'LineWidth',2.0)
        end
        axis([ v(1) v(2) -max(ZG.newcat.Depth)  -min(ZG.newcat.Depth)])
        ylabel('Depth (km)','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')
        set(gca,'XTicklabels',[])
        stro = [' ' file1 '; wl = ' num2str(iwln) ' events, inc = ' num2str(step)];
        title(stro,'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.m,'Color','k')
        grid

        set(gca,'box','on',...
            'SortMethod','childorder','TickDir','out','FontWeight',...
            'bold','FontSize',ZmapGlobal.Data.fontsz.m,'Linewidth',1.2)

        set(gca,'visible','on');
        set(gcf,'visible','on');

        ic = 1;

    end    % if ic

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        iwln=str2double(freq_field.String);
        freq_field.String=num2str(iwln);
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        step=str2double(inp2_field.String);
        inp2_field.String=num2str(step);
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        close;

    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ic = 2;
        close;
        clear meandpth;
        meandpth;
    end

    function callbackfun_007(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        dispma4();
    end

    function callbackfun_008(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        update_editfield_value(mysrc,myevt);
        winlen_days=mysrc.Value;
        medispas1();
    end

    function callbackfun_009(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        medispas1();
    end

end


function edges = crackPattern2(box, points, alpha, varargin)
%CRACKPATTERN2 Create a (bounded) crack pattern tessellation.
%
%   E = crackPattern2(BOX, POINTS, ALPHA)
%   create a crack propagation pattern wit following parameters :
%   - pattern is bounded by area BOX which is a polygon.
%   - each crack originates from points given in POINTS
%   - directions of each crack is given by a [NxM] array ALPHA, where M is
%   the number of rays emanating from each seed/
%   - a crack stop when it reaches another already created crack.
%   - all cracks stop when they reach the border of the frame, given by box
%   (a serie of 4 points).
%   The result is a collection of edges, in the form [x1 y1 x2 y2].
%
%   E = crackPattern2(BOX, POINTS, ALPHA, SPEED)
%   Also specify speed of propagation of each crack.
%
%
%   See the result with :
%     figure;
%     drawEdge(E);
%
%   See also drawEdge

% ------
% Author: David Legland
% E-mail: david.legland@inrae.fr
% Created: 2004-05-25
% Copyright 2004-2022 INRA - TPV URPOI - BIA IMASTE

if ~isempty(varargin)
    speed = varargin{1};
else
    speed = ones(size(points, 1), 1);
end

% Compute line equations for each initial crack.
% The 'Inf' at the end correspond to the position of the limit.
% If an intersection point is found with another line, but whose position
% is after this value, this means that another crack stopped it before it
% reach the intersection point.
NP = size(points, 1);
lines = zeros(0, 5);
for i = 1:size(alpha, 2)
    lines = [lines; points speed.*cos(alpha(:,i)) speed.*sin(alpha(:,i)) Inf*ones(NP, 1)]; %#ok<AGROW>
end
NL = size(lines, 1);

% initialize lines for borders, but assign a very high speed, to be sure
% borders will stop all cracks.
dx = (box([2 3 4 1],1)-box([1 2 3 4],1))*max(speed)*5;
dy = (box([2 3 4 1],2)-box([1 2 3 4],2))*max(speed)*5;

% add borders to the lines set
lines = [lines ; createLine(box, dx, dy) Inf*ones(4,1)];

edges = zeros(0, 4);

while true
    modif = 0;

    % try to update each line
	for i=1:NL

        % initialize first point of edge
        edges(i, 1:2) = lines(i, 1:2);

        % compute intersections with all other lines
        pi = intersectLines(lines(i,:), lines);

        % compute position of all intersection points on the current line
        pos = linePosition(pi, lines(i,:));

        % consider points to the right (positive position), and sort them
        indr = find(pos>1e-12 & pos~=Inf);
        [posr, indr2] = sort(pos(indr));

        % look for the closest intersection to the right
        for i2=1:length(indr2)

            % index of intersected line
            il = indr(indr2(i2));

            % position of point relative to intersected line
            pos2 = linePosition(pi(il, :), lines(il, :));

            % depending on the sign of position, tests if the line2 can
            % stop the current line, or if it was stopped before
            if pos2>0
                if pos2<abs(posr(i2)) && pos2<lines(il, 5)
                    if lines(i, 5) ~= posr(i2)
                        edges(i, 3:4) = pi(il,:);
                        lines(i, 5) = posr(i2);
                        modif = 1;
                    end
                    break;
                end
            end
        end   % end processing of right points of the line

	end % end processing of all lines

    % break the infinite loop if no more modification was made
    if ~modif
        break;
    end
end

% add edges of the surronding box.
edges = [edges ; box(1,:) box(2,:) ; box(2,:) box(3,:); ...
                 box(3,:) box(4,:) ; box(4,:) box(1,:)  ];


function test_bug2221

% MEM 1gb
% WALLTIME 00:15:00
% DEPENDENCY ft_selectdata ft_selectdata_new ft_multiplotER

% this test function intends to test the functionality of:
%  - ft_selectdata_new with respect to multiple input: does it correctly
%  identifies the intersection between the multiple input dimensions?
%  - ft_selectdata_new (new functionality): take a union rather than
%  intersection, this is to be built in as an optional switch
%  - ft_multiplotER: if input data contains not entirely overlapping time
%  axes, use selectdata for getting the union and plotting should then work

% as of september 2019, ft_selectdata_new/old have become obsolete, and the
% explicit call of ft_selectdata_new has been replaced by a call to
% ft_selectdata

% create some data first
freq1 = [];
freq1.label = {'chan01';'chan02'};
freq1.freq  = (1:10);
freq1.time  = (1:15);
freq1.powspctrm = randn(2,10,15);
freq1.dimord = 'chan_freq_time';

freq2 = freq1;
freq2.powspctrm = randn(2,8,12);
freq2.label = {'chan02';'chan03'};
freq2.freq  = (5:12);
freq2.time  = (3:14);

cfg                  = [];
cfg.select           = 'intersect';
[freq1out, freq2out] = ft_selectdata(cfg,freq1,freq2);
assert(isequal(rmfield(freq1out, {'cfg','powspctrm'}),rmfield(freq2out, {'cfg','powspctrm'})));

cfg.select        = 'union';
[freq1out, freq2out] = ft_selectdata(cfg,freq1,freq2);

%%%%%%%%%%%
filename = dccnpath('/home/common/matlab/fieldtrip/data/test/bug2221.mat');
load(filename);

data1 = data_S10_cond1;
data2 = data_S10_cond2;
cfg = [];
cfg.select  = 'intersect';

[data1out, data2out] = ft_selectdata(cfg, data1, data2);


function [GP dataOut] = iGPRFun(data, options)
GP = [];
dataOut = [];
PtsNumThr = options.PtsNumThr;
epsilon = options.epsilon;
MinPts = options.MinPts;
tData = options.tData;
tDist = options.tDist;
if size(data, 2) <= PtsNumThr
    return;
end
[~, ValidIdx] = Cluster(data, MinPts, epsilon, PtsNumThr);
if length(ValidIdx) <= options.PtsNumThr % point number is smaller than PtsNumThr
    return;
end
GP = GPR_CurbNew_IV(data, ValidIdx, options, []);
dataOut =  GP.data(GP.ValidIdx, : )';   % data0 is valid road edge points.
end


function [pdc, pdcvar, n] = ft_connectivity_pdc(input, varargin)

% FT_CONNECTIVITY_PDC computes partial directed coherence. This function implements
% the metrices described in Baccala et al., Biological Cybernetics 2001, 84(6),
% 463-74. and in Baccala et al., 15th Int.Conf.on DSP 2007, 163-66.
%
% The implemented algorithm has been tested against the implementation in the
% SIFT-toolbox. It yields numerically identical results to what is known there as
% 'nPDC' (for PDC) and 'GPDC' for generalized pdc.
%
% Use as
%   [p, v, n] = ft_connectivity_pdc(h, key1, value1, ...)
%
% The input argument H should be a spectral transfer matrix organized as
%   Nrpt x Nchan x Nchan x Nfreq (x Ntime),
% where Nrpt can be 1.
%
% Additional optional input arguments come as key-value pairs:
%   'hasjack'  = 0 (default) is a boolean specifying whether the input
%                contains leave-one-outs, required for correct variance
%                estimate
%   'feedback' = string, determining verbosity (default = 'none'), see FT_PROGRESS
%   'invfun'   = 'inv' (default) or 'pinv', the function used to invert the
%                transfer matrix to obtain the fourier transform of the
%                MVAR coefficients. Use 'pinv' if the data are
%                poorly-conditioned.
%   'noisecov' = matrix containing the covariance of the residuals of the
%                MVAR model. If this matrix is defined, the function
%                returns the generalized partial directed coherence.
%
% Output arguments:
%   p = partial directed coherence matrix Nchan x Nchan x Nfreq (x Ntime).
%       If multiple observations in the input, the average is returned.
%   v = variance of p across observations.
%   n = number of observations.
%
% Typically, nrpt should be 1 (where the spectral transfer matrix is
% computed across observations. When nrpt>1 and hasjack is true the input
% is assumed to contain the leave-one-out estimates of H, thus a more
% reliable estimate of the relevant quantities.
%
% See also FT_CONNECTIVITYANALYSIS

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

hasjack  = ft_getopt(varargin, 'hasjack', 0);
feedback = ft_getopt(varargin, 'feedback', 'none');
invfun   = ft_getopt(varargin, 'invfun', 'inv');
noisecov = ft_getopt(varargin, 'noisecov');

switch invfun
  case {'inv' 'pinv'}
    invfun = str2func(invfun);
  otherwise
    ft_error('unknown specification of inversion-function for the transfer matrix');
end

% crossterms are described by chan_chan_therest
siz = [size(input) 1];
n   = siz(1);

if ~isempty(noisecov)
  ft_progress('init', feedback, 'computing generalized partial directed coherence...');
  scale = diag(sqrt(1./diag(noisecov))); % get the 1./sqrt(var) of the signals
else
  ft_progress('init', feedback, 'computing partial directed coherence...');
  scale = eye(siz(2));
end

% pre-allocate some variables
outsum = zeros(siz(2:end));
outssq = zeros(siz(2:end));

% the mathematics for pdc is most straightforward using the inverse of the
% transfer function
pdim     = prod(siz(4:end));
tmpinput = reshape(input, [siz(1:3) pdim]);
ft_progress('init', feedback, 'inverting the transfer function...');
for k = 1:n
  ft_progress(k/n, 'inverting the transfer function for replicate %d from %d\n', k, n);
  tmp = reshape(tmpinput(k,:,:,:), [siz(2:3) pdim]);
  for m = 1:pdim
    tmp(:,:,m) = scale*invfun(tmp(:,:,m));
  end
  tmpinput(k,:,:,:) = tmp;
end
ft_progress('close');
input = reshape(tmpinput, siz);

for j = 1:n
  ft_progress(j/n, 'computing metric for replicate %d from %d\n', j, n);
  invh   = reshape(input(j,:,:,:,:), siz(2:end));

  den    = sum(abs(invh).^2,1);
  tmppdc = abs(invh)./sqrt(repmat(den, [siz(2) 1 1 1 1]));

  outsum = outsum + tmppdc;
  outssq = outssq + tmppdc.^2;
end
ft_progress('close');

pdc = outsum./n;

if n>1
  if hasjack
    bias = (n-1).^2;
  else
    bias = 1;
  end
  pdcvar = bias*(outssq - (outsum.^2)./n)./(n - 1);
else
  pdcvar = [];
end

% this is to achieve the same convention for all connectivity metrics:
% row -> column
for k = 1:prod(siz(4:end))
  pdc(:,:,k)    = transpose(pdc(:,:,k));
  if ~isempty(pdcvar)
    pdcvar(:,:,k) = transpose(pdcvar(:,:,k));
  end
end


report_this_filefun(mfilename('fullpath'));
%load /nfs/alaska/home/stefan
b = a;

% Hier vielleicht dx, dy aendern ...
ve = [];dx = 0.1; dy = 0.1;

x0 = min(a.Longitude);
x1 = max(a.Longitude);
y0 = min(a.Latitude);
y1 = max(a.Latitude);

for x = x0:dx:x1
    for y = y0:dy:y1
        ve =    [ ve ; x y ];
    end
end

le = length(ve);
Y0 = zeros(le,1);

% Hier muss die richtige abminderung rein ...
for i = 1:length(b)
    di2 = deg2km((distance(ve(:,2),ve(:,1),repmat(b(i,2),le,1),repmat(b(i,1),le,1))));
    R = di2;
    r = sqrt(R.^2 + 5.57^2);
    M = b(i,6); % wenn mit felhler: + dM  (random mit standart)
    Y = -0.136 + 0.229*(M-6) - 0.778 * log10(r) ;
    Y = 10.^Y;
    c = [Y , Y0];
    mapga = max(c');
    Y0 = mapga';
end

mapga = mapga';

l1 = length(x0:dx:x1);
l2 = length(y0:dy:y1);

re = reshape(mapga,l2,l1);
rey = reshape(ve(:,2),l2,l1);
rex = reshape(ve(:,1),l2,l1);

figure
pcolor(rex,rey,re)
hold on
shading interp
overlay
colorbar


function varargout = pow10(varargin)
%POW10 (overloaded)

varargout{1} = 10.^varargin{1};


%generalized_sylvester_direct2 is a function.
%    [Tzz, retcode] = generalized_sylvester_direct2(A, B, C, fv_lamba_bf, W)
%


function FB = FbMake( dim, flag, show )
% Various 1D/2D/3D filterbanks (hardcoded).
%
% USAGE
%  FB = FbMake( dim, flag, [show] )
%
% INPUTS
%  dim     - dimension
%  flag    - controls type of filterbank to create
%          - if d==1
%            1: gabor filter bank for spatiotemporal stuff
%          - if d==2
%            1: filter bank from Serge Belongie
%            2: 1st/2nd order DooG filters.  Similar to Gabor filterbank.
%            3: similar to Laptev&Lindberg ICPR04
%            4: decent seperable steerable? filterbank
%            5: berkeley filterbank for textons papers
%            6: symmetric DOOG filters
%          - if d==3
%            1: decent seperable steerable filterbank
%  show    - [0] figure to use for optional display
%
% OUTPUTS
%
% EXAMPLE
%  FB = FbMake( 2, 1, 1 );
%
% See also FBAPPLY2D
%
% Piotr's Image&Video Toolbox      Version 2.0
% Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

if( nargin<3 || isempty(show) ); show=0; end

% create FB
switch dim
  case 1
    FB = FbMake1D( flag );
  case 2
    FB = FbMake2D( flag );
  case 3
    FB = FbMake3d( flag );
  otherwise
    error( 'dim must be 1 2 or 3');
end

% display
FbVisualize( FB, show );

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

function FB = FbMake1D( flag )
switch flag
  case 1  %%% gabor filter bank for spatiotemporal stuff
    omegas = 1 ./ [3 4 5 7.5 11];
    sigmas =      [3 4 5 7.5 11];
    FB = FbMakegabor1D( 15, sigmas, omegas );

  otherwise
    error('none created.');
end

function FB = FbMakegabor1D( r, sigmas, omegas )
for i=1:length(omegas)
  [feven,fodd]=filterGabor1d(r,sigmas(i),omegas(i));
  if( i==1 ); FB=repmat(feven,[2*length(omegas) 1]); end
  FB(i*2-1,:)=feven; FB(i*2,:)=fodd;
end

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

function FB = FbMake2D( flag )

switch flag
  case 1  %%% filter bank from Berkeley / Serge Belongie
    r=15;
    FB = FbMakegabor( r, 6, 3, 3, sqrt(2) );
    FB2 = FbMakeDOG( r, .6, 2.8, 4);
    FB = cat(3, FB, FB2);
    %FB = FB(:,:,1:2:36); %include only even symmetric filters
    %FB = FB(:,:,2:2:36); %include only odd symmetric filters

  case 2 %%% 1st/2nd order DooG filters.  Similar to Gabor filterbank.
    FB = FbMakeDooG( 15, 6, 3, 5, .5) ;

  case 3 %%% similar to Laptev&Lindberg ICPR04
    % Wierd filterbank of Gaussian derivatives at various scales
    % Higher order filters probably not useful.
    r = 9;   dims=[2*r+1 2*r+1];
    sigs = [.5 1 1.5 3]; % sigs = [1,1.5,2];

    derivs = [];
    %derivs = [ derivs; 0 0 ]; % 0th order
    %derivs = [ derivs; 1 0; 0 1 ]; % first order
    %derivs = [ derivs; 2 0; 0 2; 1 1 ]; % 2nd order
    %derivs = [ derivs; 3 0; 0 3; 1 2; 2 1 ]; % 3rd order
    %derivs = [ derivs; 4 0; 0 4; 1 3; 3 1; 2 2 ]; % 4th order
    derivs = [ derivs; 0 1; 0 2; 0 3; 0 4; 0 5]; % 0n order
    derivs = [ derivs; 1 0; 2 0; 3 0; 4 0; 5 0]; % n0 order
    cnt=1;  nderivs = size(derivs,1);
    for s=1:length(sigs)
      for i=1:nderivs
        dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 );
        if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end
        FB(:,:,cnt) = dG; cnt=cnt+1;
        %dG = filterDoog( dims, [sigs(s)*3 sigs(s)], derivs(i,:), 0 );
        %FB(:,:,cnt) = dG; cnt=cnt+1;
        %dG = filterDoog( dims, [sigs(s) sigs(s)*3], derivs(i,:), 0 );
        %FB(:,:,cnt) = dG; cnt=cnt+1;
      end
    end

  case 4 % decent seperable steerable? filterbank
    r = 9;   dims=[2*r+1 2*r+1];
    sigs = [.5 1.5 3];
    derivs = [1 0; 0 1; 2 0; 0 2];
    cnt=1;  nderivs = size(derivs,1);
    for s=1:length(sigs)
      for i=1:nderivs
        dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 );
        if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end
        FB(:,:,cnt) = dG; cnt=cnt+1;
      end
    end
    FB2 = FbMakeDOG( r, .6, 2.8, 4);
    FB = cat(3, FB, FB2);

  case 5  %%% berkeley filterbank for textons papers
    FB = FbMakegabor( 7, 6, 1, 2, 2 );

  case 6  %%% symmetric DOOG filters
    FB = FbMakeDooGSym( 4, 2, [.5 1] );

  otherwise
    error('none created.');
end

function FB = FbMakegabor( r, nOrient, nScales, lambda, sigma )
% multi-scale even/odd gabor filters. Adapted from code by Serge Belongie.
cnt=1;
for m=1:nScales
  for n=1:nOrient
    [F1,F2]=filterGabor2d(r,sigma^m,lambda,180*(n-1)/nOrient);
    if(m==1 && n==1); FB=repmat(F1,[1 1 nScales*nOrient*2]); end
    FB(:,:,cnt)=F1;  cnt=cnt+1;   FB(:,:,cnt)=F2;  cnt=cnt+1;
  end
end

function FB = FbMakeDooGSym( r, nOrient, sigs )
% Adds symmetric DooG filters.  These are similar to gabor filters.
cnt=1; dims=[2*r+1 2*r+1];
for s=1:length(sigs)
  Fodd = -filterDoog( dims, [sigs(s) sigs(s)], [1 0], 0 );
  Feven = filterDoog( dims, [sigs(s) sigs(s)], [2 0], 0 );
  if(s==1); FB=repmat(Fodd,[1 1 length(sigs)*nOrient*2]); end
  for n=1:nOrient
    theta = 180*(n-1)/nOrient;
    FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' );  cnt=cnt+1;
    FB(:,:,cnt) = imrotate( Fodd,  theta, 'bil', 'crop' );  cnt=cnt+1;
  end
end

function FB = FbMakeDooG( r, nOrient, nScales, lambda, sigma )
% 1st/2nd order DooG filters.  Similar to Gabor filterbank.
% Defaults: nOrient=6, nScales=3, lambda=5, sigma=.5,
cnt=1; dims=[2*r+1 2*r+1];
for m=1:nScales
  sigma = sigma * m^.7;
  Fodd = -filterDoog( dims, [sigma lambda*sigma^.6], [1,0], 0 );
  Feven = filterDoog( dims, [sigma lambda*sigma^.6], [2,0], 0 );
  if(m==1); FB=repmat(Fodd,[1 1 nScales*nOrient*2]); end
  for n=1:nOrient
    theta = 180*(n-1)/nOrient;
    FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' );  cnt=cnt+1;
    FB(:,:,cnt) = imrotate( Fodd,  theta, 'bil', 'crop' );  cnt=cnt+1;
  end
end

function FB = FbMakeDOG( r, sigmaStr, sigmaEnd, n )
% adds a serires of difference of Gaussian filters.
sigs = sigmaStr:(sigmaEnd-sigmaStr)/(n-1):sigmaEnd;
for s=1:length(sigs)
  FB(:,:,s) = filterDog2d(r,sigs(s),2); %#ok<AGROW>
  if( s==1 ); FB=repmat(FB,[1 1 length(sigs)]); end
end

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

function FB = FbMake3d( flag )

switch flag
  case 1 % decent seperable steerable filterbank
    r = 25; dims=[2*r+1 2*r+1 2*r+1];
    sigs = [.5 1.5 3];
    derivs = [0 0 1; 0 1 0; 1 0 0; 0 0 2; 0 2 0; 2 0 0];
    cnt=1; nderivs = size(derivs,1);
    for s=1:length(sigs)
      for i=1:nderivs
        dG = filterDoog( dims, repmat(sigs(s),[1 3]), derivs(i,:), 0 );
        if(s==1 && i==1); FB=repmat(dG,[1 1 1 nderivs*length(sigs)]); end
        FB(:,:,:,cnt) = dG; cnt=cnt+1;
      end
    end

  otherwise
    error('none created.');
end


function numgrad = computeNumericalGradient_SR(image, label, weight_idx)
    global config mem;
    estimatedGrad = mem.grads;
    epsilon = config.NEW_MEM(0.01);
    % Initialize numgrad with zeros
    numgrad = zeros(size(config.weights{1}{weight_idx}));

    for x = 1:size(config.weights{1}{weight_idx}, 1)
        for y = 1:size(config.weights{1}{weight_idx}, 2)
            config.weights{1}{weight_idx}(x, y) = config.weights{1}{weight_idx}(x, y) + epsilon;
            op_train_pipe(image, label);
            cost1 = config.cost;
            config.weights{1}{weight_idx}(x, y) = config.weights{1}{weight_idx}(x, y)  - (2*epsilon);
            op_train_pipe(image, label);
            cost2 = config.cost;
            config.weights{1}{weight_idx}(x, y) = config.weights{1}{weight_idx}(x, y) + epsilon;

            % compute the numerical
            temp = (cost1 - cost2) / (2 * epsilon);
            numgrad(x, y) = gather(temp);

            diff = norm(temp-estimatedGrad{1}{weight_idx}(x, y));
            threshold = 10^-10;
            %if(diff > threshold)
                fprintf('numerical: %i, ', temp);
                fprintf('estimated: %i. \n', estimatedGrad{1}{weight_idx}(x, y));
                fprintf('loop (%d, %d)\n', x, y);
                fprintf('diff too large! diff: %i.\n', diff);
            %end
        end
    end
end


% This is material illustrating the methods from the book
% Financial Modelling  - Theory, Implementation and Practice with Matlab
% source
% Wiley Finance Series
% ISBN 978-0-470-74489-5
%
% Date: 02.05.2012
%
% Authors:  Joerg Kienitz
%           Daniel Wetterau
%
% Please send comments, suggestions, bugs, code etc. to
% kienitzwetterau_FinModelling@gmx.de
%
% (C) Joerg Kienitz, Daniel Wetterau
%
% Since this piece of code is distributed via the mathworks file-exchange
% it is covered by the BSD license
%
% This code is being provided solely for information and general
% illustrative purposes. The authors will not be responsible for the
% consequences of reliance upon using the code or for numbers produced
% from using the code.

function [c,fc] = FInvSABR4_1(x, f)
% This function computes the inverse of a SABR cumulative distribution
% Since it is based on FSABR2 it is very fast and works for vectors!
f2 = @(t) (x - FSABR2_1(t,f));

% Use simple bisection
a = 0.00001 * ones(1,length(x)); % left starting points
b = 1*ones(1,length(x));        % right starting points

eps = 1e-3;                     % accuracy level
k = 0;                          % init iteration counter

c=(b+a)/2;
fc = f2(c);
% Ind = -eps <= fc & fc <= eps;
while(k <= 200)
    k = k+1;                            % increase iteration counter
%     if sum(Ind) == length(x)
%         break;
%     else
%         b(fc(Ind)<0) = 0.5*(b(fc(Ind)<0)+a(fc(Ind)<0));               % update right boundary
%         a(fc(Ind)>=0) = 0.5*(b(fc(Ind)>=0)+a(fc(Ind)>=0));            % update left boundary
%     end
%     c(Ind) = 0.5*(b(Ind)+a(Ind));
%     fc = f2(c);
%     Ind = -eps <= fc & fc <= eps;

    if( (-eps <= min(fc)) & (max(fc) <= eps))
        break;                          % end if all values have been found
    else
        b(fc<0) = 0.5*(b(fc<0)+a(fc<0));               % update right boundary
        a(fc>=0) = 0.5*(b(fc>=0)+a(fc>=0));            % update left boundary
    end
    c = 0.5*(b+a);
    fc = f2(c);                         % evaluate function at new c
end

end


function ADEM_lorenz
% Action-DEM demo specifying an attractor (in terms of the parameters of
% desired equations of motion) This demo first exposes an agent to a Lorenz
% attractor world such that it can learn the three parameters of the Lorenz
% system. It is then placed in a test world with a fixed point attractor to
% see if it has remembered the chaotic dynamics it learnt in the training
% environment
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: ADEM_lorenz.m 4804 2012-07-26 13:14:18Z karl $

% generative model
%==========================================================================
G(1).E.s = 1/2;                        % smoothness
G(1).E.n = 4;                          % smoothness
G(1).E.d = 2;                          % smoothness
G(1).E.linear = 3;                     % nonlinear

% dynamics
%--------------------------------------------------------------------------
f0      = '[v; 0; 0] + [-1 1 1; -1/2 -1 0; 0 1 -1]*x/P';
fA      = '[v; 0; 0] + [-1 1 1; -1/2 -1 0; 0 1 -1]*x/P + a';
fL      = '[v; 0; 0] + [-P(1) P(1) 0; P(3) -1 -x(1); x(2) 0 P(2)]*x/64';

% parameters
%--------------------------------------------------------------------------
P0      = 16;
PL      = [10; -8/3; 32];
PM      = [0;     0;  0];

% P(1): Prandtl number
% P(2): 8/3
% P(3): Rayleigh number

% level 1
%--------------------------------------------------------------------------
G(1).x  = [1; 1; 24];
G(1).f  = inline(fL ,'x','v','a','P');
G(1).g  = inline('x','x','v','a','P');
G(1).pE = PL;
G(1).V  = exp(8);                           % error precision
G(1).W  = exp(8);                           % error precision

% level 2
%--------------------------------------------------------------------------
G(2).a  = [0;0;0];                          % action variables
G(2).v  = 0;                                % inputs
G(2).V  = exp(16);
G       = spm_ADEM_M_set(G);

% plot flow fields and equilibrium densities
%==========================================================================
spm_figure('GetWin','Figure 1');

x{1}    = linspace(-20,20,32);
x{2}    = linspace(-32,32,32);
x{3}    = linspace(  10,40,8);

% controlled flow (P0)
%--------------------------------------------------------------------------
subplot(3,2,1)
spm_fp_display_density(G,x);
xlabel('position','Fontsize',12)
ylabel('velocity','Fontsize',12)
title('controlled','Fontsize',16)
a     = axis;

% exemplar trajectory
%--------------------------------------------------------------------------
U.u   = sparse(1024,G(1).m);
t     = spm_int_J(G(1).pE,G,U);
subplot(3,2,2)
plot(t(:,1),t(:,2),'r')
xlabel('position','Fontsize',12)
ylabel('velocity','Fontsize',12)
title('controlled','Fontsize',16)
axis(a);

% uncontrolled flow (P0)
%--------------------------------------------------------------------------
G0       = G;
G0(1).f  = inline(f0,'x','v','P');
G0(1).pE = P0;

subplot(3,2,3)
spm_fp_display_density(G0,x);
xlabel('position','Fontsize',12)
ylabel('velocity','Fontsize',12)
title('before','Fontsize',16)
a = axis;

% exemplar trajectory
%--------------------------------------------------------------------------
t     = spm_int_J(G0(1).pE,G0,U);
subplot(3,2,4)
plot(t(:,1),t(:,2),'r')
xlabel('position','Fontsize',12)
ylabel('velocity','Fontsize',12)
title('before','Fontsize',16)
axis(a);
drawnow

% recognition model: learn the controlled environmental dynamics
%==========================================================================

% make a naive model (M)
%--------------------------------------------------------------------------
M       = G;
M(1).f  = inline(fL ,'x','v','P');
M(1).g  = inline('x','x','v','P');
M(1).pE = PM;
M(1).pC = 32;

% teach naive model by exposing it to a controlled environment (G)
%--------------------------------------------------------------------------
n     = 256;
C     = sparse(n,1);

DEM.M = M;
DEM.G = G;
DEM.C = C;
DEM.U = C;

% optimise recognition model and show results of learning
%--------------------------------------------------------------------------
DEM    = spm_ADEM(DEM);

spm_figure('GetWin','Figure 2');
spm_DEM_qP(DEM.qP,DEM.pP)

% replace priors with learned conditional expectation and plot
%--------------------------------------------------------------------------
spm_figure('GetWin','Figure 1');

M       = DEM.M;
M(1).pE = DEM.qP.P{1};

subplot(3,2,5)
spm_fp_display_density(M,x);
xlabel('position','Fontsize',12)
ylabel('velocity','Fontsize',12)
title('after','Fontsize',16)
a   = axis;

% exemplar trajectory
%--------------------------------------------------------------------------
t   = spm_int_J(M(1).pE,M,U);
subplot(3,2,6)
plot(t(:,1),t(:,2),'r')
xlabel('position','Fontsize',12)
ylabel('velocity','Fontsize',12)
title('after','Fontsize',16)
axis(a);
drawnow

% evaluate performance under active inference
%==========================================================================
N       = 256;
C       = spm_conv(randn(1,N)*4,8);

% create uncontrolled environment: A (with action)
%--------------------------------------------------------------------------
G(1).f  = inline(f0 ,'x','v','a','P');       % no action
G(1).f  = inline(fA ,'x','v','a','P');       % with action
G(1).pE = P0;

% make the recognition model confident about its predictions
%--------------------------------------------------------------------------
M(1).x  = G(1).x;
M(1).V  = exp(8);
M(1).W  = exp(8);
M(1).pC = [];

G(1).W  = exp(16);

% create DEM structure
%--------------------------------------------------------------------------
DEM.G   = G;
DEM.M   = M;
DEM.C   = sparse(1,N);                       % no perturbation
DEM.C   = C;                                 % with perturbation
DEM.U   = sparse(1,N);
DEM     = spm_ADEM(DEM);

spm_DEM_qU(DEM.qU,DEM.pU)

% plot behaviour
%--------------------------------------------------------------------------
subplot(2,2,3)
spm_fp_display_density(M,x); hold on
plot(DEM.pU.v{1}(1,:),DEM.pU.v{1}(2,:),'b'), hold off
xlabel('position','Fontsize',12)
ylabel('velocity','Fontsize',12)
title('learnt','Fontsize',16)

return

% Notes: alternative specification of Lorenz system
%==========================================================================

% dynamics
%--------------------------------------------------------------------------
fL      = '[v; 0; 0] + [-P(1) P(1) 0; P(3) -1 -x(1); x(2) 0 P(2)]*x/32';

% parameters
%--------------------------------------------------------------------------
PL      = [10; -8/3; 32];
P.A     = [-PL(1) PL(1) 0; PL(3) -1 0; 0 0 PL(2)]/32;
P.B     = [0 0  0;
    0 0 -1;
    0 1  0]/32;

% PL(1): Prandtl number
% PL(2): 8/3
% PL(3): Rayleigh number


function [xr,xc,xm] = z2x(z,lc,lm)
if length(z)==12
    xr = [z(1:2),0,0,0,z(3)]; a = z(4:7); th = z(8:11); w = z(12);
else
    xr = [z(1:2),0,0,0,0]; a = z(3)*ones(1,4); th = zeros(1,4); w = z(4);
end
xc = xr2c(xr,w);
xm = xr2m(xr,a,th,lc,lm);
end


% Test Jacobian primitives

p560

jacob0(p560, qz)
jacob0(p560, qr)
jacob0(p560, qn)

jacobn(p560, qz)
jacobn(p560, qr)
jacobn(p560, qn)

t = fkine(p560, qn)
tr2jac(t)


function a = subsref(t,s)
%SUBSREF Subscripted reference for a ttensor.
%
%   Examples
%   core = tensor(rand(2,2,2));
%   X = TTENSOR(core, rand{4,2), rand(5,2),rand(3,2));
%   X.core %<-- returns core array
%   X.U %<-- returns a cell array of three matrices
%   X.U{1} %<-- returns the matrix corresponding to the first mode.
%
%   See also TTENSOR.
%
%MATLAB Tensor Toolbox.
%Copyright 2015, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2015) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

switch s(1).type
    case '.'
        switch s(1).subs
            case {'core','lambda'}
                a = tt_subsubsref(t.core,s);
            case {'U','u'}
                a = tt_subsubsref(t.u,s);
            otherwise
                error(['No such field: ', s.subs]);
        end
    case '()'
	error('Subsref with () not supported for ttensor.');
    case '{}'
	new_s(1).type = '.';
	new_s(1).subs = 'u';
	new_s(2:length(s)+1) = s;
	a = subsref(t, new_s);
     otherwise
        error('Invalid subsref.');
end