text:
function[varargout]=about_jtopo(varargin)
%ABOUT_JTOPO  One-sixth degree global topography, from Smith and Sandwell + IBCAO.
%   _______________________________________________________________________
%
%   *|* jtopo.png --- Figure illustrating the JTOPO topography dataset.
%   Type 'jhelp about_jtopo' to view this image. *|*
%   _______________________________________________________________________
%
%   JTOPO is a matfile containing smoothed one-twelfth degree global
%   topography based on the Smith and Sandwell database together with the
%   International Bathymetric Chart of the Arctic Ocean (IBCAO).
%
%   LOAD JTOPO loads the structure JTOPO, with the following fields:
%
%       jtopo.about     Pointer to this document
%       jtopo.lat       Array of latitudes         [2048 x 1]
%       jtopo.lon       Array of longitudes        [1 x 4320]
%       jtopo.topo      Matrix of topography       [2048 x 4320]
%
%   Typing 'use jtopo' maps these fields into variables in the current
%   workspace, e.g. 'use jtopo, pcolor(lon,lat,topo), shading interp'.
%
%   TOPO is in units of kilometers and is positive for above sea level,
%   and negative for below sea level.
%
%   LAT is uniformly spaced from -80.666 to  89.917, and LON is uniformly
%   spaced from -180 to 179.912.  These are *grid-centered* values, that
%   is, they indicate midpoints of the topography cells.
%
%   JTOPO is distributed with JLAB, available at http://www.jmlilly.net.
%
%   See also READTOPO, which reads in any region of the Smith and Sandwell
%   data, ABOUT_IBCAO, and TOPOPLOT, which makes simple plots using JTOPO.
%   __________________________________________________________________
%
%   Processing
%
%   The one-minute Smith and Sandwell data, and 1/2 minute IBCAO data, are
%   smoothed to one-twelfth of a degree by averaging in 1/12 x 1/12 bins.
%
%   Smith and Sandwell is defined from -80.738 and 80.738, while IBCAO is
%   defined from 64 N to 90 N.  In the overlap region, from 64 to 84.738 N,
%   the root-mean-square different between the two datasets is about 50 m.
%
%   JTOPO uses a linear blend to resolve the small discrepencies in the
%   overlap region.  From 64 to 84.738 N, JTOPO transitions from being all
%   Smith and Sandwell, to all IBCAO, with a weighted average in between.
%   __________________________________________________________________
%
%   Data and documentation
%
%   This dataset is based on the Smith and Sandwell Global Topography
%   Dataset v. 19.1 and IBCAO v. 3.0, which are included with JDATA.
%
%   The source and reference for the Smith and Sandwell dataset are
%
%       http://topex.ucsd.edu/WWW_html/mar_topo.html
%
%      Smith, W. H. F., and D. T. Sandwell, Global seafloor topography
%         from satellite altimetry and ship TOPO soundings, Science,
%         v. 277, p. 1957-1962, 26 Sept., 1997.
%
%   The source and reference for the IBCAO dataset are
%
%      http://www.ngdc.noaa.gov/mgg/bathymetry/arctic/grids/version3_0/
%
%      Jakobsson, M., L. A. Mayer, B. Coakley, J. A. Dowdeswell, S. Forbes,
%          B. Fridman, H. Hodnesdal, R. Noormets, R. Pedersen, M. Rebesco,
%          H.-W. Schenke, Y. Zarayskaya A, D. Accettella, A. Armstrong,
%          R. M. Anderson, P. Bienhoff, A. Camerlenghi, I. Church,
%          M. Edwards, J. V. Gardner, J. K. Hall, B. Hell, O. B. Hestvik,
%          Y. Kristoffersen, C. Marcussen, R. Mohammad, D. Mosher,
%          S. V. Nghiem, M. T. Pedrosa, P. G. Travaglini, and
%          P. Weatherall, The International Bathymetric Chart of the Arctic
%          Ocean (IBCAO) Version 3.0, Geophysical Research Letters,
%          doi: 10.1029/2012GL052219
%   __________________________________________________________________
%
%   License and Copyright
%
%   JTOPO.MAT is distributed with JDATA for RESEARCH AND NON-PROFIT USE
%   ONLY, in accordance with the copyright statement for the Smith and
%   Sandwell dataset.  For details, see TOPO_COPYRIGHT.
%
%   No copyright or policy is specified in the IBCAO documentation.
%   __________________________________________________________________
%
%   Dataset creation
%
%   For completeness, the m-file ABOUT_JTOPO also contains the processing
%   steps used in the creation of JTOPO.MAT.
%
%   If you wish to do this yourself, with JLAB on your search path,
%   'about_jtopo --create' will recreate the JTOPO.MAT dataset by reading
%   in and averaging the two topographic datasets. This will take a while.
%
%   For this to work you will need to have the JDATA folder containing
%   file 'topo_19.1.img' and 'ibcao.mat' downloaded and on your Matlab
%   search path.
%   __________________________________________________________________
%
%   See also READTOPO, TOPOPLOT, JDATA.
%
%   'about_jtopo --f' generates the sample figure shown above.
%
%   Usage: about_jtopo
%          about_jtopo --create
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2014--2020 J.M. Lilly --- type 'help jlab_license' for details

if nargin==0
    help about_jtopo
elseif nargin>0
    if strcmpi(varargin{1}, '--create')
        jtopo_create,return
    elseif strcmpi(varargin{1}, '--f')
        type makefigs_jtopo
        makefigs_jtopo;
        return
    end
end

function[]=jtopo_create

