text:
function ct = hct(crit,y,z,tt)
%HCT Compute Harrel's C for survival model at several time points
%
%  Description
%    CT = HCT(CRIT,Y,Z,TT) Compute Harrel's C statistic estimate at
%    times TT using criteria vector CRIT (where larger value means
%    larger risk of incidence), observed time vector Y and event
%    indicator vector Z (0=event, 1=censored)
%
%  Reference
%    L. E. Chambless, C. P. Cummiskey, and G. Cui (2011). Several
%    methods to assess improvement in risk prediction models:
%    Extension to survival analysis. Statistics in Medicine
%    30(1):22-38.
%

% Copyright (C) 2012 Ernesto Ulloa, Aki Vehtari

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

ip=inputParser;
ip.addRequired('crit',@(x) ~isempty(x) && isreal(x) && all(isfinite(x(:))))
ip.addRequired('y',@(x) ~isempty(x) && isreal(x))
ip.addRequired('z', @(x) ~isempty(x) && isreal(x))
ip.addRequired('tt', @(x) ~isempty(x) && isreal(x))

ip.parse(crit,y,z,tt)

if size(y,2) ~= size(z,2)
  error('y and z dimensions must match')
end

for i=1:size(tt,2)
  comp=bsxfun(@and,bsxfun(@and,bsxfun(@lt,y(:,i),y(:,i)'),y(:,i)<=tt(i)),z(:,end)==0);
  conc=bsxfun(@gt,crit(:,i),crit(:,i)').*comp;
  ct(i,1)=sum(conc(:))./sum(comp(:));
end

end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [ xnew, ynew, w ] = quaequad0 ( mmax, kk )

%*****************************************************************************80
%
%% QUAEQUAD0 returns the requested quadrature rule.
%
%  Licensing:
%
%    This code is distributed under the GNU GPL license.
%
%  Modified:
%
%    28 June 2014
%
%  Author:
%
%    Original FORTRAN77 version by Hong Xiao, Zydrunas Gimbutas.
%    This MATLAB version by John Burkardt.
%
%  Reference:
%
%    Hong Xiao, Zydrunas Gimbutas,
%    A numerical algorithm for the construction of efficient quadrature
%    rules in two and higher dimensions,
%    Computers and Mathematics with Applications,
%    Volume 59, 2010, pages 663-676.
%
%  Parameters:
%
%    Input, integer MMAX, the degree of the quadrature (the
%    maximum degree of the polynomials of two variables that are integrated
%    exactly.  1 <= MMAX <= 50.
%
%    Input, integer KK, the number of points in the compressed rule.
%
%    Output, real XNEW(KK), YNEW(KK), the
%    coordinates of the nodes.
%
%    Output, real W(Kk), the weights.
%

%
%  Copy the arrays defining the compressed rule.
%
  if ( mmax == 1 )
    [ xnew, ynew, w ] = rule01 ( );
  elseif ( mmax == 2 )
    [ xnew, ynew, w ] = rule02 ( );
  elseif ( mmax == 3 )
    [ xnew, ynew, w ] = rule03 ( );
  elseif ( mmax == 4 )
    [ xnew, ynew, w ] = rule04 ( );
  elseif ( mmax == 5 )
    [ xnew, ynew, w ] = rule05 ( );
  elseif ( mmax == 6 )
    [ xnew, ynew, w ] = rule06 ( );
  elseif ( mmax == 7 )
    [ xnew, ynew, w ] = rule07 ( );
  elseif ( mmax == 8 )
    [ xnew, ynew, w ] = rule08 ( );
  elseif ( mmax == 9 )
    [ xnew, ynew, w ] = rule09 ( );
  elseif ( mmax == 10 )
    [ xnew, ynew, w ] = rule10 ( );
  elseif ( mmax == 11 )
    [ xnew, ynew, w ] = rule11 ( );
  elseif ( mmax == 12 )
    [ xnew, ynew, w ] = rule12 ( );
  elseif ( mmax == 13 )
    [ xnew, ynew, w ] = rule13 ( );
  elseif ( mmax == 14 )
    [ xnew, ynew, w ] = rule14 ( );
  elseif ( mmax == 15 )
    [ xnew, ynew, w ] = rule15 ( );
  elseif ( mmax == 16 )
    [ xnew, ynew, w ] = rule16 ( );
  elseif ( mmax == 17 )
    [ xnew, ynew, w ] = rule17 ( );
  elseif ( mmax == 18 )
    [ xnew, ynew, w ] = rule18 ( );
  elseif ( mmax == 19 )
    [ xnew, ynew, w ] = rule19 ( );
  elseif ( mmax == 20 )
    [ xnew, ynew, w ] = rule20 ( );
  elseif ( mmax == 21 )
    [ xnew, ynew, w ] = rule21 ( );
  elseif ( mmax == 22 )
    [ xnew, ynew, w ] = rule22 ( );
  elseif ( mmax == 23 )
    [ xnew, ynew, w ] = rule23 ( );
  elseif ( mmax == 24 )
    [ xnew, ynew, w ] = rule24 ( );
  elseif ( mmax == 25 )
    [ xnew, ynew, w ] = rule25 ( );
  elseif ( mmax == 26 )
    [ xnew, ynew, w ] = rule26 ( );
  elseif ( mmax == 27 )
    [ xnew, ynew, w ] = rule27 ( );
  elseif ( mmax == 28 )
    [ xnew, ynew, w ] = rule28 ( );
  elseif ( mmax == 29 )
    [ xnew, ynew, w ] = rule29 ( );
  elseif ( mmax == 30 )
    [ xnew, ynew, w ] = rule30 ( );
  elseif ( mmax == 31 )
    [ xnew, ynew, w ] = rule31 ( );
  elseif ( mmax == 32 )
    [ xnew, ynew, w ] = rule32 ( );
  elseif ( mmax == 33 )
    [ xnew, ynew, w ] = rule33 ( );
  elseif ( mmax == 34 )
    [ xnew, ynew, w ] = rule34 ( );
  elseif ( mmax == 35 )
    [ xnew, ynew, w ] = rule35 ( );
  elseif ( mmax == 36 )
    [ xnew, ynew, w ] = rule36 ( );
  elseif ( mmax == 37 )
    [ xnew, ynew, w ] = rule37 ( );
  elseif ( mmax == 38 )
    [ xnew, ynew, w ] = rule38 ( );
  elseif ( mmax == 39 )
    [ xnew, ynew, w ] = rule39 ( );
  elseif ( mmax == 40 )
    [ xnew, ynew, w ] = rule40 ( );
  elseif ( mmax == 41 )
    [ xnew, ynew, w ] = rule41 ( );
  elseif ( mmax == 42 )
    [ xnew, ynew, w ] = rule42 ( );
  elseif ( mmax == 43 )
    [ xnew, ynew, w ] = rule43 ( );
  elseif ( mmax == 44 )
    [ xnew, ynew, w ] = rule44 ( );
  elseif ( mmax == 45 )
    [ xnew, ynew, w ] = rule45 ( );
  elseif ( mmax == 46 )
    [ xnew, ynew, w ] = rule46 ( );
  elseif ( mmax == 47 )
    [ xnew, ynew, w ] = rule47 ( );
  elseif ( mmax == 48 )
    [ xnew, ynew, w ] = rule48 ( );
  elseif ( mmax == 49 )
    [ xnew, ynew, w ] = rule49 ( );
  elseif ( mmax == 50 )
    [ xnew, ynew, w ] = rule50 ( );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'QUAEQUAD0 - Fatal error!\n' );
    fprintf ( 1, '  Illegal input value of MMAX.\n' );
    fprintf ( 1, '  1 <= MMAX <= 50 required.\n' );
    error ( 'QUAEQUAD0 - Fatal error!' );
  end

  for i = 1 : kk
%
%  The lower-left 1/6.
%
    iitype = 2;
    nbool2 = quaeinside ( iitype, xnew(i), ynew(i) );
%
%  The lower 1/3.
%
    iitype = 1;
    nbool1 = quaeinside ( iitype, xnew(i), ynew(i) );
%
%  The whole triangle.
%
    iitype = 0;
    nbool0 = quaeinside ( iitype, xnew(i), ynew(i) );

    if ( nbool2 == 1 )

    elseif ( nbool1 == 1 )
      xnew(i) = -xnew(i);
      ynew(i) = ynew(i);
    elseif ( nbool0 == 1 )
      x0 = xnew(i);
      y0 = ynew(i);
      [ x1, y1 ] = quaerotate ( x0, y0 );
      xnew(i) = x1;
      ynew(i) = y1;
    else
      fprintf ( 1, '\n' );
      fprintf ( 1, 'QUAEQUAD0 - Fatal error!\n' );
      fprintf ( 1, '  Point does not lie inside triangle.\n' );
      error ( 'QUAEQUAD0 - Fatal error!' );
    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
BNT_HOME = '/home/ai2/murphyk/matlab/FullBNT'; % edit this

d = fullfile(BNT_HOME, 'BNT');
%PC = (strncmp(computer,'PC',2));

cd(sprintf('%s/potentials/Tables', d))
mex marg_table.c % used by @dpot/marginalize_pot.m
mex marg_sparse_table.c %used by sparse jtree
mex mult_by_table.c
mex mult_by_sparse_table.c
mex divide_by_table.c
mex divide_by_sparse_table.c
mex rep_mult.c

% Written by Wei Hu
cd(sprintf('%s/CPDs/@discrete_CPD', d))
mex convert_to_sparse_table.c

% Written by Wei Hu
cd(sprintf('%s/inference/static/@jtree_sparse_inf_engine', d))
mex init_pot.c
mex collect_evidence.c
mex distribute_evidence.c

% written by Bhaskara Marthi
cd(sprintf('%s/inference/static/@gibbs_sampling_inf_engine/private', d))
mex compute_posterior.c
mex get_slice_dbn.c
mex sample_single_discrete.c

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function pSizes = calcPixelSizes( pTotal, mSizes, pMinima, pPadding, pSpacing )
%calcPixelSizes  Calculate child sizes in pixels
%
%  pSizes = uix.calcPixelSizes(total,mSizes,minSizes,padding,spacing)
%  computes child sizes (in pixels) given total available size (in pixels),
%  child sizes (in pixels and/or relative), minimum child sizes (in
%  pixels), padding (in pixels) and spacing (in pixels).
%
%  Notes:
%  * All children are at least as large as the minimum specified size
%  * Relative sizes are respected for children larger than then minimum
%  specified size
%  * Children may extend beyond the total available size if the minimum
%  sizes, padding and spacing are too large

%  Copyright 2009-2015 The MathWorks, Inc.
%  $Revision: 1182 $ $Date: 2015-12-07 14:27:30 -0500 (Mon, 07 Dec 2015) $

% Initialize
pSizes = NaN( size( mSizes ) ); % output
n = numel( mSizes ); % need this later

% Apply absolute sizes
a = mSizes >= 0; % absolute
pSizes(a) = max( mSizes(a), pMinima(a) );

while true

    u = isnan( pSizes ); % unsolved
    pUnsolvedTotal = pTotal - max( (n-1), 0 ) * pSpacing ...
        - 2 * sign( n ) * pPadding - sum( pSizes(~u) );
    pUnsolvedSizes = mSizes(u) / sum( mSizes(u) ) * pUnsolvedTotal;
    pUnsolvedMinima = pMinima(u);
    s = pUnsolvedSizes < pUnsolvedMinima; % small
    if any( s )
        pUnsolvedSizes(s) = pUnsolvedMinima(s);
        pUnsolvedSizes(~s) = NaN;
        pSizes(u) = pUnsolvedSizes;
        % repeat
    else
        pSizes(u) = pUnsolvedSizes;
        break % done
    end

end

end % calcPixelSizes

author: goGPS-Project


text:
addpath './lib';
addpath './lib/gnss';
addpath './lib/calbiration';
addpath './lib/plot';
addpath './lib/rotation';
addpath './lib/geo';
savepath

author: yandld


text:
function r = fieldnamesContain(names, id)
  r = any(strcmp(names,id));
end

author: OpenOCL

repo: OpenOCL

save_path: github-repos/MATLAB/OpenOCL-OpenOCL


text:
function view_bdepth(lab1, valueMap)
    % view_maxz plots the maxz LTA values calculated
    % with maxzlta.m or other similar values as a color map
    % needs valueMap, gx, gy, stri
    %
    % define size of the plot etc.
    %
%
%          The Z-Value Map Window
%
%               This window displays seismicity rate changes
%               as z-values using a color code. Negative
%               z-values indicate an increase in the seismicity'
%               rate, positive values a decrease.
%               Some of the menu-bar options are
%               described below:
%
%               Threshold: You can set the maximum size that
%                 a volume is allowed to have in order to be
%                 displayed in the map. Therefore, areas with
%                 a low seismicity rate are not displayed.
%                 edit the size (in km) and click the mouse
%                 outside the edit window.
%              FixAx: You can chose the minimum and maximum
%                      values of the color-legend used.
%              Polygon: You can select earthquakes in a
%               polygon either by entering the coordinates or
%               defining the corners with the mouse
%
%              Circle: Select earthquakes in a circular volume:'
%                    Ni, the number of selected earthquakes can'
%                    be edited in the upper right corner of the'
%                    window.
%               Refresh Window: Redraws the figure, erases
%                     selected events.
%
%               zoom: Selecting Axis -> zoom on allows you to
%                     zoom into a region. Click and drag with
%                     the left mouse button. type <help zoom>
%                     for details.
%               Aspect: select one of the aspect ratio options
%               Text: You can select text items by clicking.The'
%                     selected text can be rotated, moved, you
%                     can change the font size etc.
%                     Double click on text allows editing it.

    % turned into function by Celso G Reyes 2017

    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    report_this_filefun();

    % Find out if figure already exists
    %
    bmap=findobj('Name','b-value-depth-ratio-map');

    use_old_win = false;
    % This is the info window text

    % Set up the Seismicity Map window Enviroment
    %
    if isempty(bmap) || ~use_old_win
        bmap = figure_w_normalized_uicontrolunits( ...
            'Name','b-value-depth-ratio-map',...
            'NumberTitle','off', ...
            'NextPlot','new', ...
            'backingstore','on',...
            'Visible','off', ...
            'Position',position_in_current_monitor(ZG.map_len(1), ZG.map_len(2)));
        % make menu bar

        uicontrol('Units','normal',...
            'Position',[.0 .93 .08 .06],'String','Info ',...
            'callback',@callbackfun_001);

        create_my_menu();

        ZG.tresh_km = nan; re4 = valueMap;

        colormap(jet)
        ZG.tresh_km = nan; minpe = nan; Mmin = nan;

    end   % This is the end of the figure setup

    % Now lets plot the color-map of the z-value
    %
    figure(bmap);
    delete(findobj(bmap,'Type','axes'));
    % delete(sizmap);
    reset(gca)
    cla
    set(gca,'NextPlot','replace')
    watchon;
    set(gca,'visible','off','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','SortMethod','childorder')

    rect = [0.18,  0.10, 0.7, 0.75];
    rect1 = rect;

    % find max and min of data for automatic scaling
    %
    ZG.maxc = max(valueMap(:));
    ZG.maxc = fix(ZG.maxc)+1;
    ZG.minc = min(valueMap(:));
    ZG.minc = fix(ZG.minc)-1;

    % Find percentage above and below 1.0
    disp('HELP!!!!!!');
    under_1 = valueMap < 1.0;
    equal_1 = valueMap == 1.0;
    over_1 = valueMap > 1.0;

    total_num = length(valueMap);
    p_under = under_1/total_num;
    p_equal = equal_1/total_num;
    p_over = over_1/total_num;

    % set values gretaer ZG.tresh_km = nan
    %
    re4 = valueMap;
    re4(r > ZG.tresh_km) = nan;
    re4(Prmap < minpe) = nan;
    re4(old1 <  Mmin) = nan;

    % plot image
    %
    orient landscape
    %set(gcf,'PaperPosition', [0.5 1 9.0 4.0])

    axes('position',rect)
    set(gca,'NextPlot','add')
    pco1 = pcolor(gx,gy,re4);

    axis([ min(gx) max(gx) min(gy) max(gy)])
    axis image
    set(gca,'NextPlot','add')

    shading(ZG.shading_style);

    % make the scaling for the recurrence time map reasonable
    if lab1(1) =='T'
        re = valueMap(~isnan(valueMap));
        caxis([min(re) 5*min(re)]);
    end

    fix_caxis.ApplyIfFrozen(gca);

    title([name ';  '   num2str(t0b) ' to ' num2str(teb) ],'FontSize',ZmapGlobal.Data.fontsz.s,...
        'Color','r','FontWeight','bold')

    xlabel('Longitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)
    ylabel('Latitude [deg]','FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s)

    % plot overlay
    %
    set(gca,'NextPlot','add')
    zmap_update_displays();
    ploeq = plot(ZG.primeCatalog.Longitude,ZG.primeCatalog.Latitude,'k.');
    set(ploeq,'Tag','eq_plot','MarkerSize',ZG.ms6,'Marker',ty,'Color',ZG.someColor,'Visible','on')

    set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','TickDir','out')
    h1 = gca;
    hzma = gca;

    %lab1 = 'b-value-depth-ratio:';

    % Create a colorbar
    %
    h5 = colorbar('horiz');
    set(h5,'Pos',[0.35 0.05 0.4 0.02],...
        'FontWeight','bold','FontSize',ZmapGlobal.Data.fontsz.s,'TickDir','out')

    rect = [0.00,  0.0, 1 1];
    axes('position',rect)
    axis('off')
    %  Text Object Creation
    txt1 = text(...
        'Units','normalized',...
        'Position',[ 0.33 0.06 0 ],...
        'HorizontalAlignment','right',...
        'FontSize',ZmapGlobal.Data.fontsz.s,....
        'FontWeight','bold',...
        'String',lab1);
    ni_txt = text('Position', [.39 .12],'String',[num2str(ni_plot),' events per grid node.']);
    bval_txt =  text('Position', [.34 .96],'String',['Overall b-value depth ratio = ' num2str(depth_ratio)]);
    %bval2_txt =  text('Position', [.63 .95],'String',depth_ratio);

    dbrange1 = num2str(top_zonet);
    dbrange2 = num2str(top_zoneb);
    dbrange3 = num2str(bot_zonet);
    dbrange4 = num2str(bot_zoneb);
    mid_txt = text('Position', [.20 .915],'String', ['Top and bottom zones for ratio calculation(km):' dbrange1,' to ',dbrange2 ,' and ' dbrange3,' to ',dbrange4]);
    %mid2_txt = text('Position', [.685 .915],'String', [dbrange1,' to ',dbrange2 ,' and ' dbrange3,' to ',dbrange4]);

    % Make the figure visible
    %
    set(gca,'FontSize',ZmapGlobal.Data.fontsz.s,'FontWeight','bold',...
        'FontWeight','bold','LineWidth',1.5,...
        'Box','on','TickDir','out')
    figure(bmap);
    %sizmap = signatur('ZMAP','',[0.01 0.04]);
    %set(sizmap,'Color','k')
    axes(h1)
    watchoff(bmap)
    %whitebg(gcf,[ 0 0 0 ])

    %% ui functions
    function create_my_menu()
        add_menu_divider();

        add_symbol_menu('eq_plot');
        options = uimenu('Label',' Select ');
        uimenu(options,'Label','Refresh ','MenuSelectedFcn',@callbackfun_002)
        uimenu(options,'Label','Select EQ in Circle',...
            'MenuSelectedFcn',@callbackfun_003)

        op1 = uimenu('Label',' Maps ');

        adjmenu =  uimenu(op1,'Label','Adjust Map Display Parameters');
        uimenu(adjmenu,'Label','Adjust Rmax cut',...
            'MenuSelectedFcn',@callbackfun_004)
        uimenu(adjmenu,'Label','Adjust goodness of fit cut',...
            'MenuSelectedFcn',@callbackfun_005)

        uimenu(op1,'Label','Depth Ratio Map',...
            'MenuSelectedFcn',@callbackfun_013)

        uimenu(op1,'Label','Utsu Probability Map',...
            'MenuSelectedFcn',@callbackfun_014)

        uimenu(op1,'Label','Top Zone b value Map',...
            'MenuSelectedFcn',@callbackfun_015)

        uimenu(op1,'Label','Bottom Zone b value Map',...
            'MenuSelectedFcn',@callbackfun_016)

        uimenu(op1,'Label','% of nodal EQs within top zone',...
            'MenuSelectedFcn',@callbackfun_017)

        uimenu(op1,'Label','% of nodal EQs within bottom zone',...
            'MenuSelectedFcn',@callbackfun_018)

        uimenu(op1,'Label','resolution Map',...
            'MenuSelectedFcn',@callbackfun_019)
        uimenu(op1,'Label','Histogram ','MenuSelectedFcn',@(~,~)zhist())

        add_display_menu(1);
    end

    %% callback functions

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        web(['file:' hodi '/zmapwww/chp11.htm#996756']) ;
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        use_old_win = 1;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        h1 = gca;
        met = 'rd';
        ZG=ZmapGlobal.Data;
        ZG.hold_state=false;
        cirbva_bdepth2;
        watchoff(bmap);
    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        asel = 'rmax';
        adjub();
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        asel = 'gofi';
        adjub();
        use_old_win = 1;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_013(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='b ratio';
        valueMap = old;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_014(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Probability';
        valueMap = Prmap;
        view_bdepth;
    end

    function callbackfun_015(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Top Zone b value';
        valueMap = top_b;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_016(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Bottom Zone b value';
        valueMap = bottom_b;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_017(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='% of nodal EQs within top zone';
        valueMap = per_top;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_018(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='% of nodal eqs within bottom zone';
        valueMap = per_bot;
        view_bdepth(lab1, valueMap);
    end

    function callbackfun_019(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        lab1='Radius in [km]';
        valueMap = r;
        view_bdepth(lab1, valueMap);
    end

    function adjub()
        report_this_filefun();

        prompt={'Enter the maximum radius cut-off:','Enter the minimum Utsu probability '};
        def={'nan','nan'};
        dlgTitle='Input Map Selection Criteria';
        lineNo=1;
        answer=inputdlg(prompt,dlgTitle,lineNo,def);
        re4 = valueMap;

        ZG.tresh_km = str2double(answer{2,1}) ;
        minpe = str2double(answer{1,1}) ;

        if ZG.tresh_km >= 0
            valueMap(Prmap < ZG.tresh_km) = 1;
        elseif minpe >= 0
            valueMap(r >= minpe) = 1;
        end

        ca = caxis;

        ve = ca(1):(ca(2)-ca(1))/64:ca(2);

        i = find(abs(ve-1) == min(abs(ve-1)) );

        col = jet;
        col(i,:) = [0.8 0.8 0.8] ;
        col(i-1,:) = [0.8 0.8 0.8] ;
        col(i+1,:) = [0.8 0.8 0.8] ;

        colormap(col);
    end
end

author: CelsoReyes


text:
function taxonomy = parseNCBItaxonomy(NCBI)
% Grabs taxonomic lineage from NCBI using the NCBI ID
%
% INPUT
% NCBI          NCBI ID (e.g., 511145)
%
% OUTPUT
% taxonomy      structure containing the taxonomic lineage
%
% Stefania Magnusdottir, Nov 2017

if iscell(NCBI)
    NCBI = NCBI{1};
end
if isnumeric(NCBI)
    NCBI = num2str(NCBI);
end

hmtlString = urlread(['https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=', NCBI]);
lineage = {
    'superkingdom'
    'phylum'
    'class'
    'order'
    'family'
    'genus'
    'species'};

% extract information from html string and fill in data (different parsing
% types)

% type 1
taxonomy = struct();
for i = 1:length(lineage)
    n = regexp(hmtlString, ['ALT="', lineage{i}, '">([^<]+)'], 'tokens');
    if ~isempty(n)
        n = [n{:}];
        if ~isempty(n{1, 1})
            taxonomy.(lineage{i}) = n{1, 1};
        else
            taxonomy.(lineage{i}) = '';
        end
    end
end

% type 2
taxFields = fieldnames(taxonomy);
if isempty(taxFields)
    taxonomy = struct();
    for i = 1:length(lineage)
        n = regexp(hmtlString, ['TITLE="', lineage{i}, '">([^<]+)'], 'tokens');
        if ~isempty(n)
            n = [n{:}];
            if ~isempty(n{1, 1})
                taxonomy.(lineage{i}) = n{1, 1};
            else
                taxonomy.(lineage{i}) = '';
            end
        end
    end
end

% extract strain from title
n = regexp(hmtlString, '<TITLE>Taxonomy browser (([^)]+)', 'tokens');
if isempty(n)  % try other type
    n = regexp(hmtlString, '<title>Taxonomy browser (([^)]+)', 'tokens');
end
if ~isempty(n)
    n = [n{:}];
    if ~isempty(n{1, 1})
        taxonomy.strain = n{1, 1};
    else
        taxonomy.strain = '';
    end
end

author: opencobra

repo: cobratoolbox


text:
function printfunctionstack(symbol)
% PRINTFUNCTIONSTACK print the list of functions in the stack
%
%    PRINTFUNCTIONSTACK prints a full list of the nested function calls on the stack, so it tells you where in your code you are.
%
%    EXAMPLE:
%	function myfunc1()
%		debug.printfunctionstack('>')
%		myfunc2()
%		debug.printfunctionstack('<')
%	end
%	function myfunc2()
%		debug.printfunctionstack('>')
%		myfunc3()
%		debug.printfunctionstack('<')
%	end
%	function myfunc3()
%		debug.printfunctionstack('>')
%		disp('hello world')
%		debug.printfunctionstack('<')
%	end
%
%	debug.set_debug(1)
%	myfunc1()
%
%	would result in:
%	>myfunc1
%	>myfunc1>myfunc2
%	>myfunc1>myfunc2>myfunc3
%	hello world
%	<myfunc1<myfunc2<myfunc3
%	<myfunc1<myfunc2
%	<myfunc1
%
%    See also debug.set_debug, debug.get_debug, debug.print_debug, setpref.

% AUTHOR: Glenn Thompson, UAF-GI
% $Date: $
% $Revision: -1 $

st = dbstack;
outstr='';
if numel(st)>1
        for c=numel(st):-1:2
                outstr = sprintf('%s%s%s',outstr, symbol,st(c).name);
        end
end
debug.print_debug(1, '%s at %s',outstr,datestr(now));

author: geoscience-community-codes

repo: GISMO


text:
classdef SO3DeLaValleePoussinKernel < SO3Kernel
% The rotational de la Vallee Poussin kernel is defined by
%
% $$ K(t) = \frac{B(\frac32,\frac12)}{B(\frac32,\kappa+\frac12)}\,t^{2\kappa}$$
%
% for $t\in[0,1]$, where $B$ denotes the Beta function. The de la Vallee
% Poussin kernel additionaly has the unique property that for
% a given halfwidth it can be described exactly by a finite number of
% Fourier coefficients. This kernel is recommended for Texture analysis as
% it is always positive in orientation space and there is no truncation
% error in Fourier space.
%
% Hence we can define the de la Vallee Poussin kernel $\psi_{\kappa}$
% depending on a parameter $\kappa \in \mathbb N \setminus \{0\}$ by its
% finite Chebyshev expansion
%
% $$ \psi_{\kappa}(t) = \frac{(\kappa+1)\,2^{2\kappa-1}}{\binom{2\kappa-1}{\kappa}}
% \, t^{2\kappa}  = \binom{2\kappa+1}{\kappa}^{-1} \,
% \sum\limits_{n=0}^{\kappa} (2n+1)\,\binom{2\kappa+1}{\kappa-n} \,
% \mathcal U_{2n}(t)$$.
%
% Syntax
%   psi = SO3DeLaValleePoussinKernel(100)
%   psi = SO3DeLaValleePoussinKernel('halfwidth',5*degree)
%
% Input
%  kappa - kernel parameter
%
% Options
%  halfwidth - angle at which the kernel function has reduced to half its peak value
%  bandwidth - harmonic degree
%
% See also
% SO3Kernel

properties
  kappa = 90;
  C = [];
end

methods

  function psi = SO3DeLaValleePoussinKernel(varargin)

    % extract parameter and halfwidth
    if check_option(varargin,'halfwidth')
      hw = get_option(varargin,'halfwidth');
      psi.kappa = 0.5 * log(0.5) / log(cos(hw/2));
    elseif nargin > 0
      psi.kappa = varargin{1};
    end

    % extract bandwidth
    L = get_option(varargin,'bandwidth',round(psi.kappa));

    % some constant
    psi.C = beta(1.5,0.5)/beta(1.5,psi.kappa+0.5);

    % compute Chebyshev coefficients
    psi.A = ones(1,L+1);
    psi.A(2) = psi.kappa/(psi.kappa+2);

    for l=1:L-1
      psi.A(l+2) = ((psi.kappa-l+1) * psi.A(l) - ...
        (2*l+1) * psi.A(l+1)) / (psi.kappa + l + 2);
    end

    for l=0:L, psi.A(l+1) = (2*l+1) * psi.A(l+1); end

    psi.A = psi.cutA;

  end

  function c = char(psi)
    c = ['de la Vallee Poussin, halfwidth ' ...
      xnum2str(psi.halfwidth/degree) mtexdegchar];
  end

  function value = eval(psi,co2)
    value   =  psi.C * co2.^(2*psi.kappa);
  end

  function value = grad(psi,co2)
    % the derivative of the kernel function
    % DK(omega) = - kappa * C * sin(omega/2)*cos(omega/2)^(2kappa-1)

    if nargin == 2
      value = -psi.C * psi.kappa * sqrt(1-co2.^2) .* co2.^(2*psi.kappa-1);
      %value = 2 * psi.C * psi.kappa *co2.^(2*psi.kappa-1);
    else
      value = SO3KernelHandle(@(co2) -psi.C * psi.kappa * sqrt(1-co2.^2) .* co2.^(2*psi.kappa-1));
    end

  end

  function S2K = radon(psi)
    S2K = S2DeLaValleePoussinKernel(psi.kappa);
  end

  function hw = halfwidth(psi)
    hw = 2*acos(0.5^(1/2/psi.kappa));
  end

end

end

author: mtex-toolbox

repo: mtex

save_path: github-repos/MATLAB/mtex-toolbox-mtex


text:
clc; clear variables; format long g; close all;

%Include matlabrc, hopefully
%#function matlabrc

%set pathes if not deployed
if(~isdeployed)
    addpath(genpath('helper_methods'));
    addpath(genpath('formsGUIs'));
    addpath(genpath('kspTOT_RTS'));
    addpath(genpath('kspTOT_MissionArchitect'));
    addpath(genpath('kspTOT_LaunchVehicleDesigner'));
    addpath(genpath('kspTOT_VehicleSizer'));
    addpath(genpath('kspTOT_SingleUIs'));
    addpath(genpath('images'));
    addpath(genpath('kos_scripts'));
%     addpath('zArchive');
end

%set look and feel if deployed
if(isdeployed)
    if(ispc)
        javax.swing.UIManager.setLookAndFeel(com.sun.java.swing.plaf.windows.WindowsLookAndFeel);
    elseif(isunix)
        javax.swing.UIManager.setLookAndFeel(com.jgoodies.looks.plastic.Plastic3DLookAndFeel);
    elseif(ismac)
        javax.swing.UIManager.setLookAndFeel(com.apple.laf.AquaLookAndFeel);
    end
end

%Turn off class destructor warnings.  These pop up a lot for App Designer
%UIs when closing while using uiwait().
warning('off','MATLAB:class:DestructorError');

%Turn off java component being removed warnings.  User doesn't need to see
%that and I already know.
warning('off','MATLAB:ui:javacomponent:FunctionToBeRemoved');

%Populate initial ksptot log file
writeKsptotLogFileHeaderToConsole();

%display splashscreen
hS = splashScreenGUI_App(); drawnow;
t = tic;

%Initialize KSPTOT options
appOptions = getAppOptionsFromFile();

%Initalize KSP celestial body data
if(isprop(appOptions.ksptot,'bodiesinifile') && ~isempty(appOptions.ksptot.bodiesinifile) && exist(appOptions.ksptot.bodiesinifile,'file'))
    [celBodyDataFromINI,~,~] = inifile(appOptions.ksptot.bodiesinifile,'readall');
else
    [celBodyDataFromINI,~,~] = inifile('bodies.ini','readall');
end
celBodyData = processINIBodyInfo(celBodyDataFromINI, false, 'bodyInfo');
celBodyData = CelestialBodyData(celBodyData);
[goodTF, celBodyWarnMsgs] = verifyCelBodyData(celBodyData);
bodyNames = fieldnames(celBodyData);

if(not(goodTF))
    msg = {sprintf('Potential issues were found with the loaded celestial body information: \n')};
    for(i=1:length(celBodyWarnMsgs)) %#ok<*NO4LP>
        msg{end+1} = sprintf('\t%s\n', celBodyWarnMsgs{i}); %#ok<SAGROW>
    end

    msgbox(msg,'Celestial Body Data Warnings','warn');
end

%Pause for some time to show the splash screen
while(toc(t) < 1)
    pause(0.1);
end

%Set up the GUI for use
% mainGUIHandle = mainGUI(celBodyData, bodyNames, hS, appOptions);
mainGUIHandle = mainGUI_App(celBodyData, bodyNames, hS, appOptions);
if(isvalid(hS))
    delete(hS);
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function feats = compute_features(net, img, do_norm)
% feats = compute_features(net, img) - compute features from a network
%
%  Inputs: net - the neural network (same as for vl_simplenn)
%          img - the input image (H x W x 3 - RGB image)
%
%  Output: feats - the reference given as argument to invert_nn.m
%
% Author: Aravindh Mahendran
%      New College, University of Oxford

% normalize the input image

if ~exist('do_norm','var');do_norm=1;end
if do_norm
    normalize = get_cnn_normalize(net.normalization);
    x0 = normalize(img);
else
    x0 = single(img);
end
% Convert the image into a 4D matrix as required by vl_simplenn
x0 = repmat(x0, [1, 1, 1, 1]);
% Run feedforward for network

switch net.cnn_mode
    case 0;res = vl_simplenn_dw(net, x0);feats = res(end).x;
    case 1;res = net.caffe.forward({x0});feats = res{end};
end

author: donglaiw

repo: mNeuron

save_path: github-repos/MATLAB/donglaiw-mNeuron


text:
function linpack_bench_backslash ( n, lda )

%*****************************************************************************80
%
%% LINPACK_BENCH_BACKSLASH drives the "backslash" LINPACK benchmark program.
%
%  Discussion:
%
%    This version of the program uses the MATLAB "backslash" operator
%    to factor and solve the linear system.
%
%    The standard LINPACK benchmark uses N = 1000, LDA = N + 1.
%
%  Modified:
%
%    22 May 2008
%
%  Author:
%
%    MATLAB version by John Burkardt.
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.  If no value is supplied,
%    the default value of 1000 is used.
%
%    Input, integer LDA, the leading dimension of the matrix.
%    If no value is supplied, the default value of N+1 is used.
%
  timestamp ( );

  if ( nargin < 1 )
    n = 1000;
  end

  if ( nargin < 2 )
    lda = n + 1;
  end

  cray = 0.056;
  ops = ( 2 * n * n * n ) / 3.0 + 2.0 * n * n;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'LINPACK_BENCH_BACKSLASH\n' );
  fprintf ( 1, '  The LINPACK benchmark (using the MATLAB "backslash" operator).\n' );
  fprintf ( 1, '  Language: MATLAB\n' );
  fprintf ( 1, '  Datatype: Real Double Precision\n' );
  fprintf ( 1, '  Matrix order N        = %d\n', n );
  fprintf ( 1, '  Leading dimension LDA = %d\n', lda );

  a = r8_matgen ( n, n );

  a_max = max ( max ( a(1:n,1:n) ) );

  x_true(1:n,1) = 1.0;
  b(1:n,1) = a(1:n,1:n) * x_true(1:n,1);

  t1 = cputime;

  x = a \ b;

  t2 = cputime;
  time(1) = t2 - t1;
  time(2) = 0;

  total = time(1) + time(2);
%
%  Compute a residual to verify results.
%
  a = r8_matgen ( n, n );

  resid(1:n,1) = a(1:n,1:n) * x(1:n,1) - b(1:n,1);
  resid_max = max ( abs ( resid(1:n,1) ) );

  x_max = max ( abs ( x(1:n,1) ) );

  residn = resid_max /  ( n * a_max * x_max * eps );

  time(3) = total;
  time(4) = ops / ( 1000000 * total );
  time(5) = 2.0 / time(4);
  time(6) = total / cray;

  fprintf ( 1, '\n' );
  fprintf ( 1, '     Norm. Resid      Resid           MACHEP' );
  fprintf ( 1, '         X(1)          X(N)\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  %14e  %14e  %14e  %14f  %14f\n', ...
    residn, resid_max, eps, x(1,1), x(n,1) );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      Factor     Solve      Total     MFLOPS' );
  fprintf ( 1, '       Unit      Cray-Ratio\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  %9f  %9f  %9f  %9f  %9f  %9f\n', time(1:6) );

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

  fprintf ( 1, '\n' );
  timestamp ( );

  return
end
function a = r8_matgen ( lda, n )

%*****************************************************************************80
%
%% R8_MATGEN generates a random matrix.
%
%  Modified:
%
%    08 June 2005
%
%  Author:
%
%    MATLAB version by John Burkardt
%
%  Parameters:
%
%    Input, integer LDA, the leading dimension of the matrix.
%
%    Input, integer N, the order of the matrix.
%
%    Output, real A(LDA,N), the N by N matrix.
%
  a = zeros ( lda, n );

  init(1:4) = [ 1, 2, 3, 1325 ];

  for j = 1 : n
     for i = 1 : n
       [ a(i,j), init ] = r8_random ( init );
    end
  end

  a(1:n,1:n) = a(1:n,1:n) - 0.5;

  return
end
function [ value, seed ] = r8_random ( seed )

%*****************************************************************************80
%
%% R8_RANDOM returns a uniformly distributed random number between 0 and 1.
%
%  Discussion:
%
%    This routine uses a multiplicative congruential method with modulus
%    2**48 and multiplier 33952834046453.
%
%    48-bit integers are stored in 4 integer array elements with 12 bits
%    per element.  Hence the routine is portable across machines with
%    integers of 32 bits or more.
%
%  Modified:
%
%    08 June 2005
%
%  Author:
%
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    George Fishman,
%    Multiplicative congruential random number generators with modulus 2**b:
%    an exhaustive analysis for b = 32 and a partial analysis for b = 48,
%    Mathematics of Computation,
%    Volume 189, 1990, pages 331-344.
%
%  Parameters:
%
%    Input, integer SEED(4), the seed of the random number generator; the array
%    elements must be between 0 and 4095, and SEED(4) must be odd.
%
%    Output, real VALUE, the next pseudorandom number.
%
%    Output, integer SEED(4), the updated seed.
%
  ipw2 = 4096;
  m1 = 494;
  m2 = 322;
  m3 = 2508;
  m4 = 2549;
  one = 1.0;
  r = 1.0 / 4096.0;
%
%  Multiply the seed by the multiplier modulo 2**48.
%
  it4 = seed(4) * m4;
  it3 = floor ( it4 / ipw2 );
  it4 = it4 - ipw2 * it3;
  it3 = it3 + seed(3) * m4 + seed(4) * m3;
  it2 = floor ( it3 / ipw2 );
  it3 = it3 - ipw2 * it2;
  it2 = it2 + seed(2) * m4 + seed(3) * m3 + seed(4) * m2;
  it1 = floor ( it2 / ipw2 );
  it2 = it2 - ipw2 * it1;
  it1 = it1 + seed(1) * m4 + seed(2) * m3 + seed(3) * m2 + seed(4) * m1;
  it1 = mod ( it1, ipw2 );
%
%  Return updated seed
%
  seed(1) = it1;
  seed(2) = it2;
  seed(3) = it3;
  seed(4) = it4;
%
%  Convert 48-bit integer to a real number in the interval (0,1)
%
  value = ...
      r * ( it1  ...
    + r * ( it2  ...
    + r * ( it3  ...
    + r * ( it4 ) ) ) );

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


text:
function payment_calc

%PAYMENT_CALC Example loan payment calculator using Swing and MATLAB.
% note: uses financial toolbox

% make the swing class names appear as functions to MATLAB.
% see http://java.sun.com/j2se/1.3/docs/api/javax/swing/package-summary.html
import javax.swing.*;

% make the java.awt class names appear as functions to MATLAB.
% see http://www.javasoft.com/products/jdk/1.1/docs/api/Package-java.awt.html
import java.awt.*;

% create a swing window with this title
frame = JFrame('Loan Payment Calculator');
frame.setSize( 300,200)

% put the dialog in the center of the screen
% ** default sizes are approximate since we use pack below
defXSize = 300;
defYSize = 200;
% get screensize from MATLAB
ss = get(0,'ScreenSize');

% calculate x and y start points
xloc = ss(3) / 2 - defXSize / 2;
yloc = ss(4) / 2 - defYSize / 2;

% create Labels, Text Fields/Areas, and Buttons
LabelLoan   = JLabel('Amount of Loan');
LabelYears  = JLabel('Number of Years');
LabelRate   = JLabel('Interest Rate');
TextLoan    = JTextField(9);
TextYears   = JTextField(3);
BoxRate    = JComboBox({' ','9.25','9.0','8.75',...
        '8.5','8.25','8.0','7.75',...
        '7.5','7.25','7.0','6.75',...
        '6.5','6.25'});
ButtonCalc  = JButton('Calculate');
ButtonClear = JButton('Clear');
ButtonQuit = JButton('Quit');

LabelPayment = JLabel('Monthly Payment');
TextPayment  = JTextField(8);
LabelIntPaid = JLabel('Total Interest Paid');
TextIntPaid  = JTextField(9);

% create layout
MainPanel = JPanel( GridLayout(1,2) );
InPanel   = JPanel( BoxLayout.Y_AXIS );
OutPanel  = JPanel( BoxLayout.Y_AXIS );

% add the labels to the input panel
InPanel.add( LabelLoan );
InPanel.add( TextLoan );
InPanel.add( LabelYears );
InPanel.add( TextYears );
InPanel.add( LabelRate );
InPanel.add( BoxRate );
InPanel.add( ButtonCalc );
InPanel.add( ButtonClear );

% add the labels to the output panel
OutPanel.add( LabelPayment );
OutPanel.add( TextPayment );
OutPanel.add( LabelIntPaid );
OutPanel.add( TextIntPaid );
OutPanel.add( ButtonQuit );

% add the Input and Output panels to the main panel
MainPanel.add( InPanel );
MainPanel.add( OutPanel );

% add the main panel to the main frame (a.k.a. window)
frame.getContentPane.add( MainPanel );

% force dialog location
frame.setLocation(Point(xloc,yloc));

% make dialog visible
frame.show;

set( InPanel, 'UserData', [0 0 0]);
set( frame,'WindowClosingCallback', ...
    {@Callback, InPanel},...
    'Name','quit');
set( BoxRate, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','rate');
set( ButtonCalc, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','calc');
set( ButtonClear, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','clear');
set( ButtonQuit, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','quit');
set( TextLoan, 'ActionPerformedCallback',{@Callback, InPanel}, ...
    'FocusLostCallback',{@Callback, InPanel},...
    'HorizontalAlignment',[4], ... %right justified
    'Name','loan');
set( TextYears, 'ActionPerformedCallback',{@Callback, InPanel}, ...
    'FocusLostCallback',{@Callback, InPanel},...
    'HorizontalAlignment',[4], ... %right justified
    'Name','year');
set( TextPayment, 'HorizontalAlignment',[4], ... %right justified
    'Editable','off',...
    'Background',[1 1 1]);
set( TextIntPaid, 'HorizontalAlignment',[4], ... %right justified
    'Editable','off',...
    'Background',[1 1 1]);

while ~(exist('STOP'))
    waitfor(InPanel,'ApplicationData')

    result = getappdata(InPanel,'QuestionAppData');

    if ~isnumeric(result)
        if (strcmp(result,'calc'))      % write out answers in text fields
        UData = get( ButtonCalc, 'UserData');
        set( TextPayment , 'Text', cur2str( UData(1) ));
        set( TextIntPaid , 'Text', cur2str( UData(2) ));
        elseif (strcmp(result,'clear')) % clear out text fields
        set( TextPayment , 'Text', '');
        set( TextIntPaid , 'Text', '');
        set( TextYears, 'Text', '' );
        set( TextLoan, 'Text', '' );
        set( BoxRate, 'SelectedItem',' ' );
        else                            % end application and close
            STOP = 1;
        end
    end

    rmappdata(InPanel,'QuestionAppData'); % clear application data
end

% close the java window
frame.dispose;

%
% since this function is called via a function handle
% The args are eventSrc (the handle of object which threw
% the event), eventData (unused in release 12), and panel
% (nargin are when the callback is created).
%
function Callback( eventSrc, eventData, panel )

UData = get( panel, 'UserData');

name = get(eventSrc,'Name');

switch name
case 'rate'    % get rate selected and save in panel
    Srate = get( eventSrc, 'SelectedItem' );
    result = str2num(Srate);
    UData = [UData(1) UData(2) result];
case 'year'    % get number of years and save in panel
    Syear = get( eventSrc, 'Text' );
    if (strcmp(Syear,''))
        result = 1;
    else
        result = str2num(Syear);
    end
    UData = [ UData(1) result UData(3)];
case 'loan'    % get amount of loan and save in panel
    Sloan = get( eventSrc, 'Text' );
    if (strcmp(Sloan,''))
        result = 0;
    else
        result = str2num(Sloan);
    end
    UData = [ result UData(2) UData(3)];
case 'calc'    % calculate payments and interest
    [PRINP,INTP,BAL,P] = amortize(UData(3)/1200,UData(2)*12,UData(1));
    set( eventSrc, 'UserData', [ P sum(INTP) ]);
    result = 'calc';
case 'clear'   % send command to clear text fields
    result = 'clear';
case 'quit'    % send command to stop waiting and close application
    result = 'quit';
end
set( panel, 'UserData', UData );
setappdata( panel, 'QuestionAppData', result );

author: Sable

repo: mcbench-benchmarks


text:
% =========================================================================
% An example code for the algorithm proposed in
%
%   Zhuolin Jiang, Zhe Lin, Larry S. Davis.
%   "Learning A Discriminative Dictionary for Sparse Coding via Label
%    Consistent K-SVD", CVPR 2011.
%
% Author: Zhuolin Jiang (zhuolin@umiacs.umd.edu)
% Date: 10-16-2011
% =========================================================================

clear all;
clc;
addpath(genpath('.\ksvdbox'));  % add K-SVD box
addpath(genpath('.\OMPbox')); % add sparse coding algorithem OMP
load('.\trainingdata\featurevectors.mat','training_feats', 'testing_feats', 'H_train', 'H_test');

%% constant
sparsitythres = 30; % sparsity prior
sqrt_alpha = 4; % weights for label constraint term
sqrt_beta = 2; % weights for classification err term
dictsize = 570; % dictionary size
iterations = 50; % iteration number
iterations4ini = 20; % iteration number for initialization

%% dictionary learning process
% get initial dictionary Dinit and Winit
fprintf('\nLC-KSVD initialization... ');
[Dinit,Tinit,Winit,Q_train] = initialization4LCKSVD(training_feats,H_train,dictsize,iterations4ini,sparsitythres);
fprintf('done!');

% run LC K-SVD Training (reconstruction err + class penalty)
fprintf('\nDictionary learning by LC-KSVD1...');
[D1,X1,T1,W1] = labelconsistentksvd1(training_feats,Dinit,Q_train,Tinit,H_train,iterations,sparsitythres,sqrt_alpha);
save('.\trainingdata\dictionarydata1.mat','D1','X1','W1','T1');
fprintf('done!');

% run LC k-svd training (reconstruction err + class penalty + classifier err)
fprintf('\nDictionary and classifier learning by LC-KSVD2...')
[D2,X2,T2,W2] = labelconsistentksvd2(training_feats,Dinit,Q_train,Tinit,H_train,Winit,iterations,sparsitythres,sqrt_alpha,sqrt_beta);
save('.\trainingdata\dictionarydata2.mat','D2','X2','W2','T2');
fprintf('done!');

%% classification process
[prediction1,accuracy1] = classification(D1, W1, testing_feats, H_test, sparsitythres);
fprintf('\nFinal recognition rate for LC-KSVD1 is : %.03f ', accuracy1);

[prediction2,accuracy2] = classification(D2, W2, testing_feats, H_test, sparsitythres);
fprintf('\nFinal recognition rate for LC-KSVD2 is : %.03f ', accuracy2);

author: tiepvupsu

repo: DICTOL

save_path: github-repos/MATLAB/tiepvupsu-DICTOL


text:
function w = ymdf_to_weekday_gregorian ( y, m, d, f )

%*****************************************************************************80
%
%% YMDF_TO_WEEKDAY_GREGORIAN returns the weekday of a Gregorian YMDF date.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer Y, M, D, real F, the YMDF date.
%
%    Output, integer W, is the week day number of the date, with
%    1 for Sunday, through 7 for Saturday.
%
  jed = ymdf_to_jed_gregorian ( y, m, d, f );

  [ w, f2 ] = jed_to_weekday ( jed );

  return
end


text:
% op_plotspec.m
% Jamie Near, McGill University 2015.
%
% USAGE:
% out=op_plotspec(in,ppmmin,ppmmax,xlab,ylab,tit);
%
% DESCRIPTION:
% Plot the MR spectrum in the frequency domain.
%
% INPUTS:
% in     = input data in matlab structure format.  This argument can be a
%          MATLAB structure (formatted according to the FID-A structure
%          format), or it can be a cell array, where the elemenets of each
%          cell are FID-A structures.  In the latter case, each spectrum in
%          the structure will be plotted, with the option of a vertical
%          offset.
% ppmmin = lower limit of ppm scale to plot (optional.  Default = 0.2 ppm).
% ppmmax = upper limit of ppm scale to plot (optional.  Default = 5.2 ppm).
% xlab   = Label for the x-axis (optional.  Default = 'Frequency (ppm)');
% ylab   = label for the y-axis (optional.  Default = '');
% tit    = label for the title of the plot (optional.  Default = '');
%
% OUTPUTS:
% out    = Figure handle.

function out=op_plotspec(in,ppmmin,ppmmax,xlab,ylab,tit)

if nargin<6
    tit='';
    if nargin<5
        ylab='';
        if nargin<4
            xlab='Frequency (ppm)';
            if nargin<3
                ppmmax=5.2;
                if nargin<2
                    ppmmin=0.2;
                    if nargin<1
                        error('ERROR: no input spectrum specified.  Aborting!!');
                    end
                end
            end
        end
    end
end

if isstruct(in)
    if ndims(squeeze(in.fids))>2
        disp('More than 1 dimension detected in addition to the frequency dimension.');
        disp('Which dimension would you like to be displayed? ');
        if in.dims.coils
            disp(['     Enter: ''' num2str(in.dims.coils) ''' to display signal from all RF channels.']);
        end
        if in.dims.averages
            disp(['     Enter: ''' num2str(in.dims.averages) ''' to display signal from all averages.']);
        end
        if in.dims.subSpecs
            disp(['     Enter: ''' num2str(in.dims.subSpecs) ''' to display signal from all subspectra.']);
        end
        if in.dims.extras
            disp(['     Enter: ''' num2str(in.dims.extras) ''' to display signal from the ''extras'' dimension.']);
        end
        dim=input('............ ');
    else
        dim=0;
    end
    fignum=figure;
    if ~dim
        out=plot(in.ppm,real(squeeze(in.specs)));
    elseif dim==2
        out=plot(in.ppm,real(squeeze(in.specs(:,:,1))));
    elseif dim==3
        out=plot(in.ppm,real(squeeze(in.specs(:,1,:,1))));
    elseif dim==4
        out=plot(in.ppm,real(squeeze(in.specs(:,1,1,:,1))));
    elseif dim==5
        out=plot(in.ppm,real(squeeze(in.specs(:,1,1,1,:))));
    end
    xlim([ppmmin ppmmax]);
    set(gca,'XDir','reverse');
    set(gca,'FontSize',16);
    if isempty(ylab)
        set(gca,'YColor','w');
    else
        set(gca,'YColor','k');
    end
    set(gca,'XColor','k');
    set(gca,'Color','w');
    set(gcf,'Color','w');
    box off;
    title(tit);
    xlabel(xlab,'FontSize',20);
    ylabel(ylab,'FontSize',20);
    Fig1Ax1 = get(fignum, 'Children');
    Fig1Ax1Line1 = get(Fig1Ax1, 'Children');
    set(Fig1Ax1Line1, 'LineWidth', 1.2);
    %set(Fig1Ax1Line1,'MarkerSize', 10);
elseif iscell(in)
    if ndims(squeeze(in{1}.specs))>2
        disp('More than 1 dimension detected in addition to the frequency dimension.');
        disp('Which dimension would you like to be displayed? ');
        if in{1}.dims.coils
            disp(['     Enter: ''' num2str(in{1}.dims.coils) ''' to display signal from all RF channels.']);
        end
        if in{1}.dims.averages
            disp(['     Enter: ''' num2str(in{1}.dims.averages) ''' to display signal from all averages.']);
        end
        if in{1}.dims.subSpecs
            disp(['     Enter: ''' num2str(in{1}.dims.subSpecs) ''' to display signal from all subspectra.']);
        end
        if in{1}.dims.extras
            disp(['     Enter: ''' num2str(in{1}.dims.extras) ''' to display signal from the ''extras'' dimension.']);
        end
        dim=input('............ ');
    else
        dim=0;
    end
    figure;
    if ~dim
        out=plot(in{1}.ppm,real(in{1}.specs));
    elseif dim==2
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,:,1))));
    elseif dim==3
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,1,:,1))));
    elseif dim==4
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,1,1,:,1))));
    elseif dim==5
        out=plot(in{1}.ppm,real(squeeze(in{1}.specs(:,1,1,1,:))));
    end
    ylabel('ARB UNITS');
    disp('Multiple input spectra detected!! ')
    stagger=input('Please enter the desired vertical spacing of the spectra in ARB UNITS:  ');
    close;
    fignum=figure;
    hold
    colours=distinguishable_colors(length(in));
    for n=1:length(in)
        if ~dim
            out=plot(in{n}.ppm,real(in{n}.specs)+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==2
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,:,1)))+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==3
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,1,:,1)))+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==4
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,1,1,:,1)))+(n-1)*stagger,'Color',colours(n,:));
        elseif dim==5
            out=plot(in{n}.ppm,real(squeeze(in{n}.specs(:,1,1,1,:)))+(n-1)*stagger,'Color',colours(n,:));
        end
        xlim([ppmmin ppmmax]);
        set(gca,'XDir','reverse');
        set(gca,'FontSize',16);
        if isempty(ylab)
            set(gca,'YColor','w');
        else
            set(gca,'YColor','k');
        end
        set(gca,'XColor','k');
        set(gca,'Color','w');
        set(gcf,'Color','w');
        box off;
        title(tit);
        xlabel(xlab,'FontSize',20);
        ylabel(ylab,'FontSize',20);
        Fig1Ax1 = get(fignum, 'Children');
        Fig1Ax1Line1 = get(Fig1Ax1, 'Children');
        set(Fig1Ax1Line1, 'LineWidth', 1.2);
    end
else
    error('ERROR:  Input data format not recognized.  ABORTING!!');
end

author: CIC-methods

repo: FID-A

save_path: github-repos/MATLAB/CIC-methods-FID-A


text:
function t = traceProduct(A, B)

% TRACEPRODUCT Returns the trace of the product of two matrices.
% FORMAT
% DESC returns the trace of the product of two matrices, tr(A*B).
% ARG A : the first matrix in the product.
% ARG B : the second matrix in the product.
% RETURN t : the trace of the product.
%
% SEEALSO : trace
%
% COPYRIGHT : Neil D. Lawrence, 2004

% NDLUTIL

t = sum(sum(A.*B'));

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
% poolType = 'mean' or 'max'
% poolLayer = integer layer number after which we do the pooling
function layer = genNetworkTemporalConvLSTM(para)

layer = genNetworkTemporalConv2(para);
useFirstNLayer = length(para.nFilter)*3+1;
layer = layer(1:useFirstNLayer);

paraLSTM = para;
paraLSTM.inputDim = layer{end}.dim(1);
layerLSTM = genNetworkLSTM(paraLSTM);

layer = [layer layerLSTM(2:end)];

end

author: singaxiong

repo: SignalGraph


text:
function r8vec_norm_li_test ( )

%*****************************************************************************80
%
%% R8VEC_NORM_LI_TEST tests R8VEC_NORM_LI.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 April 2009
%
%  Author:
%
%    John Burkardt
%
  n = 10;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'R8VEC_NORM_LI_TEST\n' );
  fprintf ( 1, '  For an R8VEC:\n' );
  fprintf ( 1, '  R8VEC_NORM_LI:   L-infinity norm.\n' );

  b = -n;
  c = n;

  seed = 123456789;

  [ a, seed ] = r8vec_uniform_ab ( n, b, c, seed );

  r8vec_print ( n, a, '  Input vector:' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  L-Infinity norm: %f\n', r8vec_norm_li ( n, a ) );

  return
end


text:
function out = MF_FitSubsegments(y,model,order,subsetHow,samplep,randomSeed)
% MF_FitSubsegments Robustness of model parameters across different segments of a time series
%
% The spread of parameters obtained (including in-sample goodness of fit
% statistics) provide some indication of stationarity.
%
% Values of goodness of fit provide some indication of model suitability.
%
% This code inherits strongly from MF_CompareTestSets
%
%---INPUTS:
% y, the input time series.
%
% model, the model to fit in each segments of the time series:
%           'arsbc': fits an AR model using the ARfit package. Outputs
%                       statistics are on how the optimal order, p_{opt}, and
%                       the goodness of fit varies in different parts of the
%                       time series.
%           'ar': fits an AR model of a specified order using the code
%                   ar from Matlab's System Identification Toolbox. Outputs are
%                   on how Akaike's Final Prediction Error (FPE), and the fitted
%                   AR parameters vary across the different segments of time
%                   series.
%           'ss': fits a state space model of a given order using the code
%                   n4sid from Matlab's System Identification Toolbox. Outputs
%                   are on how the FPE varies.
%           'arma': fits an ARMA model using armax code from Matlab's System
%                   Identification Toolbox. Outputs are statistics on the FPE,
%                   and fitted AR and MA parameters.
%
% subsetHow, how to choose segments from the time series, either 'uniform'
%               (uniformly) or 'rand' (at random).
%
% samplep, a two-vector specifying how many segments to take and of what length.
%           Of the form [nsamples, length], where length can be a proportion of
%           the time-series length. e.g., [20,0.1] takes 20 segments of 10% the
%           time-series length.
%
% randomSeed, whether (and how) to reset the random seed, using BF_ResetSeed
%               (for when subsetHow is 'rand')
%
%---OUTPUTS: depend on the model, as described above.

% ------------------------------------------------------------------------------
% Copyright (C) 2020, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function 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/>.
% ------------------------------------------------------------------------------

% ------------------------------------------------------------------------------
%% Preliminaries
% ------------------------------------------------------------------------------
N = length(y); % length of time series

% ------------------------------------------------------------------------------
%% Check Inputs
% ------------------------------------------------------------------------------

% (1) y: column vector time series
if nargin < 1 || isempty(y)
    error('Give us a time series, ya mug');
end
% Convert y to time series object
y = iddata(y,[],1);

% (2) model, the type of model to fit
if nargin < 2 || isempty(model)
    model = 'ss'; % fit a state space model by default
end

% (3) order of model, order
if nargin < 3 || isempty(order)
    order = 2; % model of order 2 by default. Not very good defaults.
end

% (4) How to choose subsets from the time series, subsetHow
if nargin < 4 || isempty(subsetHow)
    subsetHow = 'rand'; % takes segments randomly from time series
end

% (5) Sampling parameters, samplep
if nargin < 5 || isempty(samplep)
    samplep = [20, 0.1]; % sample 20 times with 10%-length subsegments
end

% (6) randomSeed: how to treat the randomization
if nargin < 6
    randomSeed = [];
end

% ------------------------------------------------------------------------------
%% Set the ranges beforehand
% ------------------------------------------------------------------------------
% Number of samples to take, numPred
numPred = samplep(1);
r = zeros(numPred,2); % ranges

switch subsetHow
    case 'rand'
        if samplep(2) < 1 % specified a fraction of time series
            l = floor(N*samplep(2));
        else % specified an absolute interval
            l = samplep(2);
        end

        % Control the random seed (for reproducibility):
        BF_ResetSeed(randomSeed);

        % numPred random starting points:
        spts = randi(N-l+1,numPred,1);
        r(:,1) = spts;
        r(:,2) = spts+l-1;

    case 'uniform'
        if length(samplep) == 1 % size will depend on number of unique subsegments
            spts = round(linspace(0,N,numPred+1)); % numPred+1 boundaries = numPred portions
            r(:,1) = spts(1:numPred)+1;
            r(:,2) = spts(2:end);
        else
            if samplep(2) < 1 % specified a fraction of time series
                l = floor(N*samplep(2));
            else % specified an absolute interval
                l = samplep(2);
            end
            spts = round(linspace(1,N-l+1,numPred)); % numPred+1 boundaries = numPred portions
            r(:,1) = spts;
            r(:,2) = spts+l-1;
        end

    otherwise
        error('Unknown subset method ''%s''',subsetHow);
end

% ------------------------------------------------------------------------------
%% Fit the model to each training set
% ------------------------------------------------------------------------------
% model will be stored as a model object, m
% model is fitted using the entire dataset as the training set
% test sets will be smaller chunks of this.
% [could also fit multiple models using data not in multiple test sets, but
% this is messier]
switch model
    case 'arsbc'
        %% Fit AR models of 'best' order according to SBC, using arfit package
        % fit AR models of 'best' order, return statistics on how this best
        % order changes. The order input argument is not used for this
        % option.
        orders = zeros(numPred,1);
        sbcs = zeros(numPred,1);
        yy = y.y;
        for i = 1:numPred
            % Use arfit software to retrieve the optimum AR(p) order by
            % Schwartz's Bayesian Criterion, SBC (or BIC); in the range
            % p = 1-10
            % Enforce zero mean level. This could be relaxed.
            try
                [west, Aest, Cest, SBC] = ARFIT_arfit(yy(r(i,1):r(i,2)), 1, 10, 'sbc', 'zero');
            catch emsg
                if strcmp(emsg.message,'Time series too short.')
                   fprintf(1,'Time Series is too short for ARFIT\n');
                   out = NaN; return
                else
                    error('Problem fitting AR model');
                end
            end
            orders(i) = length(Aest);
            sbcs(i) = min(SBC);
        end

        % Return statistics
        out.orders_mode = mode(orders);
        out.orders_mean = mean(orders);
        out.orders_std = std(orders);
        out.orders_max = max(orders);
        out.orders_min = min(orders);
        out.orders_range = range(orders);

        out.sbcs_mean = mean(sbcs);
        out.sbcs_std = std(sbcs);
        out.sbcs_range = range(sbcs);
        out.sbcs_min = min(sbcs);
        out.sbcs_max = max(sbcs);

    case 'ar'
        %% Fit AR model of specified order
        % Return statistics on parameters and goodness of fit

        %% Check that a System Identification Toolbox license is available to run the 'ar' function:
        BF_CheckToolbox('identification_toolbox')

        fpes = zeros(numPred,1);
        as = zeros(numPred,order+1);
        for i = 1:numPred
            % fit the ar model
            m = ar(y(r(i,1):r(i,2)),order);
            % get parameters and goodness of fit
            fpes(i) = m.EstimationInfo.FPE;
            as(i,:) = m.a;
        end

        % statistics on FPE
        out.fpe_std = std(fpes);
        out.fpe_mean = mean(fpes);
        out.fpe_max = max(fpes);
        out.fpe_min = min(fpes);
        out.fpe_range = range(fpes);

        % Statistics on fitted AR parameters
        for i = 1:order % first column will be ones
            % Dynamic field referencing:
            out.(['a_',num2str(i),'_std']) = std(as(:,i+1));
            out.(['a_',num2str(i),'_mean']) = mean(as(:,i+1));
            out.(['a_',num2str(i),'_max']) = max(as(:,i+1));
            out.(['a_',num2str(i),'_min']) = min(as(:,i+1));
            % eval(sprintf('out.a_%u_std = std(as(:,%u+1));',i,i));
            % eval(sprintf('out.a_%u_mean = mean(as(:,%u+1));',i,i));
            % eval(sprintf('out.a_%u_max = max(as(:,%u+1));',i,i));
            % eval(sprintf('out.a_%u_min = min(as(:,%u+1));',i,i));
        end

    case 'ss'
        %% Fit state space models of specified order
        % Return statistics on goodness of fit
        % Could do parameters too, but I this would involve many outputs
        fpes = zeros(numPred,1);
        for i = 1:numPred
            try  m = n4sid(y(r(i,1):r(i,2)),order);
            catch
                % Some range of the time series is invalid for fitting the
                % model to.
                error('Couldn''t fit this state space model')
            end
            fpes(i) = m.EstimationInfo.FPE;
        end

        % statistics on FPE
        out.fpe_std = std(fpes);
        out.fpe_mean = mean(fpes);
        out.fpe_max = max(fpes);
        out.fpe_min = min(fpes);
        out.fpe_range = range(fpes);

    case 'arma'
        %% fit an ARMA model of specified order(s)
        % Note: order should be a two-component vector
        % Output parameters and goodness of fit
        fpes = zeros(numPred,1);
        ps = zeros(numPred,order(1)+1);
        qs = zeros(numPred,order(2)+1);

        for i = 1:numPred
            try
                m = armax(y(r(i,1):r(i,2)),order);
            catch emsg
                error('Couldn''t fit this ARMA model')
            end
            fpes(i) = m.EstimationInfo.FPE;
            ps(i,:) = m.a;
            qs(i,:) = m.c;
        end

        % statistics on FPE
        out.fpe_std = std(fpes);
        out.fpe_mean = mean(fpes);
        out.fpe_max = max(fpes);
        out.fpe_min = min(fpes);
        out.fpe_range = range(fpes);

        % Statistics on fitted AR parameters, p
        for i = 1:order % first column will be ones
            out.(['p_',num2str(i),'_std']) = std(ps(:,i+1));
            out.(['p_',num2str(i),'_mean']) = mean(ps(:,i+1));
            out.(['p_',num2str(i),'_max']) = max(ps(:,i+1));
            out.(['p_',num2str(i),'_min']) = min(ps(:,i+1));
        end

        % Statistics on fitted MA parameters, q
        for i = 1:order % first column will be ones
            out.(['q_',num2str(i),'_std']) = std(qs(:,i+1));
            out.(['q_',num2str(i),'_mean']) = mean(qs(:,i+1));
            out.(['q_',num2str(i),'_max']) = max(qs(:,i+1));
            out.(['q_',num2str(i),'_min']) = min(qs(:,i+1));
        end
    otherwise
        error('Unknown model ''%s''',model);
end

end

author: benfulcher

repo: hctsa

save_path: github-repos/MATLAB/benfulcher-hctsa


text:
function vw = switch2Gray(vw)
%
% Switches Volume view to gray mode:
% - changes vw.subdir to 'Gray'
% - sets vw.ui.grayVolButtons=2
% - computes/loads vw.coords
% - loads user preferences
% - empties co, amp, ph, map
%
% djh, 7/98
% ress, 6/03: Added 3D button UI controls

if isempty(vw)
    myErrorDlg('Volume window must be open to switch it to gray mode.');
end

vwType = viewGet(vw, 'view type');

if ~strcmp(vwType,'Volume') && ~strcmp(vwType,'Gray')
    myErrorDlg('Only volume window can be switched to gray mode.');
end

% set viewType
vw = viewSet(vw,'view type','Gray');
vw = viewSet(vw,'subdir','Gray');

% Compute/load VOLUME.coords
vw = getGrayCoords(vw);

% Empty data matrices already set in openRaw...
% vw.co = [];
% vw.amp = [];
% vw.ph = [];
% vw.map = [];

% Only do this for VOLUME, not for hiddenVolume
if strcmp(vwType, 'VOLUME')
    if checkfields(vw, 'ui', 'grayVolButtons')
          % Set vw.ui.grayVolButtons
          selectButton(vw.ui.grayVolButtons, 1);
    end
end

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function pdf = normal_truncated_b_pdf ( x, mu, s, b )

%*****************************************************************************80
%
%% NORMAL_TRUNCATED_B_PDF evaluates the upper truncated Normal PDF.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 August 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real X, the argument of the PDF.
%
%    Input, real MU, S, the mean and standard deviation of the
%    parent Normal distribution.
%
%    Input, real B, the upper truncation limit.
%
%    Output, real PDF, the value of the PDF.
%
  beta = ( b - mu ) / s;
  xi = ( x - mu ) / s;

  beta_cdf = normal_01_cdf ( beta );
  xi_pdf = normal_01_pdf ( xi );

  pdf = xi_pdf / beta_cdf / s;

  return
end

author: johannesgerer


text:
function C = IPTColorfullness(imgIPT)
%
%       C = IPTColorfullness(imgIPT)
%
%       This computes the colorfullness in the IPT color space
%
%       input:
%         - imgIPT: an image in the IPT color space
%
%       output:
%         - C: colorfullness
%
%     Copyright (C) 2015  Francesco Banterle
%
%     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/>.
%

check3Color(imgIPT);

C = sqrt(imgIPT(:,:,2).^2 + imgIPT(:,:,3).^2);

end

author: banterle


text:
function dataOut=plotMultipleVoxAboveThreshPerCondition(view)
%
% dataOut=plotMultipleVoxAboveThreshPerCondition
%
% Bar plot of the number of superthreshold voxels (based on the co) in a particular condition
% All y-axes are made the same. The bar heights
% and total voxels in each ROI can be obtained from the userdata
%
% arw 04/01/05

mrGlobals;

% Select ROIs
nROIs=size(view.ROIs,2);
roiList=cell(1,nROIs);
for r=1:nROIs
    roiList{r}=view.ROIs(r).name;
end
selectedROIs = find(buttondlg('ROIs to Plot',roiList));
nROIs=length(selectedROIs);
if (nROIs==0)
    error('No ROIs selected');
end

% Plot it
selectGraphWin
clf
fontSize = 8;
headerStr = ['Vox above thresh'];
set(gcf,'Name',headerStr);

minylim=0;
maxylim=0;
nrows=0;
ncols=0;

nscans = numScans(view);
ROIcos=zeros(nscans,nROIs);
thisCoThresh=get(view.ui.cothresh.sliderHandle,'value');
totalVoxels=zeros(nscans,nROIs);
voxAboveThresh=zeros(nscans,nROIs);

for r=1:nROIs

    n=selectedROIs(r);
    view = selectROI(view,n); % is there another way?
    ROIcoords=getCurROIcoords(view);

    for scanNum=1:nscans

        subCo = getCurDataROI(view,'co',scanNum,ROIcoords);
        totalVoxels(scanNum,r)=size(subCo,2);
        voxAboveThresh(scanNum,r)=length(find(subCo>=thisCoThresh));
    end

    xstr{r}=int2str(r);
    roiName{r}=view.ROIs(selectedROIs(r)).name;
    fprintf(['\n#%d :',roiName{r}],r);

end
dataOut.totalVoxels=totalVoxels;
dataOut.voxAboveThresh=voxAboveThresh;
dataOut.ROIname=roiName;

% Now do the plotting

if nscans<=3
    nrows=1;
    ncols=nscans;
    fontSize = 9;
elseif nscans<=8
    nrows=2;
    ncols=ceil(nscans/nrows);
    fontSize = 8;
else
    nrows=ceil(sqrt(nscans));
    ncols=ceil(nscans/nrows);
    fontSize = 6;
end

for r=1:nscans

    subplot(nrows,ncols,r);

    %plot the bar graph
    h=bar(voxAboveThresh(r,:));% ,ROIseZ(r,:)',xstr);
    xlabel('ROI','FontSize',fontSize);
    ylabel('Number above threshold','FontSize',fontSize);
    set(gca,'FontSize',ceil(fontSize*1.2));
    conditionName{r}=dataTYPES(view.curDataType).scanParams(r).annotation;
    fprintf(['\nCondition #%d :',conditionName{r}],r);

    fprintf('\nTotalVoxels: %d',totalVoxels(r,:));

    title(['Condition #: ' int2str(r)]);
    yl=ylim;

    if yl(1)< minylim
        minylim=yl(1);
    end
    if yl(2)> maxylim
        maxylim=yl(2);
    end
end

set(gca,'UserData',dataOut);

% give all plots same y-axis

for r=1:nscans
    subplot(nrows,ncols,r);
    ylim([minylim maxylim]);
end

return;


text:
function [ mD ] = CalcDistanceMatrixCRows( mX )
% ----------------------------------------------------------------------------------------------- %
% [ mD ] = CalcDistanceMatrixARows( mX )
%   Calculates the distance matrix for the input data. The distance matrix
%   is a symmetric matrix where 'mD(ii, jj) = dist(mX(ii, :), mX(jj, :));'.
%   This function uses the squared Euclidean Distance for the distance
%   metric.
% Input:
%   - mX            -   Data Matrix.
%                       Each data sample is a row of the matrix.
%                       Structure: Matrix (numVars x varDim).
%                       Type: 'Single' / 'Double'.
%                       Range: (-inf, inf).
% Output:
%   - mD            -   Distance Matrix.
%                       A symmetric matrix where 'mD(ii, jj) = dist(mX(ii,
%                       :), mX(jj, :));'.
%                       Structure: Matrix (numVars x numVars).
%                       Type: 'Single' / 'Double'.
%                       Range: [0, inf).
% References
%   1.  A
% Remarks:
%   1.  B
% TODO:
%   1.  C
% Release Notes:
%   -   1.0.000     01/01/2021  Royi Avital	RoyiAvital@yahoo.com
%       *   First release version.
% ----------------------------------------------------------------------------------------------- %

FALSE   = 0;
TRUE    = 1;

OFF     = 0;
ON      = 1;

mG = mX * mX.';
vG = diag(mG);

mD = vG.' + vG - (2 * mG);

end

author: RoyiAvital

repo: StackExchangeCodes


text:
% ANFIS-ART Feed-Forward operation.
function y = anfis_art_forward(x,u2,v2,gamma,ThetaL4)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%        								 							     				                                       %
%   			                 	NETWORK FUNCTIONALITY SECTION					   %
%      																					                                       %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
NumInVars    = size(x,1);
NumInTerms = size(u2,2);
NumRules     = NumInTerms;

% LAYER 1 - MF NODES
% Each node in this layer acts as a one-dimensional membership function.
% Out2 is a (NumInVars X NumInTerms) matrix.
 In1mat = x*ones(1,NumInTerms);
 % Matrix containing a copy of Out1 for each Layer 2 Term Node.
 Out1 = 1 - g(In1mat-v2,gamma) - g(u2-In1mat,gamma);

% LAYER 2 - PRECONDITION MATCHING OF FUZZY LOGIC RULES
% RULE NODES == NumInTerms
 Out2 = prod(Out1,1);
 S_2 = sum(Out2);

% LAYER 3 - NORMALIZATION NODES - All Node Activity Adds-up to unity.
if S_2~=0
     Out3 = Out2/S_2;
end

% LAYERS 4 - 5: CONSEQUENT NODES - SUMMING NODE
 Aux1 = [x; 1]*Out3;

 % New Input Training Data shaped as a column vector.
 a = reshape(Aux1,(NumInVars+1)*NumRules,1);
 y = a'*ThetaL4;


text:
function [net] = net_init_char_qrnn(opts)

rng('default');
rng(0) ;

f=1/100 ;

n_hidden_nodes=opts.parameters.n_hidden_nodes;
n_input_nodes=opts.parameters.n_input_nodes;
n_output_nodes=opts.parameters.n_output_nodes;
n_gates=opts.parameters.n_gates;

net{1}.type='Gates';% update gates
net{1}.layers = {} ;
net{1}.layers{end+1} = struct('type', 'mlp', ...
                           'weights', {{f*randn(n_gates*n_hidden_nodes,n_input_nodes, 'single'), zeros(n_gates*n_hidden_nodes,1,'single')}}) ;
net{1}.layers{end+1} = struct('type', 'sigmoid') ;

%generate the adjustments of the hidden nodes for the current time frame
net{2}.type='InputTransform';
net{2}.layers = {} ;
net{2}.layers{end+1} = struct('type', 'mlp', ...
                           'weights', {{f*randn(n_hidden_nodes,n_input_nodes, 'single'), zeros(n_hidden_nodes,1,'single')}}) ;
net{2}.layers{end+1} = struct('type', 'relu') ;

net{3}.type='Fit';
net{3}.layers = {};
net{3}.layers{end+1} = struct('type', 'mlp', ...
                           'weights', {{f*randn(n_output_nodes,n_hidden_nodes, 'single'), zeros(n_output_nodes,1,'single')}}) ;
net{3}.layers{end+1} = struct('type', 'softmaxloss');

author: yechengxi

repo: LightNet

save_path: github-repos/MATLAB/yechengxi-LightNet


text:
function elliptic_em_values_test ( )

%*****************************************************************************80
%
%% ELLIPTIC_EM_VALUES_TEST demonstrates the use of ELLIPTIC_EM_VALUES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 February 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'ELLIPTIC_EM_VALUES_TEST:\n' );
  fprintf ( 1, '  ELLIPTIC_EM_VALUES stores values of\n' );
  fprintf ( 1, '  the complete elliptic integral of the second\n' );
  fprintf ( 1, '  kind, with parameter modulus M.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      M            EM(M)\n' );
  fprintf ( 1, '\n' );

  n_data = 0;

  while ( 1 )

    [ n_data, x, fx ] = elliptic_em_values ( n_data );

    if ( n_data == 0 )
      break
    end

    fprintf ( 1, '  %12f  %24.16f\n', x, fx );

  end

  return
end

repo: jburkardt-m


text:
function [pop] = mutation_pop(pop)
%   Applies mutation to whole population.
global pmut_real ;
global eta_m ;
global min_realvar ;
global max_realvar ;

[popsize,~] = size(pop);
nreal = length(min_realvar);

for i = 1:popsize
    pop(i,1:nreal) = real_mutate(pop(i,1:nreal), pmut_real, eta_m, ...
                                    min_realvar, max_realvar);
end

end

author: chudur-budur


text:
function [X]=missmult(A,B)

%MISSMULT product of two matrices containing NaNs
%
%[X]=missmult(A,B)
%This function determines the product of two matrices containing NaNs
%by finding X according to
%     X = A*B
%If there are columns in A or B that are pur missing values,
%then there will be entries in X that are missing too.
%
%The result is standardized, that is, corrected for the lower
%number of contributing terms.
%
%Missing elements should be denoted by 'NaN's

% Copyright (C) 1995-2006  Rasmus Bro & Claus Andersson
% Copenhagen University, DK-1958 Frederiksberg, Denmark, rb@life.ku.dk
%
% This program is free software; you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation; either version 2 of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
% You should have received a copy of the GNU General Public License along with
% this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
% Street, Fifth Floor, Boston, MA  02110-1301, USA.

%INBOUNDS
%REALONLY

[ia ja]=size(A);
[ib jb]=size(B);
X=zeros(ia,jb);

one_arry=ones(ia,1);
for j=1:jb,
   p=one_arry*B(:,j)';
   tmpMat=A.*p;
   X(:,j)=misssum(tmpMat')';
end;

author: andrewssobral

repo: mtt

save_path: github-repos/MATLAB/andrewssobral-mtt


text:
function [ CONDXY ] = ConditionalHist( X,Y,varargin)
%[CONDXY] = ConditionalHist(X,Y) Calculates the conditional probabilty
%of Y given X
%
%INPUT
%   X
%   Y
% (options)
%   'numXbins'  (default: 50)
%   'numYbins'  (default: 50)
%   'Xbounds'
%   'Ybounds'
%   'Xbinoverlap' (default: 1)
%   'minX'      (default: 25)
%   'conditionby'   condition on X with different occupancy from datapoints
%
%
%OUTPUT
%   CONDXY
%       .pYX    a [numXbins x numYbins] matrix in which the [x,y]th element is P(y|x)
%       .XYhist joint histogram of X and Y
%       .XYprop joint probability of X and Y
%       .Xhist  histogram of X
%       .Xbins  X bins
%       .Ybins  Y bins
%
%DLevenstein 2019
%%
p = inputParser;
addParameter(p,'numXbins',50)
addParameter(p,'numYbins',50)
addParameter(p,'Xbounds',[])
addParameter(p,'Ybounds',[])
addParameter(p,'minX',25)
addParameter(p,'Xbinoverlap',1)
addParameter(p,'conditionby',[])
parse(p,varargin{:})
numXbins = p.Results.numXbins;
numYbins = p.Results.numYbins;
Xbounds = p.Results.Xbounds;
Ybounds = p.Results.Ybounds;
minX = p.Results.minX;
Xbinoverlap = p.Results.Xbinoverlap;
conditionby = p.Results.conditionby;

%% For cell input

if iscell(Y) && iscell(X)
    CONDXY = cellfun(@(x,y) ConditionalHist(x,y,varargin{:}),...
        X,Y,'UniformOutput',false);
    CONDXY = bz_CollapseStruct([CONDXY{:}],3);
    CONDXY.Xbins = CONDXY.Xbins(1,:,1);
    CONDXY.Ybins = CONDXY.Ybins(1,:,1);
    return
end

%% For multiple columns in X - conditonal probabilty of each

if size(Y,2)>1 && size(X,2)==1
    for yy = 1:size(Y,2)
        CONDXY(yy) = ConditionalHist(X,Y(:,yy),varargin{:});
    end
    CONDXY = bz_CollapseStruct(CONDXY,3);
    return
end

%%
if isempty(Xbounds)
    Xbounds(1) = min(X); Xbounds(2) = max(X);
end
if isempty(Ybounds)
    Ybounds(1) = min(Y(~isinf(Y))); Ybounds(2) = max(Y(~isinf(Y)));
end

Xedges = linspace(Xbounds(1),Xbounds(2),numXbins+1);
Xbins = Xedges(1:end-1)+ 0.5.*diff(Xedges([1 2]));
Xedges(1) = -inf;Xedges(end) = inf;

Yedges = linspace(Ybounds(1),Ybounds(2),numYbins+1);
Ybins = Yedges(1:end-1)+ 0.5.*diff(Yedges([1 2]));
Yedges(1) = -inf;Yedges(end) = inf;

%First calculate the marginal probability of X
[Xhist,~,XbinID] = histcounts(X,Xedges);

%Then calculate the joint probabilty of X and Y
if length(Ybins) ==1
    XYhist = Xhist;
elseif isempty(Y)
    warning('Y is empty... using nans')
    Y = nan(size(X));
    XYhist = nan(length(Xbins),length(Ybins));
else
    [XYhist] = hist3([X,Y],{Xbins,Ybins});
end

% Conditional probability of Y given X
if isempty(conditionby)
    Xhist4norm = Xhist;
else
    Xhist4norm = histcounts(conditionby,Xedges);
end
Xhist4norm(Xhist4norm<=minX) = nan; %Remove bins that don't have enough sampling
pYX = bsxfun(@(x,y) x./y,XYhist,Xhist4norm');

%Mean Y given X
for xx = 1:length(Xbins)
    meanYX(xx) = nanmean(Y(XbinID==xx));
    meanYX(isnan(Xhist4norm)) = nan;
end

CONDXY.pYX = pYX;
CONDXY.XYhist = XYhist;
CONDXY.XYprob = XYhist./nansum(XYhist(:));
CONDXY.meanYX = meanYX;
CONDXY.Xhist = Xhist;
CONDXY.pX = Xhist./nansum(Xhist);
CONDXY.Xbins = Xbins;
CONDXY.Ybins = Ybins;

%%
% figure
% imagesc(CONDXY.Xbins,CONDXY.Ybins,CONDXY.pYX')
% axis xy
end

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function cvx_optpnt = exponential( sx )

%EXPONENTIAL   Exponential cone.
%   EXPONENTIAL, called with no arguments, creates three scalar variables X,
%   Y, and Z and constraints them to lie in an exponetial cone. That is,
%   given the declaration
%       variables x y z
%       {x,y,z} == exp_cone
%   constraints the variables to satisfy
%       y*exp(x/y) <= z
%       y > 0
%   The inequality form does not obey the disciplined convex programming
%   ruleset, but a function EXP_P has been created to represent this
%   computation; so the set declaration above is equivalent to
%       EXP_P(X,Y) <= Z
%   EXP_CONE(SX), where SX is a size vector, creates three array variables
%   X, Y, and Z, each of size SX, which are constrained elementwise to
%   satisfy EXP_P(X,Y) <= Z. If SX is empty, then SX=[1,1] is assumed.

cvx_expert_check( 'exponential' );
narginchk(0,1);

%
% Check size vector
%

if nargin == 0 || isempty( sx ),
    sx = [1,1]; %#ok
else
    [ temp, sx ] = cvx_check_dimlist( sx, true ); %#ok
    if ~temp,
        error( 'First argument must be a dimension vector.' );
    end
end

%
% Build the cone
%

cvx_begin set
    variables x( sx ) y( sx ) z( sx )
    [ tx, dummy ] = find( cvx_basis( x ) ); %#ok
    [ ty, dummy ] = find( cvx_basis( y ) ); %#ok
    [ tz, dummy ] = find( cvx_basis( z ) ); %#ok
    newnonl( cvx_problem, 'exponential', [ tx(:)' ; ty(:)' ; tz(:)' ] );
    cvx___.canslack( tx ) = false;
    cvx___.canslack( ty ) = false;
cvx_end

cvx_optpnt = cvxtuple( struct( 'x', x, 'y', y, 'z', z ) );

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX


text:
function points = getSpacedPoints(X1, X2, N, spacing)
%GETSPACEDPOINTS     Create vector of log or linear spaced points.
%
% DESCRIPTION:
%       getSpacedPoints generates a row vector of either logarithmically
%       or linearly spaced points between X1 and X2. When spacing is set to
%       'linear', the function is identical to the inbuilt linspace
%       function. When spacing is set to 'log', the function is similar to
%       the inbuilt logspace function, except that X1 and X2 define the
%       start and end numbers, not decades. For logarithmically spaced
%       points, X1 must be > 0. If N < 2, X2 is returned.
%
% USAGE:
%       points = getSpacedPoints(X1, X2)
%       points = getSpacedPoints(X1, X2, N)
%       points = getSpacedPoints(X1, X2, N, spacing)
%
% INPUTS:
%       X1          - starting points value
%       X2          - ending points value (where X2 > X1)
%
% OPTIONAL INPUTS:
%       N           - number of points in the vector (default = 100)
%       spacing     - 'log' or 'linear' spaced values (default = 'linear')
%
% OUTPUTS:
%       points      - row vector of equally spaced points
%
% ABOUT:
%       author      - Bradley E. Treeby
%       date        - 14th July 2005
%       last update - 1st December 2012
%
% 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/>.

% check for number of points input
if nargin < 3
    N = 100;
end

% check for spacing input
if nargin < 4
    spacing = 'linear';
end

% check if the end point is larger than the start point
if X2 <= X1
    error('X2 must be larger than X1');
end

% force N to be an integer
N = round(N);

if (N < 2)
    % return the end point if N < 2
    points = X2;
elseif (N == 2)
    % return the start and end points if N = 2
    points(1) = X1;
    points(2) = X2;
else

    % update X1 and X2 values for log spaced variables
    if (strcmp(spacing, 'log'))

        % check that X1 is greater than 0
        if X1 <= 0
            error('X1 must be > 0 for log spaced points');
        end

        X1 = log10(X1);
        X2 = log10(X2);
    end

    % create step variable and points range
    step = (X2 - X1)/(N - 1);
    points = X1:step:X2;

    % update log spaced points
    if (strcmp(spacing, 'log'))
        points = 10.^(points);
    end
end

repo: Aero-matlab


text:
%DYADIC Dyadic datafile operations
%
%  C = DYADIC(A,P,B,Q)
%
% Computes C = P*A + Q*B
%
% This datafile operation is, like others, either stored as
% a preprocessing or as a postprocessing for datafiles using
% a call to DYADICM.
%
% Note that in P a function name can be stored and in Q a cell
% array with a set of parameters. In that case effectively
% feval(p,a1,a2,q{:}) will be executed inside DYADICM.
%
% SEE ALSO (PRTools Guide)
% DATAFILES, DYADICM

author: marianux

repo: ecg-kit

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


text:
% Fig. 9.13  Feedback Control of Dynamic Systems, 6e
%             Franklin, Powell, Emami
% script to generate Fig. 9.13
% using the general nonlinear simulation
clf;
N=1;
a=2;
r=0;
num=[1 2 1];
den=[1 0 0 0];
nf=1;
df=1;
for k=1:3
   r=r+1;
   sim('nonsim',20)
   hold on
   plot(yn(:,1),yn(:,2))
end
r=3.475;
sim('nonsim',20)
plot(yn(:,1),yn(:,2))
xlabel('Time (sec)');
ylabel('Amplitude');
Title('Figure 9.13 Simulation of a conditionally stable system')
text(2,1.5,'r = 1')
text(2,3.1,'r = 2')
text(2.3,5.2,'r = 3')
text(2,6.5,'r = 3.475')
nicegrid