%/************************************************************************
%Main Smith and Sandwell portion
%delta=1/6;
delta=1/12;

lon=[-180-delta/2:delta:180-delta/2];
lat=[-80.66666-delta/2:delta:80.67+delta/2]';

topo=zeros(length(lat)-1,length(lon)-1);
for i=1:length(lon)-1
    disp(['Longitude band number ' num2str(i) ' of ' num2str(length(lon)-1) '.' ])
    [topo1,lat1,lon1]=readtopo([lon(i) lon(i)+delta -80.738 80.738]);
    topo1=vmean(topo1,2);  %Average across longitudes
    [mz,latbin,lonbin]=twodstats(lat1,lon(i)+0*lat1+delta/2,topo1,lat,[lon(i) lon(i)+delta]);%Average across latitudes
    topo(:,i)=mz';
end

lat=latbin;
lon=lon(1:end-1)+delta/2;

about='For more information, type ''about_jtopo''.';
matsave jtopo about lat lon topo
%matsave jtopo_onetwelfth about lat lon topo
%\************************************************************************

%/************************************************************************
%Adding Arctic dataset
lon=[-180-delta/2:delta:180-delta/2];
lat=[-80.66666-delta/2:delta:90]';

newtopo=zeros(length(lat)-1,length(lon)-1);
newtopo(1:size(jtopo.topo,1),:)=jtopo.topo;

load ibcao
ibcaotopo=zeros(size(newtopo));
[long,latg]=meshgrid(ibcao.lon,ibcao.lat);
for i=1:length(lon)-1
    disp(['Longitude band number ' num2str(i) ' of ' num2str(length(lon)-1) '.' ])
    index=find(ibcao.lon>lon(i) & ibcao.lon< lon(i)+delta);
    [mz,latbin,lonbin]=twodstats(latg(:,index),long(:,index),ibcao.topo(:,index),...
        lat(min(find(lat>64)):end),[lon(i) lon(i)+delta]);%Average across latitudes
    ibcaotopo(min(find(lat>64)):end,i)=mz';
end

%topodiff=jtopo.topo(min(find(lat>64)):end,:)-ibcaotopo(1:100,:);
%figure,plot(1000*vmean(abs(topodiff),2))
%sqrt(mean(squared(topodiff(:))))*1000 = 52 meters
lat=lat(1:end-1)+delta/2;
lon=lon(1:end-1)+delta/2;

%Linearly blend between the two datasets
index=min(find(lat>64)):find(lat<max(jtopo.lat),1,'last');
weight=ones(size(lat));
weight(index)=1-[0:length(index)-1]./(length(index)-1);
weight(index(end)+1:end)=0;

%figure,plot(lat,weight),vlines([64 80.6666666])
weight=vrep(weight,size(newtopo,2),2);
topo=newtopo.*weight+ibcaotopo.*(1-weight);
%\************************************************************************

matsave jtopo about lat lon topo
%matsave jtopo_onetwelfth about lat lon topo
disp('JTOPO creation complete.')

author: jonathanlilly

repo: jLab

save_path: github-repos/MATLAB/jonathanlilly-jLab


text:
function n = p04_n ( )

%*****************************************************************************80
%
%% P04_N returns the number of variables for problem 4.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 October 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, integer N.  If N is positive, N represents the
%    only legal value for N for this problem.  If N is
%    negative, the absolute value of N is the least legal
%    value of N, but other values are allowable.
%
  n = 2;

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [c,delta,cash] = BlackScholesCall(spot,K,r,vol,T)
% Black-Scholes price of a European call
% Inputs:
%   spot = spot price of underlying
%   K = strike of the call optioon
%   r = risk free rate as a fraction
%   vol = volatility of the underlying as a fraction
%   T = time to maturity in years
% Outputs:
%   c = price of European call(s)
%   delta = delta of the call(s)
%   cash = cash held in a replicating portfolio
%
d1 = (log(spot./K) + (r + vol.*vol/2).*T)./(vol.*sqrt(T));
d2 = d1 - vol.*sqrt(T);
delta = normcdf(d1);
cash =  -K.*exp(-r.*T).*normcdf(d2);
c = spot.*delta + cash;

author: Sable

repo: mcbench-benchmarks


text:
%ESTIMATEAFFINE2D  Computes an optimal affine transformation between two 2D point sets
%
%     H = cv.estimateAffine2D(from, to)
%     [H, inliers] = cv.estimateAffine2D(...)
%     [...] = cv.estimateAffine2D(..., 'OptionName', optionValue, ...)
%
% ## Input
% * __from__ First input 2D point set containing `(X,Y)`. Cell array of
%   2-element vectors `{[x,y],...}` or Nx2/Nx1x2/1xNx2 numeric array.
% * __to__ Second input 2D point set containing `(x,y)`. Same size and type as
%   `from`.
%
% ## Output
% * __H__ Output 2D affine transformation matrix 2x3 or empty matrix if
%   transformation could not be estimated. The returned matrix has the
%   following form `[a11 a12 b1; a21 a22 b2]`.
% * __inliers__ Output vector of same length as number of points, indicating
%   which points are inliers (1-inlier, 0-outlier).
%
% ## Options
% * __Method__ Robust method used to compute transformation. RANSAC is the
%   default method. The following methods are possible:
%   * __Ransac__ RANSAC-based robust method.
%   * __LMedS__ Least-Median of squares robust method
% * __RansacThreshold__ Maximum reprojection error in the RANSAC algorithm to
%   consider a point as an inlier. Applies only to RANSAC. default 3.0.
% * __MaxIters__ The maximum number of robust method iterations. default 2000
% * __Confidence__ Confidence level, between 0 and 1, for the estimated
%   transformation. Anything between 0.95 and 0.99 is usually good enough.
%   Values too close to 1 can slow down the estimation significantly. Values
%   lower than 0.8-0.9 can result in an incorrectly estimated transformation.
%   default 0.99.
% * __RefineIters__ Maximum number of iterations of refining algorithm
%   (Levenberg-Marquardt). Passing 0 will disable refining, so the output
%   matrix will be output of robust method. default 10
%
% It computes:
%
%     [x; y] = [a11 a12; a21 a22] * [X; Y] + [b1; b2]
%
% The function estimates an optimal 2D affine transformation between two 2D
% point sets using the selected robust algorithm.
%
% The computed transformation is then refined further (using only inliers)
% with the Levenberg-Marquardt method to reduce the re-projection error even
% more.
%
% Note: The RANSAC method can handle practically any ratio of outliers but
% needs a threshold to distinguish inliers from outliers. The method LMedS
% does not need any threshold but it works correctly only when there are more
% than 50% of inliers.
%
% See also: cv.estimateAffinePartial2D, cv.getAffineTransform
%

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).
% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)
% Copyright: ETH Zurich, 2014
% Author: Romano Cicchetti

function [ houses ] = findHouseholds(appliance, dataset)

    % returns all household for which the plug-level data of the specified
    % appliance exists

     appliance_house_matrix = getApplianceHouseMatrix(dataset);
     houses = find(appliance_house_matrix(appliance,:)>0);

end

author: beckel

repo: nilm-eval

save_path: github-repos/MATLAB/beckel-nilm-eval


%% set parameters
%folderpath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/ICVL/Training/Depth/';
%filepath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/ICVL/Training/labels.txt';
%frameNum = 331006;

folderpath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/ICVL/Testing/Depth/';
filepath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/ICVL/Testing/test_seq_1.txt';
frameNum = 702;

%folderpath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/ICVL/Testing/Depth/';
%filepath = '/home/gyeongsikmoon/workspace/Data/Hand_pose_estimation/ICVL/Testing/test_seq_2.txt';
%frameNum = 894;

fp = fopen(filepath);
fid = 1;

tline = fgetl(fp);
while fid <= frameNum

    splitted = strsplit(tline);
    img_name = splitted{1};

    if exist(strcat(folderpath,img_name), 'file')
        img = imread(strcat(folderpath,img_name));

        fp_save = fopen(strcat(folderpath,img_name(1:size(img_name,2)-3),'bin'),'w');
        fwrite(fp_save,permute(img,[2,1,3]),'float');
        fclose(fp_save);

        %delete(strcat(folderpath,img_name));
    end

    tline = fgetl(fp);
    fid = fid + 1;
end

fclose(fp);


text:
function VisualServoTest(testCase)
      tests = functiontests(localfunctions);
end

        function testFunctions
            %BundleAdjust.testFunctions Test generated functions
            %
            % BundleAdjust.testFunctions will run a batch of unit tests on the
            % functions generated by BundleAdjust.generateFunctions.
            %
            % See also BundleAdjust.generateFunctions.

            cam = CentralCamera('default' );

            t = [0 0 0]';
            R = rpy2tr(0.3, 0.3, 0.4);
            q = UnitQuaternion(R).double

            T =  transl(t) * R;

            P = [1 2 5]';
            [p0,vis] = cam.project(P, 'Tcam', T);

            d = 0.00001;
            dd = d*eye(3);

            [UVS,JAS,JBS] = cameraModel(t(1), t(2), t(3), q(2), q(3), q(4), ...
                P(1), P(2), P(3), ...
                cam.f, cam.rho(1), cam.rho(2), cam.u0, cam.v0);

            %% projection
            fprintf('-- test projection function\n');
            fprintf(' toolbox\n');
            p0
            fprintf(' symbolic\n');
            UVS

            assert( max(abs(UVS-p0)) < 0.1, 'Error with projection equation')

            %% jacobian B
            fprintf('-- Jacobian B\n');
            fprintf(' toolbox\n');
            p1 = cam.project( bsxfun(@plus, P, dd), 'Tcam', T);

            JB = bsxfun(@minus, p1, p0) / d

            % symbolically derived result
            fprintf(' symbolic\n');
            JBS
            assert( max(max(abs(JBS-JB))) < 0.1, 'Error with Jacobian B equation')

            %% jacobian A

            R = UnitQuaternion(q).R;
            T =  rt2tr(R, t);

            JA = [];
            for i=1:3
                T =  rt2tr(R, t+dd(:,i));
                p = cam.project(P, 'Tcam', T);
                JA = [JA (p-p0)/d];
            end

            for i=1:3
                qq = q(2:4);
                qq(i) = qq(i) + d;
                qs = sqrt(1-sum(qq.^2));
                RR = UnitQuaternion([qs qq]).R;
                T =  rt2tr(RR, t);
                p = cam.project(P, 'Tcam', T);
                JA = [JA (p-p0)/d];
            end

            fprintf('-- Jacobian A\n');
            fprintf(' toolbox\n');
            JA

            % symbolically derived result
            fprintf(' symbolic\n');
            JAS
            assert( max(max(abs(JAS-JA))) < 0.1, 'Error with Jacobian A equation')

function camera_test(testCase)
    cam = CentralCamera('default');
    s = cam.char();
    cam

    P = mkgrid(3, 1.0, transl(0,0,2));

    uv = cam.project(P)
    cam.plot(P);
    uv = cam.plot(P);

    fov = cam.fov();
    K = cam.K();
    C = cam.C();

    about P
    ray = cam.ray(uv);

    cam.hold()
    cam.plot(P);
    cam.ishold();
    cam.clf();
    cam.plot([200 300 1]');
    cam.homline([200 200 1]');
    cam.plot_camera();
    %cam.plot_epiline();

    J = cam.visjac_p(P, 1);
    J = cam.visjac_p_polar(P, 1);
    %J = cam.visjac_l(P);
    %J = cam.visjac_e(P);
    cam.flowfield([1 0 0 0 0 0]');
end

function epipolar_test(testCase)
    return
    F = fmatrix(uv1, uv2)
    %[F,r] = fmatrix(uv1, uv2)

    epidist(F, uv1, uv2)

    [F,r] = fmatrix([uv1; uv2])

    clearfigs
    cam1 = camera('camera 1');

    P = mkgrid(3, 1.0, transl(0,0,2));
    P

    T = transl(0.5,-0.2,0)*trotx(-0.2)*trotz(0.3);
    T = transl(-0.3, 0.4, -0.8)*trotz(0.5)*troty(.3)*trotx(.3);
    cam2 = camera(T, 'camera 2');

    uv1 = cam1.plot(P, 'o')
    uv2 = cam2.plot(P, 'o')

    H = homography(uv1, uv2)

    homtrans(H, uv1)-uv2

    cam2.hold
    plot2(homtrans(H, uv1)', '+')
    cam2.hold(0)
    cam2.clf

    homtrans(H, uv1)
    homtrans(inv(H), uv2)

    P2 = pinv(cam1.C) * [
        312 512 712
        912 912 912
          1   1   1];

    P2
    cam1.project(P2(1:3,:))
    pause
    % columns at (X,Y,Z) and any multiple will project to the same point
    % set range of points to be 1, 3, 4
    P2 = P2(1:3,:) * diag([1 3 4])
    cam1.project(P2(1:3,:))
    P = [P P2]
    cam1.plot(P, 'o')
    cam2.plot(P, 'o')

    uv1 = cam1.project(P)
    uv2 = cam2.project(P)

    homtrans(H, uv1)-uv2

    H = ransac(@homography, [uv1 uv2], .01)
end
%function sphcamera_test(testCase)
%function panocamera_test(testCase)

author: petercorke

repo: machinevision-toolbox-matlab


text:
function [varargout] = rdir(rootdir,varargin)
% RDIR - Recursive directory listing
%
%  d = rdir(ROOT)
%  d = rdir(ROOT, TEST)
%  d = rdir(ROOT, TEST, RMPATH)
%  d = rdir(ROOT, TEST, 1)
%  d = rdir(ROOT, '', ...)
%  rdir(...)
%
%
% *Inputs*
%
% * ROOT
%
% rdir(ROOT) lists the specified files.
% ROOT can be a pathname, filename, or can include both. One can use
% absolute and relative pathnames and wildcards (*). Wildcard can be placed
% anywhere and used many times like 'path*\*.m'
%
% One can also use a double wildcard (**) to match multiple directory
% levels. For example ROOT = 'path\**\*.m' will match all ".m" files in
% "path" and all subdirectories of "path".
%
% NOTE : ".svn" directories created by SubVersion (SVN) are excluded from
% the recursive listing.
%
% * TEST
%
% Optional test that can be performed on the returned files.
%
% TEST is a string indicating expression to be evaluated on selected field
% of rdir output.
% All fields (ie name, date, bytes, isdir and datenum) can be used.
%
% Tests are strings similar to what one would use in a "if" statement e.g.
%  'bytes>1024 & datenum>now-7'
% One can also use function like "regexp" or "strfind" with string fields
% like "name" and "date" e.g 'regexp(name, 'expr')'.
%
% * RMPATH
%
% Optional path to remove from beginning of "name" field in returned
% output. Specified path must be common to all items found.
%
% If RMPATH = 1 or true, path to remove is part of ROOT before the first
% wildcard.
%
%
% *Outputs*
%
% d is a structure with the same fields as Matlab DIR output.
%
% The "name" field includes the relative path as well as the name to the
% file that was found. Path can be shorten or ommited when using 3rd
% argument RMPATH.
%
% If not output variable is specified then the output is sent to the
% screen.
%
%
% *Versions*
%
% * 1.0 - 2009, Gus Brown
% * 2.0 - 26/05/2011 Thomas Vanaret
%         No longer exclude all directories from a simple search (no *);
%         Fixing bug on returned path;
%         Exclude ".svn" directories;
%         Extended test possibilies;
%         Subfunctions created;
% * 2.1 - 14/07/2011 Thomas Vanaret
%         New argument allowing to remove common path from name;
%         Comments review;
% * 2.2 - 20/12/2011 Thomas Vanaret
%         Fixing bug on display with 0b files;
%         Specific display when no file match filter;
%
%
%
% *Examples*
%
%   D = rdir('*.m');
%     for ii=1:length(D), disp(D(ii).name); end;
%
%   % to find all files in the current directory and sub directories
%   D = rdir('**\*')
%
%   % If no output is specified then the files are sent to
%   % the screen.
%   rdir('c:\program files\windows *\*.exe');
%   rdir('c:\program files\windows *\**\*.dll');
%
%   % Using the test function to find files modified today
%   rdir('c:\win*\*','datenum>floor(now)');
%   % Using the test function to find files of a certain size
%   rdir('c:\program files\win*\*.exe','bytes>1024 & bytes<1048576');
%   % Using the test function to find files modified in 2011
%   rdir('c:\win*\*','strfind(date, ''2011'')');
%
%   % Using the 3rd input to shorten output name
%   rdir([matlabroot, '\*.txt'], '', 'C:\Program Files\')
%   % Using the 3rd input to shorten output name
%   rdir([matlabroot, '\*.txt'], '', 1)
%
%
% See also DIR
%

%--------------------------------------------------------------------------
%% Input validation

% use the current directory if nothing is specified
if ~exist('rootdir','var'),
  rootdir = '*';
end

prepath = '';       % the path before the wild card
wildpath = '';      % the path wild card
postpath = rootdir; % the path after the wild card
I = find(rootdir==filesep,1,'last');

% Directory separator for current platform
if filesep == '\'
  % On PC, filesep is '\'
  anti_filesep = '/';
else
  % On UNIX system, filesep is '/'
  anti_filesep = '\';
end

if isempty(I) && ~isempty(strfind(rootdir, anti_filesep))
  error([mfilename, ':FileSep'],...
    'Use correct directory separator "%s".', filesep)
end

%--------------------------------------------------------------------------
%% Split rootdir
% split the file path around the wild card specifiers

if ~isempty(I),
  prepath = rootdir(1:I);
  postpath = rootdir(I+1:end);
  I = find(prepath=='*',1,'first');
  if ~isempty(I),
    postpath = [prepath(I:end) postpath];
    prepath = prepath(1:I-1);
    I = find(prepath==filesep,1,'last');
    if ~isempty(I),
      wildpath = prepath(I+1:end);
      prepath = prepath(1:I);
    end;
    I = find(postpath==filesep,1,'first');
    if ~isempty(I),
      wildpath = [wildpath postpath(1:I-1)];
      postpath = postpath(I:end);
    end;
  end;
end;

% disp([' "' prepath '" ~ "' wildpath '" ~ "' postpath '" ']);

%--------------------------------------------------------------------------
%% Recursive listing

if isempty(wildpath)
  % If no directory wildcards then just get file and directoties list

  D = dir([prepath postpath]);

  % Exclude ".", ".." and ".svn" directories from the list
  excl = isdotdir(D) | issvndir(D);
  D(excl) = [];

  if isdir([prepath postpath]);
    fullpath = [prepath postpath];
  else
    fullpath = prepath;
  end

  % Place directories on the top of the list
  is_dir = [D.isdir]';
  D = [D(is_dir); D(~is_dir)];

  % Add path before name
  for ii = 1:length(D)
    D(ii).name = fullfile(fullpath, D(ii).name);
  end

  % disp(sprintf('Scanning "%s"   %g files found',[prepath postpath],length(D)));

elseif strcmp(wildpath,'**')
  % A double wildcards directory means recurs down into sub directories

  % first look for files in the current directory (remove extra filesep)
  D = rdir([prepath postpath(2:end)]);

  % then look for sub directories
  tmp = dir([prepath '*']);

  % Exclude ".", "..", ".svn" directories and files from the list
  excl = isdotdir(tmp) | issvndir(tmp) | ~([tmp.isdir]');
  tmp(excl) = [];

  % Process each sub directory found
  Dt = dir('');
  for ii = 1:length(tmp),
    Dt = [Dt; rdir([prepath tmp(ii).name filesep wildpath postpath])]; %#ok<AGROW>
  end
  D = [D; Dt];

else
  % Process directory wild card looking for sub directories that match

  tmp = dir([prepath wildpath]);

  % Exclude ".", "..", ".svn" directories and files from the list
  excl = isdotdir(tmp) | issvndir(tmp) | ~([tmp.isdir]');
  tmp(excl) = [];

  if ~isdir(prepath)
    % Fix case like rdir('path*\...') where prepath is not a directoty
    % name.
    prepath = '';
  end

  % Process each directory found
  D = dir('');
  for ii = 1:length(tmp),
    D = [D; rdir([prepath tmp(ii).name postpath])]; %#ok<AGROW>
  end

end

%--------------------------------------------------------------------------
%% Apply filter

nb_before_filt = length(D);
if (nargin>=2 && ~isempty(varargin{1})),
  try
    test_tf = evaluate(D, varargin{1});

    D = D(test_tf);

  catch
    warning([mfilename, ':InvalidTest'],...
      'Invalid TEST "%s" : %s', varargin{1}, lasterr);
  end
end

%--------------------------------------------------------------------------
%% Remove path

common_path = '';
if (nargin>=3 && ~isempty(varargin{2})),

  arg2 = varargin{2};
  if ischar(arg2)
    common_path = arg2;
  elseif (isnumeric(arg2) || islogical(arg2)) && arg2
    common_path = prepath;
  end

  rm_path = regexptranslate('escape', common_path);

  % Check that path is common to all
  start = regexp({D.name}', ['^', rm_path]);

  % Convert to a logical.
  is_common = not( cellfun(@isempty, start) );

  if all(is_common)
    for k = 1:length(D)
      D(k).name = regexprep(D(k).name, ['^', rm_path], '');
    end

  else
    common_path = '';
  end

end

%--------------------------------------------------------------------------
%% Display listing if no output variables are specified

if nargout==0,
  if isempty(D)
    if nb_before_filt == 0
      fprintf('%s not found.\n', rootdir)
    else
      fprintf('No item matching filter.\n')
    end
  else

    if ~isempty(common_path)
     fprintf('All in : %s\n', common_path)
    end

    pp = {'' 'k' 'M' 'G' 'T'};
    for ii = 1:length(D)
      if D(ii).isdir
        % Directory item : display name
        disp(sprintf(' %29s %-64s','',D(ii).name));
      else
        % File item : display size, modification date and name
        sz = D(ii).bytes;
        if sz > 0
          ss = min(4,floor(log2(sz)/10));
        else
          ss = 0;
        end
        disp(sprintf('%4.0f %1sb  %20s  %-64s ',...
          sz/1024^ss, pp{ss+1}, datestr(D(ii).datenum, 0), D(ii).name));
      end
    end
  end
else
  % send list out
  varargout{1} = D;
end;

%---------------------------- end of main function ------------------------

%% ------------------------------------------------------------------------
function tf = issvndir(d)
% True for ".svn" directories.
% d is a structure returned by "dir"
%

is_dir = [d.isdir]';

is_svn = strcmp({d.name}, '.svn')';
%is_svn = false; % uncomment to disable ".svn" filtering

tf = (is_dir & is_svn);

%---------------------------- end of subfunction --------------------------

%% ------------------------------------------------------------------------
function tf = isdotdir(d)
% True for "." and ".." directories.
% d is a structure returned by "dir"
%

is_dir = [d.isdir]';

is_dot = strcmp({d.name}, '.')';
is_dotdot = strcmp({d.name}, '..')';

tf = (is_dir & (is_dot | is_dotdot) );

%---------------------------- end of subfunction --------------------------

%% ------------------------------------------------------------------------
function tf = evaluate(d, expr)
% True for item where evaluated expression is correct or return a non empty
% cell.
% d is a structure returned by "dir"
%

% Get fields that can be used
name = {d.name}'; %#ok<NASGU>
date = {d.date}'; %#ok<NASGU>
datenum = [d.datenum]'; %#ok<NASGU>
bytes = [d.bytes]'; %#ok<NASGU>
isdir = [d.isdir]'; %#ok<NASGU>

tf = eval(expr);

% Convert cell outputs returned by "strfind" or "regexp" filters to a
% logical.
if iscell(tf)
  tf = not( cellfun(@isempty, tf) );
end

%---------------------------- end of subfunction --------------------------

%---------------------------- END OF FUNCTION -----------------------------

repo: REST


text:
function ttf = friedman_test(n_problem, r, n)
%FRIEDMAN regression

fun = @(i, j, x) x^(j-1);

if n_problem == 1
    %Friedman 1
    d = 10;
    N = 20000;
    x = rand(d,N);
    y = 10*sin(pi*x(1,:).*x(2,:)) + 20*(x(3,:) - 0.5*ones(1,N)).^2 + 10*x(4,:) + 5*x(5,:);

    tt_rank = [1 ; r*ones(d-1,1) ; 1];
    n_basis = n*ones(d,1);
    basis_ps = cumsum([1 ; n_basis*N]);
    basis_cr = zeros(basis_ps(d+1) - basis_ps(1), 1);
    for dim = 1: d
        t = zeros(n, N);
        for i = 1: n
            t(i,:) = x(dim,:).^(i-1);
        end
        basis_cr(basis_ps(dim):basis_ps(dim+1)-1) = reshape(t, [n*N 1]);
    end
elseif n_problem == 2
    %Friedman 2
    d = 4;
    N = 20000;
    x = rand(d,N);
    x1 = x(1,:)*100;
    x2 = x(2,:)*520*pi + 40*pi*ones(1,N);
    x3 = x(3,:);
    x4 = x(4,:)*10 + ones(1,N);
    y = sqrt(x1.^2 + (x2.*x3 - 1./(x2.*x4)).^2);

    tt_rank = [1 ; r*ones(d-1,1) ; 1];
    n_basis = n*ones(d,1);
    basis_ps = cumsum([1 ; n_basis*N]);
    basis_cr = zeros(basis_ps(d+1) - basis_ps(1), 1);
    for dim = 1: d
        t = zeros(n, N);
        for i = 1: n
            t(i,:) = x(dim,:).^(i-1);
        end
        basis_cr(basis_ps(dim):basis_ps(dim+1)-1) = reshape(t, [n*N 1]);
    end
else
    %Friedman 3
    d = 4;
    N = 20000;
    x = rand(d,N);
    x1 = x(1,:)*100;
    x2 = x(2,:)*520*pi + 40*pi*ones(1,N);
    x3 = x(3,:);
    x4 = x(4,:)*10 + ones(1,N);
    y = atan((x2.*x3 - 1./(x2.*x4))./x1);

    tt_rank = [1 ; r*ones(d-1,1) ; 1];
    n_basis = n*ones(d,1);
    basis_ps = cumsum([1 ; n_basis*N]);
    basis_cr = zeros(basis_ps(d+1) - basis_ps(1), 1);
    for dim = 1: d
        t = zeros(n, N);
        for i = 1: n
            t(i,:) = x(dim,:).^(i-1);
        end
        basis_cr(basis_ps(dim):basis_ps(dim+1)-1) = reshape(t, [n*N 1]);
    end
end

coeff = reg_als(basis_cr, y, tt_rank, n_basis);
ttf = tt_function(fun, coeff);

end

author: oseledets

repo: TT-Toolbox


text:
%--- help for inputParser/parse ---
%
% parse(PARSEOBJ,ARGLIST) parses user inputs based on the input scheme.
%    PARSE matches arguments in the comma separated list ARGLIST with
%    input scheme defined by PARSEOBJ.  The inputParser properties Results,
%    UsingDefaults, and Unmatched are set by calling the PARSE methods.  If
%    the parse fails for any reason, the PARSE method throws an error.
%
%    See also inputParser, inputParser/addOptional, inputParser/addRequired,
%    inputParser/addParameter, inputParser.Results, inputParser.KeepUnmatched, inputParser.UsingDefaults
%
%    Reference page in Doc Center
%       doc inputParser/parse
%
%

author: jmaih


text:
function string = user_string(string_name, string)
%USER_STRING  Get/set a user specific string
%
% Examples:
%   string  = user_string(string_name)
%   isSaved = user_string(string_name, new_string)
%
% Function to get and set a string in a system or user specific file. This
% enables, for example, system specific paths to binaries to be saved.
%
% The specified string will be saved in a file named <string_name>.txt,
% either in a subfolder named .ignore under this file's folder, or in the
% user's prefdir folder (in case this file's folder is non-writable).
%
% IN:
%   string_name - String containing the name of the string required, which
%                 sets the filename storing the string: <string_name>.txt
%   new_string  - The new string to be saved in the <string_name>.txt file
%
% OUT:
%   string  - The currently saved string. Default: ''
%   isSaved - Boolean indicating whether the save was succesful

% Copyright (C) Oliver Woodford 2011-2014, Yair Altman 2015-

% This method of saving paths avoids changing .m files which might be in a
% version control system. Instead it saves the user dependent paths in
% separate files with a .txt extension, which need not be checked in to
% the version control system. Thank you to Jonas Dorn for suggesting this
% approach.

% 10/01/2013 - Access files in text, not binary mode, as latter can cause
%              errors. Thanks to Christian for pointing this out.
% 29/05/2015 - Save file in prefdir if current folder is non-writable (issue #74)
% 09/01/2018 - Fix issue #232: if the string looks like a file/folder path, ensure it actually exists

    if ~ischar(string_name)
        error('string_name must be a string.');
    end
    % Create the full filename
    fname = [string_name '.txt'];
    dname = fullfile(fileparts(mfilename('fullpath')), '.ignore');
    file_name = fullfile(dname, fname);
    if nargin > 1
        % Set string
        if ~ischar(string)
            error('new_string must be a string.');
        end
        % Make sure the save directory exists
        %dname = fileparts(file_name);
        if ~exist(dname, 'dir')
            % Create the directory
            try
                if ~mkdir(dname)
                    string = false;
                    return
                end
            catch
                string = false;
                return
            end
            % Make it hidden
            try
                fileattrib(dname, '+h');
            catch
            end
        end
        % Write the file
        fid = fopen(file_name, 'wt');
        if fid == -1
            % file cannot be created/updated - use prefdir if file does not already exist
            % (if file exists but is simply not writable, don't create a duplicate in prefdir)
            if ~exist(file_name,'file')
                file_name = fullfile(prefdir, fname);
                fid = fopen(file_name, 'wt');
            end
            if fid == -1
                string = false;
                return;
            end
        end
        try
            fprintf(fid, '%s', string);
        catch
            fclose(fid);
            string = false;
            return
        end
        fclose(fid);
        string = true;
    else
        % Get string
        fid = fopen(file_name, 'rt');
        if fid == -1
            % file cannot be read, try to read the file in prefdir
            file_name = fullfile(prefdir, fname);
            fid = fopen(file_name, 'rt');
            if fid == -1
                string = '';
                return
            end
        end
        string = fgetl(fid);
        fclose(fid);

        % Fix issue #232: if the string looks like a file/folder path, ensure it actually exists
        if ~isempty(string) && any(string=='\' | string=='/') && ~exist(string) %#ok<EXIST>
            string = '';
        end
    end
end

author: goGPS-Project


text:
% Function used in production of clique trees
%
% Copyright (C) Daphne Koller, Stanford Univerity, 2012

function [newF C E] = EliminateVar(F, C, E, Z)

useFactors = [];
scope = [];

for i=1:length(F)
    if any(F(i).var == Z)
        useFactors = [useFactors i];
        scope = union(scope, F(i).var);
    end
end

% update edge map
% These represent the induced edges for the VE graph.
for i=1:length(scope)
    for j=1:length(scope)

        if i~=j
            E(scope(i),scope(j)) = 1;
            E(scope(j),scope(i)) = 1;
        end
    end
end

E(Z,:) = 0;
E(:,Z) = 0;

nonUseFactors = setdiff(1:length(F),[useFactors]);

for i=1:length(nonUseFactors)
    newF(i) = F(nonUseFactors(i));
    newmap(nonUseFactors(i)) = i;
end

newFactor = struct('var', [], 'card', [], 'val', []);
for i=1:length(useFactors)
    newFactor = FactorProduct(newFactor,F(useFactors(i)));
end

newFactor = FactorMarginalization(newFactor,Z);
newF(length(nonUseFactors)+1) = newFactor;

newC = length(C.nodes)+1;
C.nodes{newC} = scope;
C.factorInds(newC) = length(nonUseFactors)+1;
for i=1:newC-1
    if ismember(C.factorInds(i), useFactors)
        C.edges(i,newC) = 1;
        C.edges(newC,i) = 1;
        C.factorInds(i) = 0;
    else
        if C.factorInds(i) ~= 0
            C.factorInds(i) = newmap(C.factorInds(i));
        end
    end
end

author: anhncs

repo: Probabilistic-Graphical-Models


text:
function newMsh = meshSmooth(msh,QueryFlag)
%Smooth a VTK mesh and update if there is a mesh in a current window
%
%   newMsh = meshSmooth(msh,QueryFlag)
%
% The msh can either be a file name to a white matter classification
% file or one of our VTK mesh data structures (see meshGet, meshSet).
%
% Several msh fields are checked to determine the smoothing
% parameters.  These are
%   smooth_iterations  (default 35)
%   smooth_relaxation  (default 0.15)
%   smooth_sinc_method (default 1)
%
% If you set  QueryFlag = 1, you will be asked about these parameter
% values.
%
% The relaxation factor only changes the smoothness by increasing the
% current value. If want you choose a value that is smaller than the
% current mesh smoothing, you should really revert to the original mesh and
% then smooth it.  Yes, we know, we could do that for you here.
%
% The smooth iterations specifies how much you want to process in order to
% converge.
%
% Example:
%  fName ='X:\anatomy\nakadomari\left\20050901_fixV1\left.Class';
%  msh = meshBuild(fName);
%
%  Not very smooth, default = 35
%  msh = meshSet(msh,'smooth_iterations',1);
%  msh = meshSmooth(msh);
%  msh = meshVisualize(msh);
%
% Author GB
% ras 01/07: if there's a mesh window open, auto-update the vertices
% rfb 08/10: populate initial vertices within meshSmooth
% al 04/11: removed a line in the code that repopulated the initialVertices

if notDefined('msh'), error('This function needs a mesh input'); end
if notDefined('QueryFlag'), QueryFlag = 0; end
% If the input is a string, we build the mesh.
if ischar(msh), msh = meshBuild(msh); end

% If the parameters are set, we don't query the user.  If they are not set,
% we will pop up a window and check the parameters.
%
if isempty(meshGet(msh,'smooth_iterations')), msh = meshSet(msh,'smooth_iterations',30);  end
if isempty(meshGet(msh,'smooth_relaxation')), msh = meshSet(msh,'smooth_relaxation',0.5);  end
if isempty(meshGet(msh,'smooth_sinc_method')), msh = meshSet(msh,'smooth_sinc_method',0);  end
if isempty(meshGet(msh,'mod_depth')), msh = meshSet(msh,'mod_depth',0.15);  end
if QueryFlag
    prompt = {'Smooth with Windowed Sinc (0|1):',...
        'Smooth Iterations:',...
        'Smooth Relaxation (0-2):'};
    defAns = {num2str(meshGet(msh,'smooth_sinc_method')),...
        num2str(meshGet(msh,'smooth_iterations')),...
        num2str(meshGet(msh,'smooth_relaxation'))};
    resp = inputdlg(prompt, 'Set Mesh Build Parameters', 1, defAns);
    if(~isempty(resp))
        msh = meshSet(msh,'smooth_sinc_method',str2num(resp{1}));
        msh = meshSet(msh,'smooth_iterations',str2num(resp{2}));
        msh = meshSet(msh,'smooth_relaxation',str2num(resp{3}));
    else
        newMsh = msh;
        return
    end
end
fprintf('[%s]: Smoothing mesh...', mfilename)
smoothedMsh = smooth_mesh(msh);
fprintf('done. \n');
newMsh = msh;

newMsh = meshSet(newMsh,'vertices',meshGet(smoothedMsh,'vertices'));
newMsh = meshSet(newMsh,'colors',meshGet(smoothedMsh,'colors'));
newMsh = meshSet(newMsh,'normals',meshGet(smoothedMsh,'normals'));
newMsh = meshSet(newMsh,'triangles',meshGet(smoothedMsh,'triangles'));

% update display if it's open - which we detect by the presence of an id
if newMsh.id > 0
    mrmSet(newMsh, 'vertices');
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [outputEEG, commandHistory] = pop_erplabSelectChannelInterpolation( EEG, varargin )
%pop_erplabSelectChannelInterpolation In EEG data, replace specific channels through interpolation with the option to ignore specific channels
%
% FORMAT
%
%    EEG = pop_erplabSelectChannelInterpolation(inEEG, replaceChannels, ignoreChannels)
%
% INPUT:
%
%    EEG                EEGLAB EEG dataset
%    replaceChannels       list of event codes to shift
%    ignoreChannels        time in sec. If ignoreChannels is positive, the EEG event code time-values are shifted to the right (e.g. increasing delay).
%                       - If ignoreChannels is negative, the event code time-values are shifted to the left (e.g decreasing delay).
%                       - If ignoreChannels is 0, the EEG's time values are not shifted.
%    interpolationMethod         Type of interpolationMethod to use
%                       - 'nearest'    (default) Round to the nearest integer
%                       - 'floor'      Round to nearest ingtowards positive infinity
%                       - 'ceiling'    Round to nearest integer towards negative infinity
%
% OPTIONAL INPUT:
%
%    displayFeedback  Type of feedback to display at Command window
%                        - 'summary'   (default) Print summarized info to Command Window
%                        - 'detailed'  Print event table with latency differences
%                        - 'both'      Print both summarized & detailed info
%
% OUTPUT:
%
%    EEG               EEGLAB EEG dataset with the specified channels replaced through interpolation
%
%
% EXAMPLE:
%
%     replaceChannels       = {'22', '19'};
%     ignoreChannels        = 0.015;
%     interpolationMethod   = 'floor';
%     outputEEG             = pop_erplabSelectChannelInterpolation(EEG, replaceChannels, ignoreChannels, interpolationMethod);
%
%
% Requirements:
%   - EEG_CHECKSET (eeglab function)
%
% See also eegignoreChannels.m erpignoreChannels.m
%
%
% *** This function is part of ERPLAB Toolbox ***
% Author: Jason Arita
% Center for Mind and Brain
% University of California, Davis,
% Davis, CA
% 2009

%% Return help if given no input
if nargin < 1
    help pop_erplabSelectChannelInterpolation
    return
end

%% Error Checks

% Error check: Input EEG structure
if isobject(EEG) % eegobj
    whenEEGisanObject % calls a script for showing an error window
    return
end

%% Call GUI
% When only 1 input is given the GUI is then called
if nargin==1

     % Input EEG error check
    serror = erplab_eegscanner(EEG, 'pop_erplabSelectChannelInterpolation',...
        0, ... % 0 = do not accept md;
        0, ... % 0 = do not accept empty dataset;
        0, ... % 0 = do not accept epoched EEG;
        0, ... % 0 = do not accept if no event codes
        2);    % 2 = do not care if there exists an ERPLAB EVENTLIST struct

    % Quit if there is an error with the input EEG
    if serror; return; end

    % Get previous input parameters
    def  = erpworkingmemory('pop_erplabSelectChannelInterpolation');
    if isempty(def); def = {}; end

    % Call GUI function
    inputstrMat = gui_erplab_selectiveEegInterpolation(def);  % GUI

    % Exit when CANCEL button is pressed
    if isempty(inputstrMat) && ~strcmp(inputstrMat,'')
        commandHistory = 'User selected cancel';
        return;
    end

    replaceChannels          = inputstrMat{1};
    ignoreChannels           = inputstrMat{2};
    interpolationMethod      = inputstrMat{3};
%     displayFeedback          = inputstrMat{4};
    %

    % Save the GUI inputs to memory
    erpworkingmemory('pop_erplabSelectChannelInterpolation', ...
        {replaceChannels,    ...
        ignoreChannels,      ...
        interpolationMethod});
%         displayFeedback });

    % New output EEG set name
    if length(EEG)==1
        EEG.setname = [EEG.setname '_channelInterpolated'];
    end

    [outputEEG, commandHistory] = pop_erplabSelectChannelInterpolation(EEG, ...
        'replaceChannels'    , replaceChannels,     ...
        'ignoreChannels'     , ignoreChannels,      ...
        'interpolationMethod', interpolationMethod, ...
        'History'            , 'gui');

    return;

end

%% Parse named input parameters (vs positional input parameters)

inputParameters               = inputParser;
inputParameters.FunctionName  = mfilename;
inputParameters.CaseSensitive = false;

% Required parameters
inputParameters.addRequired('EEG');
% Optional named parameters (vs Positional Parameters)
inputParameters.addParameter('replaceChannels'     , []);
inputParameters.addParameter('ignoreChannels'      , []);
inputParameters.addParameter('interpolationMethod' , 'spherical');
inputParameters.addParameter('DisplayFeedback'     , 'summary'); % old parameter for BoundaryString
inputParameters.addParameter('History'             , 'script', @ischar); % history from scripting

inputParameters.parse(EEG, varargin{:});

%% Execute corresponding function
replaceChannels     = inputParameters.Results.replaceChannels;
ignoreChannels      = inputParameters.Results.ignoreChannels;
interpolationMethod = inputParameters.Results.interpolationMethod;

outputEEG = erplab_selectiveEegInterpolation(EEG ...
    , replaceChannels       ...
    , ignoreChannels        ...
    , interpolationMethod   );

%% Generate equivalent history command
%

commandHistory  = ''; %#ok<*NASGU>
skipfields      = {'EEG', 'DisplayFeedback', 'History'};
fn              = fieldnames(inputParameters.Results);
commandHistory         = sprintf( '%s  = pop_erplabSelectChannelInterpolation( %s ', inputname(1), inputname(1));
for q=1:length(fn)
    fn2com = fn{q}; % get fieldname
    if ~ismember(fn2com, skipfields)
        fn2res = inputParameters.Results.(fn2com); % get content of current field
        if ~isempty(fn2res)
            if iscell(fn2res)
                commandHistory = sprintf( '%s, ''%s'', {', commandHistory, fn2com);
                for c=1:length(fn2res)
                    getcont = fn2res{c};
                    if ischar(getcont)
                        fnformat = '''%s''';
                    else
                        fnformat = '%s';
                        getcont = num2str(getcont);
                    end
                    commandHistory = sprintf( [ '%s ' fnformat], commandHistory, getcont);
                end
                commandHistory = sprintf( '%s }', commandHistory);
            else
                if ischar(fn2res)
                    if ~strcmpi(fn2res,'off')
                        commandHistory = sprintf( '%s, ''%s'', ''%s''', commandHistory, fn2com, fn2res);
                    end
                else
                    %if iscell(fn2res)
                    %        fn2resstr = vect2colon(cell2mat(fn2res), 'Sort','on');
                    %        fnformat = '{%s}';
                    %else
                    fn2resstr = vect2colon(fn2res, 'Sort','on');
                    fnformat = '%s';
                    %end
                    commandHistory = sprintf( ['%s, ''%s'', ' fnformat], commandHistory, fn2com, fn2resstr);
                end
            end
        end
    end
end
commandHistory = sprintf( '%s );', commandHistory);

% get history from script. EEG
switch inputParameters.Results.History
    case 'gui' % from GUI
        commandHistory = sprintf('%s %% GUI: %s', commandHistory, datestr(now));
        %fprintf('%%Equivalent command:\n%s\n\n', commandHistory);
        displayEquiComERP(commandHistory);
    case 'script' % from script
        EEG = erphistory(EEG, [], commandHistory, 1);
    case 'implicit'
        % implicit
    otherwise %off or none
        commandHistory = '';
end

%
% Completion statement
%
prefunc = dbstack;
nf = length(unique_bc2({prefunc.name}));
if nf==1
    msg2end
end
return

end

% function runGUI(EEG)
%  % Input EEG error check
%     serror = erplab_eegscanner(EEG, 'pop_erplabSelectChannelInterpolation',...
%         0, ... % 0 = do not accept md;
%         0, ... % 0 = do not accept empty dataset;
%         0, ... % 0 = do not accept epoched EEG;
%         0, ... % 0 = do not accept if no event codes
%         2);    % 2 = do not care if there exists an ERPLAB EVENTLIST struct
%
%     % Quit if there is an error with the input EEG
%     if serror
%         return
%     end
%
%     % Get previous input parameters
%     def  = erpworkingmemory('pop_erplabSelectChannelInterpolation');
%     if isempty(def)
%         def = {};
%     end
%
%     % Call GUI
%     inputstrMat = gui_erplab_selectiveEegInterpolation(def);  % GUI
%
%     % Exit when CANCEL button is pressed
%     if isempty(inputstrMat) && ~strcmp(inputstrMat,'')
%         commandHistory = 'User selected cancel';
%         return;
%     end
%
%     replaceChannels          = inputstrMat{1};
%     ignoreChannels           = inputstrMat{2};
%     interpolationMethod      = inputstrMat{3};
%     %     displayFeedback     = inputstrMat{4};
%     %
%     %     erpworkingmemory('pop_erplabSelectChannelInterpolation', ...
%     %         {replaceChannels, ignoreChannels, interpolationMethod, displayFeedback});
%     %
%
%     % New output EEG name
%     if length(EEG)==1
%         EEG.setname = [EEG.setname '_interpolated'];
%     end
%
%
%
%     [EEG, commandHistory] = pop_erplabSelectChannelInterpolation(EEG, ...
%         'replaceChannels'    , replaceChannels,  ...
%         'ignoreChannels'     , ignoreChannels,   ...
%         'interpolationMethod', interpolationMethod,    ...
%         'History'            , 'gui');
%
%
%     return
% end

author: ucdavis

repo: erplab

save_path: github-repos/MATLAB/ucdavis-erplab


text:
function image = draw_perimeter_image(image, map, intensity)
% draws a tight perimeter along ones in the map
% image(height, width, length(intensity))
% map(height, width, length(intensity))

scale = size(image, 1) / size(map, 1);
if size(image, 2) / size(map, 2) ~= scale
    disp('warning: map proportions not to scale!');
end

% get bounds
im_y = mod((0:size(map,2)*size(map, 1)-1), size(map, 1))+1;
im_x = floor((0:size(map,2)*size(map, 1)-1)/size(map, 1))+1;
solids_ind = find(map==1);
solids_x = im_x(solids_ind);
solids_y = im_y(solids_ind);

min_x = min(solids_x);
min_y = min(solids_y);
max_x = max(solids_x);
max_y = max(solids_y);

% draw and bottom top of perimeter
for x = min_x:max_x
    if min_y == 1 & map(min_y, x)
        image = draw_line_image2(image, ([x (x+1) min_y min_y]-1)'*scale+1, intensity);
    end
    if map(max_y, x)
            image = draw_line_image2(image, ([x (x+1) max_y+1 max_y+1]-1)'*scale+1, intensity);
    end
    for y = max(min_y,2):max_y

        if map(y, x)==1 & map(y-1, x)~=1
            image = draw_line_image2(image, ([x (x+1) y y]-1)'*scale+1, intensity);
        end
        if map(y, x)~=1 & map(y-1, x)==1
            image = draw_line_image2(image, ([x (x+1) y y]-1)'*scale+1, intensity);
        end
    end
end

% draw left and right of perimeter
for y = min_y:max_y
    if min_x == 1 & map(y, min_x)
        image = draw_line_image2(image, ([min_x min_x y (y+1)]-1)'*scale+1, intensity);
    end
    if map(y, max_x)
        image = draw_line_image2(image, ([max_x+1 max_x+1 y (y+1)]-1)'*scale+1, intensity);
    end
    for x = max(min_x, 2):max_x
        if map(y, x)==1 & map(y, x-1)~=1
            image = draw_line_image2(image, ([x x y (y+1)]-1)'*scale+1, intensity);
        end
        if map(y, x)~=1 & map(y, x-1)==1
            image = draw_line_image2(image, ([x x y (y+1)]-1)'*scale+1, intensity);
        end
    end
end

author: zouchuhang

repo: LayoutNet


text:
function O = img_hist2(subdir)
% A general function for plotting histograms of any image
% For each subject, comparing across subjects
%
% :Inputs:
%
%   **imgname:**
%        name of image file to make intensity histograms from
%
%   **subdir:**
%        cell array of text strings containing names of individual subject
%        directories (wherein are contained the file specified in imgname
%        or each subject)
%
% Performs the histogram plot a number of times, without plotting
% and reports the variance in pdf moments as a function of subject,
% run, and condition (beta img within run).
%
% Start in directory above individual subject results
%
% :Examples:
% ::
%
%    img_hist2(EXPT.subjects)
%    img_hist2({'020827mk' '020829jh' '020903lb'})
%
% ..
% Tor Wager
% ..

% ..
%    defaults
% ..
dwcard = '02*';									% wildcard defining ind subject directories, e.g., '02*'
%csfname = 'rnnhet1spgr_seg3.img';	% reslice first to space of functionals
%grname = 'rnnhet1spgr_seg1.img';
%csfpath = '/data/placebo/';		% before ind subject
%csfp2 = 'anatomy';							% after ind subject

Pc = getcsfname(subdir);
PP = getimgname;

[dummy,txtlab] = fileparts(Pc(1,:));

% rows = subjects
% cols = moment
%
% rows = subjects
% cols = runs
% 3d   = beta (condition)

for condition = 1:size(PP,1)
   for run = 1:size(PP,2)

       fprintf(1,'%s\n ',PP{condition,run})
       % hP = get_filename(dwcard,PP{condition,run});
	hP = tor_list_files(subdir,PP{condition,run});
 	hP = str2mat(hP(:));
       csfM = spm_general_hist(hP,Pc,txtlab,0);

       % Mean, Std, skeW, Kurtosis
       O.m(:,run,condition) = csfM(:,1);
       O.s(:,run,condition) = csfM(:,2);
       O.w(:,run,condition) = csfM(:,3);
       O.k(:,run,condition) = csfM(:,4);

   end
end

fprintf(1,'\n ')

diary img_hist2.out

disp(['EXPERIMENT: ' pwd]);disp('')

[O.subjM,O.Mtotalv] = displayme(O.m,txtlab,'MEANS');disp('')
[O.subjS,O.Stotalv] = displayme(O.s,txtlab,'STD');disp('')
[O.subjW,O.Wtotalv] = displayme(O.w,txtlab,'SKEWNESS');disp('')
[O.subjK,O.Ktotalv] = displayme(O.k,txtlab,'KURTOSIS');disp('')

diary off

keyboard

return

function Pc = getcsfname(subdir)

doseg = input('Do anatomical images need to be segmented? (1/0)');
if doseg
    % get the list of csf images for each subject
    myp = spm_get(1,'*img',['Choose anatomical img for ' subdir{1} '-  Others should have similar path.']);
    [d f e] = fileparts(myp);
    disp([myp])
    %subc = input('Enter subject code part of this path (replaced for all subjects): ','s');
    x = findstr(d,subdir{1});
    [d2 f2] = fileparts(d(x:end));
    d = d(1:x-1);
    % use d, subdir, and f2 as path
    Pc = fullfile(d,subdir{1},f2,[f e]);

    for i = 2:length(subdir)
        Pc = str2mat(Pc,fullfile(d,subdir{i},f2,[f e]));
    end

    try
        V = spm_vol(Pc);
    catch
        Pc
        disp('Error loading images!')
        keyboard
    end

    disp('Images must be resliced to space of functionals.')
    fname = spm_get(1,'*img','Choose a functional image from this study.');
    reslice_imgs(fname,Pc,1);

    canonicalT1 = spm_get(1,'*img','Choose Template Image.');
    spm_segment(canonicalT1,'C')
end

% get the list of csf images for each subject
myp = spm_get(1,'*img',['Choose csf mask (in space of functionals) for ' subdir{1} '-  Others should have similar path.']);
[d f e] = fileparts(myp);
disp([myp])
%subc = input('Enter subject code part of this path (replaced for all subjects): ','s');
x = findstr(d,subdir{1});
[d2 f2] = fileparts(d(x:end));
d = d(1:x-1);
% use d, subdir, and f2 as path
Pc = fullfile(d,subdir{1},f2,[f e]);

for i = 2:length(subdir)
    Pc = str2mat(Pc,fullfile(d,subdir{i},f2,[f e]));
end

return

function PP = getimgname

% get the list of betas within runs
mypwd = pwd;
mydir = spm_get(-1,'*','Choose an individual subject SPM results dir');
eval(['cd ' mydir])
d = dir(['beta*img']);
load SPM
P = str2mat(d.name);
ind = 1;
for i = 1:length(Sess)
    for j = 1:length(Sess{i}.col)
        PP{j,i} = deblank(P(ind,:));
        ind = ind + 1;
    end
end
eval(['cd ' mypwd])

return

function a = getmeans(a,d1,d2)
% input mat, dim to avg over, 2nd dim to avg over

a = squeeze(mean(mean(a,d1),d2));
if size(a,2) > size(a,1), a = a';, end

return

function [subjM,Mtotalv] = displayme(mm,txtlab,tlab2)

gm = mean(mean(mean(mm)));
Mtotalv = sum((mm(:) - gm).^2);

disp(['Variability across ' tlab2 ' within mask: ' txtlab])
disp(['Grand mean (over the experiment) is ' num2str(gm) ', SSt = ' num2str(Mtotalv)])

subjM = getmeans(mm,2,3);
Mexp = (prod(size(mm)) ./ size(mm,1)) * sum((subjM - mean(subjM)).^2);
dfb = size(mm,1) - 1; dfw = prod(size(mm)) - (dfb+1);
F = Mexp./(Mtotalv-Mexp);
fprintf(1,'SESSION\tm %3.2f\tstd %3.2f\t SSb %3.2f\t%%Var explained %3.2f\tF(%3.0f,%3.0f) = %3.2f\tp = %3.5f\n', ...
	mean(subjM),std(subjM),Mexp,100*(Mexp./Mtotalv),dfb,dfw,F,1-fcdf(F,dfb,dfw));

subjM = getmeans(mm,1,3);
Mexp = (prod(size(mm)) ./ size(mm,2)) * sum((subjM - mean(subjM)).^2);
dfb = size(mm,2) - 1; dfw = prod(size(mm)) - (dfb+1);
F = Mexp./(Mtotalv-Mexp);
fprintf(1,'RUN\tm %3.2f\tstd %3.2f\t SSb %3.2f\t%%Var explained %3.2f\tF(%3.0f,%3.0f) = %3.2f\tp = %3.5f\n', ...
	mean(subjM),std(subjM),Mexp,100*(Mexp./Mtotalv),dfb,dfw,F,1-fcdf(F,dfb,dfw));

subjM = getmeans(mm,1,2);
Mexp = (prod(size(mm)) ./ size(mm,3)) * sum((subjM - mean(subjM)).^2);
dfb = size(mm,3) - 1; dfw = prod(size(mm)) - (dfb+1);
F = Mexp./(Mtotalv-Mexp);
fprintf(1,'CONDITION\tm %3.2f\tstd %3.2f\t SSb %3.2f\t%%Var explained %3.2f\tF(%3.0f,%3.0f) = %3.2f\tp = %3.5f\n', ...
	mean(subjM),std(subjM),Mexp,100*(Mexp./Mtotalv),dfb,dfw,F,1-fcdf(F,dfb,dfw));

return

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function k = fileKernDiagCompute(kern, x)

% FILEKERNDIAGCOMPUTE Compute diagonal of FILE kernel.
% FORMAT
% DESC computes the diagonal of the kernel matrix for the stored file kernel given a design matrix of inputs.
% ARG kern : the kernel structure for which the matrix is computed.
% ARG index : indices of the diagonal to return.
% RETURN k : a vector containing the diagonal of the kernel matrix
% computed at the given points.
%
% SEEALSO : fileKernParamInit, kernDiagCompute, kernCreate, fileKernCompute
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2006

% KERN

k = kern.variance*fileKernRead(kern, x, 'diag');

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
function E=fit1(x0,x,y)
E=max(abs( x0(1)*x+x0(2)-y ));

author: dynamicslab


text:
function Sd = makeSdzip(baseMVA, bus, mpopt)
%MAKESDZIP   Builds vectors of nominal complex bus power demands for ZIP loads.
%   SD = MAKESDZIP(BASEMVA, BUS, MPOPT) returns a struct with three fields,
%   each an nb x 1 vectors. The fields 'z', 'i' and 'p' correspond to the
%   nominal p.u. complex power (at 1 p.u. voltage magnitude) of the constant
%   impedance, constant current, and constant power portions, respectively of
%   the ZIP load model.
%
%   Example:
%       Sd = makeSdzip(baseMVA, bus, mpopt);

%   MATPOWER
%   Copyright (c) 2015-2016, Power Systems Engineering Research Center (PSERC)
%   by Shrirang Abhyankar
%   and Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;

if nargin < 3
    mpopt = [];
end
if ~isempty(mpopt) && ~isempty(mpopt.exp.sys_wide_zip_loads.pw)
    if any(size(mpopt.exp.sys_wide_zip_loads.pw) ~= [1 3])
        error('makeSdzip: ''exp.sys_wide_zip_loads.pw'' must be a 1 x 3 vector');
    end
    if abs(sum(mpopt.exp.sys_wide_zip_loads.pw) - 1) > eps
        error('makeSdzip: elements of ''exp.sys_wide_zip_loads.pw'' must sum to 1');
    end
    pw = mpopt.exp.sys_wide_zip_loads.pw;
else
    pw = [1 0 0];
end
if ~isempty(mpopt) && ~isempty(mpopt.exp.sys_wide_zip_loads.qw)
    if any(size(mpopt.exp.sys_wide_zip_loads.qw) ~= [1 3])
        error('makeSdzip: ''exp.sys_wide_zip_loads.qw'' must be a 1 x 3 vector');
    end
    if abs(sum(mpopt.exp.sys_wide_zip_loads.qw) - 1) > eps
        error('makeSdzip: elements of ''exp.sys_wide_zip_loads.qw'' must sum to 1');
    end
    qw = mpopt.exp.sys_wide_zip_loads.qw;
else
    qw = pw;
end

Sd.z = (bus(:, PD) * pw(3)  + 1j * bus(:, QD) * qw(3)) / baseMVA;
Sd.i = (bus(:, PD) * pw(2)  + 1j * bus(:, QD) * qw(2)) / baseMVA;
Sd.p = (bus(:, PD) * pw(1)  + 1j * bus(:, QD) * qw(1)) / baseMVA;

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function rcnn_cache_pool5_features(imdb, varargin)
% rcnn_cache_pool5_features(imdb, varargin)
%   Computes pool5 features and saves them to disk. We compute
%   pool5 features because we can easily compute fc6 and fc7
%   features from them on-the-fly and they tend to compress better
%   than fc6 or fc7 features due to greater sparsity.
%
%   Keys that can be passed in:
%
%   start             Index of the first image in imdb to process
%   end               Index of the last image in imdb to process
%   crop_mode         Crop mode (either 'warp' or 'square')
%   crop_padding      Amount of padding in crop
%   net_file          Path to the Caffe CNN to use
%   cache_name        Path to the precomputed feature cache

% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------

ip = inputParser;
ip.addRequired('imdb', @isstruct);
ip.addOptional('start', 1, @isscalar);
ip.addOptional('end', 0, @isscalar);
ip.addOptional('crop_mode', 'warp', @isstr);
ip.addOptional('crop_padding', 16, @isscalar);
ip.addOptional('net_file', ...
    './data/caffe_nets/finetune_voc_2007_trainval_iter_70k', ...
    @isstr);
ip.addOptional('cache_name', ...
    'v1_finetune_voc_2007_trainval_iter_70000', @isstr);

ip.parse(imdb, varargin{:});
opts = ip.Results;
opts.net_def_file = './model-defs/rcnn_batch_256_output_pool5.prototxt';

image_ids = imdb.image_ids;
if opts.end == 0
  opts.end = length(image_ids);
end

% Where to save feature cache
opts.output_dir = ['./feat_cache/' opts.cache_name '/' imdb.name '/'];
mkdir_if_missing(opts.output_dir);

% Log feature extraction
timestamp = datestr(datevec(now()), 'dd.mmm.yyyy:HH.MM.SS');
diary_file = [opts.output_dir 'rcnn_cache_pool5_features_' timestamp '.txt'];
diary(diary_file);
fprintf('Logging output in %s\n', diary_file);

fprintf('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n');
fprintf('Feature caching options:\n');
disp(opts);
fprintf('~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n');

% load the region of interest database
roidb = imdb.roidb_func(imdb);

rcnn_model = rcnn_create_model(opts.net_def_file, opts.net_file);
rcnn_model = rcnn_load_model(rcnn_model);
rcnn_model.detectors.crop_mode = opts.crop_mode;
rcnn_model.detectors.crop_padding = opts.crop_padding;

total_time = 0;
count = 0;
for i = opts.start:opts.end
  fprintf('%s: cache features: %d/%d\n', procid(), i, opts.end);

  save_file = [opts.output_dir image_ids{i} '.mat'];
  if exist(save_file, 'file') ~= 0
    fprintf(' [already exists]\n');
    continue;
  end
  count = count + 1;

  tot_th = tic;

  d = roidb.rois(i);
  im = imread(imdb.image_at(i));

  th = tic;
  d.feat = rcnn_features(im, d.boxes, rcnn_model);
  fprintf(' [features: %.3fs]\n', toc(th));

  th = tic;
  save(save_file, '-struct', 'd');
  fprintf(' [saving:   %.3fs]\n', toc(th));

  total_time = total_time + toc(tot_th);
  fprintf(' [avg time: %.3fs (total: %.3fs)]\n', ...
      total_time/count, total_time);
end

author: rbgirshick

repo: rcnn

save_path: github-repos/MATLAB/rbgirshick-rcnn