text:
% plugin_installstartup() - install popular toolboxes when EEGLAB starts
%
% Usage:
%   >> restartEeglabFlag = plugin_installstartup; % pop up window
%
% Outputs:
%   restartEeglabFlag - [0|1] restart EEGLAB
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Oct. 29, 2013-

% Copyright (C) 2013 Arnaud Delorme, SCCN, INC, UCSD, arno@salk.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function restartEeglabFlag = plugin_installstartup

%                 { 'style' 'checkbox' 'string' 'Neuroelectromagnetic Forward Head Modeling Toolbox (NFT): Advanced source localization tools - beta (Zeynep Akalin Acar, 100 Mb)' 'value' 1 'enable' 'on' } ...

    uilist = { { 'style' 'text' 'String' 'Download and install some popular third party EEGLAB plug-ins' 'fontweight', 'bold','tag', 'title'} ...
                 { } ...
                 { 'style' 'checkbox' 'string' 'Brain Vision Analyser data import plugin (40 Kb)' 'value' 1 'enable' 'on' } ...
                 { 'style' 'checkbox' 'string' 'ANT data import plugin (800 Kb)' 'value' 1 'enable' 'on' } ...
                 { 'style' 'checkbox' 'string' 'Measure Projection Toolbox (MPT) for ulti-subject ICA analysis (415 Mb)' 'value' 1 'enable' 'on' } ...
                 { 'style' 'checkbox' 'string' 'Source Information Flow Toolbox (SIFT) for causal analysis of EEG sources (600 Mb)' 'value' 1 'enable' 'on' } ...
                 { 'style' 'checkbox' 'string' 'BCILAB for real-time and offline BCI platform (200 Mb)' 'value' 1 'enable' 'on' } ...
                 { 'style' 'checkbox' 'string' 'LIMO for linear analysis of MEEG data using single trials (2.5 Mb)' 'value' 1 'enable' 'on' } ...
                 { } ...
                 { 'style' 'radiobutton' 'string' 'Do not show this query again' 'value' 0 } ...
                 {} ...
                 { 'style' 'text' 'String' 'Note: manage plug-in tools using EEGLAB menu item, "File > Plug-ins > Manage plug-ins"' } ...
                 {} ...
                 { 'Style', 'pushbutton', 'string', 'Do not install now', 'tag' 'cancel' 'callback', 'set(gcbf, ''userdata'', ''cancel'');' } { } ...
                 { 'Style', 'pushbutton', 'string', 'Install plugins now', 'tag', 'ok', 'callback', 'set(gcbf, ''userdata'', ''ok'');' } ...
                 };

    geomline = [1];
    geom     = { [1] [1] geomline geomline geomline geomline geomline geomline [1] geomline [1] [1] [1] [1 1 1]};
    geomvert = [ 1   0.5 1        1        1        1        1        1        0.3 1        0.3 1   1   1];

    %result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''plugin_installstartup'')', 'title', 'Install popular plugins', 'geomvert', geomvert, 'eval', evalstr);
    fig = figure('visible', 'off');
    [tmp1 tmp2 handles] = supergui( 'geomhoriz', geom, 'uilist', uilist, 'title', 'Install popular plugins', 'geomvert', geomvert, 'fig', fig); %, 'eval', evalstr);
    set(findobj(fig, 'tag', 'title'), 'fontsize', 16);
    waitfor( fig, 'userdata');

    % decode inputs
    handles
    results = cellfun(@(x)(get
    get(handles, 'value')

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function pass = test_std2(pref)
% Test the chebfun3/max command.

if ( nargin < 1 )
    pref = chebfunpref;
end
tol = 1e3*pref.cheb3Prefs.chebfun3eps;

% Note that std(chebfun(@(x) x.^2)) = sqrt(4/45).

f1 = chebfun3(@(x,y,z) x.^2 + z); % f1 has (x,y)-std equal to sqrt(4/45).
f2 = chebfun3(@(x,y,z) z.^2 + y); % f2 has (x,z)-std equal to sqrt(4/45).
f3 = chebfun3(@(x,y,z) y.^2 + x); % f3 has (y,z)-std equal to sqrt(4/45).

exact = chebfun(@(x) sqrt(4/45)); % (x,y)-std of z equals 0.

h1 = std2(f1);
h2 = std2(f1,[],[1,2]);
h3 = std2(f2,[],[1,3]);
h4 = std2(f3,[],[3, 2]);

pass(1) = norm(h1 - exact) < tol;
pass(2) = norm(h2 - exact) < tol;
pass(3) = norm(h3 - exact) < tol;
pass(4) = norm(h4 - exact) < tol;

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function T = EinsteinSum(varargin)
% tensor multiplication according to Einstein summation convention
%
% Description
% This function computes a tensor product according to Einstein summation
% convention
%
% Syntax
%   % sumation against dimension 1 and 2
%   C = EinsteinSum(E,[1 -1 2 -2],v,-1,v,-2)
%
%   eps = EinsteinSum(C,[-1 1 -2 2],sigma,[-1 -2])
%
% Input
%  T1,T2 - @tensor
%  dimT1 - vector of indices giving the summation order in tensor 1
%  dimT2 - vector of indices giving the summation order in tensor 2
%
% Output
%  T - @tensor
%
% See also
%

% TODO: check for correct symmetries !!!

global useBSXFUN;

M1 = 1; dimT1 = [];
T = varargin{1};

% for each tensor in varargin
iv = 1;
while iv < length(varargin) && ~ischar(varargin{iv})

  % take new vector from varargin
  M2 = varargin{iv};
  dimT2 = varargin{iv+1};
  iv = iv+2;

  % convert to double
  if isa(M2,'tensor')
    M2 = M2.M;
  elseif isa(M2,'quaternion')
    M2 = matrix(M2);
  elseif isa(M2,'vector3d')
    M2 = double(M2);
    M2 = permute(M2,[3 1 2]);
  end

  %
  if length(dimT2) > 1 && sum(dimT2<0)>1 && max(accumarray(-dimT2(dimT2<0).',1)>1)
    [M2,dimT2] = innerSum(M2,dimT2);
  end

  % reorder T1 such that [-rDel ... -3 -2 -1  1 2 3 .. rOut x x x]
  rOut = max([0,dimT1,dimT2]);
  rDel = -min([0,dimT1,dimT2]);
  rExt = max([0,ndims(M1) - length(dimT1), ndims(M2) - length(dimT2)]);

  % new order of dimensions for tensor 1
  dimT1(dimT1>0) = dimT1(dimT1>0) - 1;  % we should start with zero to avoid the cap
  exp1 = 1:rOut + rDel; exp1(dimT1 + rDel + 1) = []; % dimensions in reserve
  order1 = [dimT1 + rDel + 1,...  the tensor components
    rOut + rDel + (1:rExt),...    none tensor components
    exp1];

  % new order of dimensions for tensor 2
  dimT2(dimT2>0) = dimT2(dimT2>0) - 1; % we should start with zero to avoid the cap
  exp2 = 1:rOut + rDel; exp2(dimT2 + rDel + 1) = []; % dimensions in reserve
  order2 = [dimT2 + rDel + 1,...  the tensor components
    rOut + rDel + (1:rExt),...    none tensor components
    exp2];

  M1 = ipermute(M1,order1);
  M2 = ipermute(M2,order2);

  if useBSXFUN
    M1 = bsxfun(@times, M1, M2);
  else
    M1 = M1 .* M2;
  end

  % setup dimT1
  dimT1 = [-rDel:-1,1:rOut];

end

% sum over the dimensions to be removed
if useBSXFUN
  for d = 1:rDel, M1 = sum(M1,d); end
else
  if rDel>0, M1 = sum(M1,1:rDel); end
end

% and remove these leading dimensions
s = size(M1);
M1 = reshape(M1,[s(rDel+1:end) 1 1]);

% rank 0 tensor should become double
if rOut == 0
  T = M1;
elseif strcmp(class(T),'tensor') || check_option(varargin(iv:end),'keepClass')
  T.M = M1;
  T.rank = rOut;
else
  T = tensor(M1,T.CS,'noCheck','rank',rOut,varargin{iv:end});
end

end

%%
function [M,ind] = innerSum(M,ind)

% find indices to be summed
[a,b] = findDouble(ind);

if isempty(a), return;end

ind([a,b]) = [];

% remember size of matrix
sM = size(M);
sM([a,b]) = [];

% make a,b the first two dimensions
order = 1:max([ndims(M) a b]);
order([a b]) = [];
order = [a b order];
M = permute(M,order);

% reduces multiple remove dimensions to one
M = reshape(M,3^numel(a),3^numel(b),[]);

% sum along the diagonal of the first two dimensions
N = zeros(1,1,size(M,3));
for l = 1:3^numel(a)
  N = N + M(l,l,:);
end

% reshape back
M = reshape(N,[sM 1 1]);

end

%%
function [a,b] = findDouble(x)

%if length(x) <= 1 || all(x>=0) || sum(x<0)<2 || max(accumarray(-x(x<0).',1))<2
%  a = [];
%  b = [];
%  return;
%end

d = bsxfun(@minus,x,x') == 0 & bsxfun(@times,x<0,x'<0);
d = d & ~tril(ones(size(d)));
[a,b] = find(d);
a = a'; b = b';

end

author: mtex-toolbox

repo: mtex

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


text:
function [Y, XYZ] = iimg_read_vols(V, mask)
% Drop-in replacement for spm_read_vols
% Primary difference is that if the images have the same voxel size but are NOT resliced
% (e.g., have differing affine matrices), this will handle reading each individually and
% putting them together.

    if nargin<2, mask = 0; end
    if nargin<1, error('insufficient arguments'); end

    if length(V)>1 && any(any(diff(cat(1, V.dim), 1, 1), 1))
        error('images don''t all have the same dimensions');
    end
    if any(any(any(diff(cat(3, V.mat), 1, 3), 3)))
        %error('images don''t all have same orientation & voxel size');
        for i = 1:length(V)
            Y(:,:,:,i) = spm_read_vols(V(i), mask);
        end

        if nargout > 1
            [R, C, P] = ndgrid(1:V(1).dim(1), 1:V(1).dim(2), 1:V(1).dim(3));
            RCP = [R(:)';C(:)';P(:)'];
            clear R C P
            RCP(4,:) = 1;
            XYZ = V(1).mat(1:3,:)*RCP;
        end
    else
        [Y, XYZ] = spm_read_vols(V, mask);
    end
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2014 the National Renewable Energy Laboratory and Sandia Corporation
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Run the WEC-Sim RM3 Test Case for 1DOF w/PTO
% This script will run the RM3 in WEC-Sim for irregular waves with Hs=2.5[m]
% and Tp=8[s]. The RM3 WEC models has 2 bodies, restricted to heave motion
% only, and has PTO damping=1200[kN-s/m].

global plotNO
locdir=pwd;
%% Run Simulation
wecSim;                     % Run Simulation

%% Post-Process Data
% Body 1
B1.WEC_Sim_new.time=output.bodies(1).time;
Hshift1=output.bodies(1).position(1,3);
B1.WEC_Sim_new.heave=output.bodies(1).position(:,3)-Hshift1;
%Body 2
B2.WEC_Sim_new.time=output.bodies(2).time;
Hshift2=output.bodies(2).position(1,3);
B2.WEC_Sim_new.heave=output.bodies(2).position(:,3)-Hshift2;
% Relative Motion
Rel.WEC_Sim_new.time=B1.WEC_Sim_new.time;
Rel.WEC_Sim_new.heave=B1.WEC_Sim_new.heave-B2.WEC_Sim_new.heave;
% Spectrum
Sp.WEC_Sim_new.m0 = calcSpectralMoment(waves.omega,waves.spectrum,0);
Sp.WEC_Sim_new.m2 = calcSpectralMoment(waves.omega,waves.spectrum,2);

%% Load Data
irrCICouput_new=output;        % Keeps the new run in the workspace
load('irregularCIC_org.mat')    % Load Previous WEC-Sim Data

%% Post-Process Data
% Body 1
B1.WEC_Sim_org.time=output.bodies(1).time;
Hshift1=output.bodies(1).position(1,3);
B1.WEC_Sim_org.heave=output.bodies(1).position(:,3)-Hshift1;
%Body 2
B2.WEC_Sim_org.time=output.bodies(2).time;
Hshift2=output.bodies(2).position(1,3);
B2.WEC_Sim_org.heave=output.bodies(2).position(:,3)-Hshift2;
% Relative Motion
Rel.WEC_Sim_org.time=B1.WEC_Sim_org.time;
Rel.WEC_Sim_org.heave=B1.WEC_Sim_org.heave-B2.WEC_Sim_org.heave;
% Spectrum
Sp.WEC_Sim_org.m0 = calcSpectralMoment(waves.omega,waves.spectrum,0);
Sp.WEC_Sim_org.m2 = calcSpectralMoment(waves.omega,waves.spectrum,2);

clear Hshift1 Hshift2

%% Quantify Maximum Difference Between Saved and Current WEC-Sim Runs
[irregularCIC.B1_H_max ,irregularCIC.B1_H_I]=max(abs(B1.WEC_Sim_org.heave-B1.WEC_Sim_new.heave));
[irregularCIC.B2_H_max ,irregularCIC.B2_H_I]=max(abs(B2.WEC_Sim_org.heave-B2.WEC_Sim_new.heave));
[irregularCIC.Rel_H_max,irregularCIC.Rel_H_I]=max(abs(Rel.WEC_Sim_org.heave-Rel.WEC_Sim_new.heave));

irregularCIC.B1  = B1;
irregularCIC.B2  = B2;
irregularCIC.Rel = Rel;
irregularCIC.Sp  = Sp;

save('irregularCIC','irregularCIC')

%% Plot Old vs. New Comparison
if plotNO==1 % global variable
    cd ../..
    plotOldNew(B1,B2,Rel,[irregularCIC.B1_H_max ,irregularCIC.B1_H_I],...
        [irregularCIC.B2_H_max ,irregularCIC.B2_H_I],...
        [irregularCIC.Rel_H_max,irregularCIC.Rel_H_I],'IrregularCIC');
    cd(locdir)
end
%% Clear output and .slx directory

try
	rmdir('output','s')
	rmdir('slprj','s')
	delete('RM3.slx.autosave', 'RM3_sfun.mexmaci64')
catch
end

author: WEC-Sim

repo: WEC-Sim

save_path: github-repos/MATLAB/WEC-Sim-WEC-Sim


text:
function [ area, radin, radout ] = polygon_side_data_2d ( n, side )

%*****************************************************************************80
%
%% POLYGON_SIDE_DATA_2D determines polygonal data from its side length in 2D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of sides of the polygon.
%    N must be at least 3.
%
%    Input, real SIDE, the length of one side of the polygon.
%
%    Output, real AREA, the area of the regular polygon.
%
%    Output, real RADIN, the inner radius of the polygon, that is,
%    the radius of the largest circle that can be inscribed within
%    the polygon.
%
%    Output, real RADOUT, the outer radius of the polygon, that is,
%    the radius of the smallest circle that can be described about
%    the polygon.
%
  if ( n < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'POLYGON_SIDE_DATA_2D - Fatal error!\n' );
    fprintf ( 1, '  Input value of N must be at least 3.\n' );
    fprintf ( 1, '  but your input value was N = ', n );
    error ( 'POLYGON_SIDE_DATA_2D - Fatal error!' );
  end

  angle = pi / n;
  area = 0.5 * n * side * side / tan ( angle );
  radin = 0.5 * side / tan ( angle );
  radout = 0.5 * side / sin ( angle );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function c=melcepst(s,fs,w,nc,p,n,inc,fl,fh)
%MELCEPST Calculate the mel cepstrum of a signal C=(S,FS,W,NC,P,N,INC,FL,FH)
%
%
% Simple use: c=melcepst(s,fs)	% calculate mel cepstrum with 12 coefs, 256 sample frames
%				  c=melcepst(s,fs,'e0dD') % include log energy, 0th cepstral coef, delta and delta-delta coefs
%
% Inputs:
%     s	 speech signal
%     fs  sample rate in Hz (default 11025)
%     nc  number of cepstral coefficients excluding 0'th coefficient (default 12)
%     n   length of frame (default power of 2 <30 ms))
%     p   number of filters in filterbank (default floor(3*log(fs)) )
%     inc frame increment (default n/2)
%     fl  low end of the lowest filter as a fraction of fs (default = 0)
%     fh  high end of highest filter as a fraction of fs (default = 0.5)
%
%		w   any sensible combination of the following:
%
%				'R'  rectangular window in time domain
%				'N'	Hanning window in time domain
%				'M'	Hamming window in time domain (default)
%
%		      't'  triangular shaped filters in mel domain (default)
%		      'n'  hanning shaped filters in mel domain
%		      'm'  hamming shaped filters in mel domain
%
%				'p'	filters act in the power domain
%				'a'	filters act in the absolute magnitude domain (default)
%
%			   '0'  include 0'th order cepstral coefficient
%				'e'  include log energy
%				'd'	include delta coefficients (dc/dt)
%				'D'	include delta-delta coefficients (d^2c/dt^2)
%
%		      'z'  highest and lowest filters taper down to zero (default)
%		      'y'  lowest filter remains at 1 down to 0 frequency and
%			   	  highest filter remains at 1 up to nyquist freqency
%
%		       If 'ty' or 'ny' is specified, the total power in the fft is preserved.
%
% Outputs:	c     mel cepstrum output: one frame per row
%

%      Copyright (C) Mike Brookes 1997
%
%      Last modified Thu Jun 15 09:14:48 2000
%
%   VOICEBOX is a MATLAB toolbox for speech processing. Home page is at
%   http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   ftp://prep.ai.mit.edu/pub/gnu/COPYING-2.0 or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin<2 fs=11025; end
if nargin<3 w='M'; end
if nargin<4 nc=12; end
if nargin<5 p=floor(3*log(fs)); end
if nargin<6 n=pow2(floor(log2(0.03*fs))); end
if nargin<9
   fh=0.5;
   if nargin<8
     fl=0;
     if nargin<7
        inc=floor(n/2);
     end
  end
end

if any(w=='R')
   z=enframe(s,n,inc);
elseif any (w=='N')
   z=enframe(s,hanning(n),inc);
else
   z=enframe(s,hamming(n),inc);
end
f=rfft(z.');
[m,a,b]=melbankm(p,n,fs,fl,fh,w);
pw=f(a:b,:).*conj(f(a:b,:));
pth=max(pw(:))*1E-6;
if any(w=='p')
   y=log(max(m*pw,pth));
else
   ath=sqrt(pth);
   y=log(max(m*abs(f(a:b,:)),ath));
end
c=rdct(y).';
nf=size(c,1);
nc=nc+1;
if p>nc
   c(:,nc+1:end)=[];
elseif p<nc
   c=[c zeros(nf,nc-p)];
end
if ~any(w=='0')
   c(:,1)=[];
end
if any(w=='e')
   c=[log(sum(pw)).' c];
end

% calculate derivative

if any(w=='D')
  vf=(4:-1:-4)/60;
  af=(1:-1:-1)/2;
  ww=ones(5,1);
  cx=[c(ww,:); c; c(nf*ww,:)];
  vx=reshape(filter(vf,1,cx(:)),nf+10,nc);
  vx(1:8,:)=[];
  ax=reshape(filter(af,1,vx(:)),nf+2,nc);
  ax(1:2,:)=[];
  vx([1 nf+2],:)=[];
  if any(w=='d')
     c=[c vx ax];
  else
     c=[c ax];
  end
elseif any(w=='d')
  vf=(4:-1:-4)/60;
  ww=ones(4,1);
  cx=[c(ww,:); c; c(nf*ww,:)];
  vx=reshape(filter(vf,1,cx(:)),nf+8,nc);
  vx(1:8,:)=[];
  c=[c vx];
end

if nargout<1
   [nf,nc]=size(c);
   t=((0:nf-1)*inc+(n-1)/2)/fs;
   ci=(1:nc)-any(w=='0')-any(w=='e');
   imh = imagesc(t,ci,c.');
   axis('xy');
   xlabel('Time (s)');
   ylabel('Mel-cepstrum coefficient');
	map = (0:63)'/63;
	colormap([map map map]);
	colorbar;
end

author: bastamon


text:
function r = atan(p)
%UMINUS: this function calculates the atan of a x, y, and z values of
% the structures that I use in the FVtool.
%
% SYNOPSIS:
%
%
% PARAMETERS:
%
%
% RETURNS:
%
%
% EXAMPLE:
%
% SEE ALSO:
%

% Copyright (c) 2012-2016 Ali Akbar Eftekhari
% See the license file

r = p;
r.xvalue = atan(p.xvalue);
r.yvalue = atan(p.yvalue);
r.zvalue = atan(p.zvalue);

author: simulkade

repo: FVTool

save_path: github-repos/MATLAB/simulkade-FVTool


text:
function S = globMatrixNed3DMass(fun,mesh,fem1,fem2)

%% USAGE: generate stiffness global matrix on a 3D mesh
%
% INPUTS:
% fun --- coefficient function
% mesh --- a struct data contains very rich mesh information.
% fem1 --- global DoF for test function space
% fem2 --- global DoF for trial function space
%
% OUTPUTS:
% [IN JN XN] --- triplets of the sparse matrix from regular elements.
% [II JI XI] --- triplets of the sparse matrix from interface elements.

% Last Modified: 08/07/2020 by Xu Zhang

%% 0. Initializaiton
feEvalBas1 = @EvalNed1Bas3D;
feEvalBas2 = @EvalNed1Bas3D;

dof1 = fem1.ldof; dof2 = fem2.ldof; nloc = dof1*dof2;
nt = length(mesh.t);
A = fem1.area; gx = fem1.gx; gy = fem1.gy; gz = fem1.gz; gw = fem1.gw;
X = zeros(nloc*nt, 1);

coef = feval(fun,gx,gy,gz);
Ibasx = cell(dof1,1); Ibasy = cell(dof1,1); Ibasz = cell(dof1,1);
Jbasx = cell(dof2,1); Jbasy = cell(dof2,1); Jbasz = cell(dof2,1);
for i = 1:dof1
    Ibasx{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 0, 1).*fem1.t_e_orit(:,i);
    Ibasy{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 0, 2).*fem1.t_e_orit(:,i);
    Ibasz{i} = feEvalBas1(fem1.bas, ':', gx, gy, gz, i, 0, 3).*fem1.t_e_orit(:,i);
end
for j = 1:dof2
    Jbasx{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 0, 1).*fem2.t_e_orit(:,j);
    Jbasy{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 0, 2).*fem2.t_e_orit(:,j);
    Jbasz{j} = feEvalBas2(fem2.bas, ':', gx, gy, gz, j, 0, 3).*fem2.t_e_orit(:,j);
end

I = reshape(repmat(fem1.g2ldof,6,1),nloc*nt,1);
J = repmat(reshape(fem2.g2ldof,dof2*nt,1),6,1);
ind = 0;
for i = 1:dof1
    for j = 1:dof2
        X(ind+1:ind+nt) = A.*(sum(((Ibasx{i}.*(coef.*Jbasx{j})).*gw'),2) + ...
            sum(((Ibasy{i}.*(coef.*Jbasy{j})).*gw'),2) + ...
            sum(((Ibasz{i}.*(coef.*Jbasz{j})).*gw'),2));
        ind = ind + nt;
    end
end
ID = find(X~=0);
S = sparse(I(ID),J(ID),X(ID),size(fem1.gdof,1),size(fem2.gdof,1));

repo: ifem


text:
% OCR (Optical Character Recognition).
% PRINCIPAL PROGRAM
warning off %#ok<WNOFF>
% Clear all
clc, close all, clear all
% Read image
imagen=imread('TEST_1.jpg');
% Show image
imshow(imagen);
title('INPUT IMAGE WITH NOISE')
% Convert to gray scale
if size(imagen,3)==3 %RGB image
    imagen=rgb2gray(imagen);
end
% Convert to BW
threshold = graythresh(imagen);
imagen =~im2bw(imagen,threshold);
% Remove all object containing fewer than 30 pixels
imagen = bwareaopen(imagen,30);
%Storage matrix word from image
word=[ ];
re=imagen;
%Opens text.txt as file for write
fid = fopen('text.txt', 'wt');
% Load templates
load templates
global templates
% Compute the number of letters in template file
num_letras=size(templates,2);
while 1
    %Fcn 'lines' separate lines in text
    [fl re]=lines(re);
    imgn=fl;
    %Uncomment line below to see lines one by one
    %imshow(fl);pause(0.5)
    %-----------------------------------------------------------------
    % Label and count connected components
    [L Ne] = bwlabel(imgn);
    for n=1:Ne
        [r,c] = find(L==n);
        % Extract letter
        n1=imgn(min(r):max(r),min(c):max(c));
        % Resize letter (same size of template)
        img_r=imresize(n1,[42 24]);
        %Uncomment line below to see letters one by one
         %imshow(img_r);pause(0.5)
        %-------------------------------------------------------------------
        % Call fcn to convert image to text
        letter=read_letter(img_r,num_letras);
        % Letter concatenation
        word=[word letter];
    end
    %fprintf(fid,'%s\n',lower(word));%Write 'word' in text file (lower)
    fprintf(fid,'%s\n',word);%Write 'word' in text file (upper)
    % Clear 'word' variable
    word=[ ];
    %*When the sentences finish, breaks the loop
    if isempty(re)  %See variable 're' in Fcn 'lines'
        break
    end
end
fclose(fid);
%Open 'text.txt' file
winopen('text.txt')
fprintf('For more information, visit: <a href= "http://www.matpic.com">www.matpic.com </a> \n')
clear all

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function writeInputFromBlocks(inputFile)
% This function reads custom parameters from masked WEC-Sim blocks, and
% writes a new wecSimInputFile.m based on the mask variables.
%
% Steps:
% 1. Blocks are reordered into the standard WEC-Sim input file order
%    (simu, waves, body, constraint, pto, cable, mooring)
% 2. Open a new output file and create default classes
% 3. For every mask variable, call the writeLineFromVar() function for
%    that block to determine the appropriate string for the input file
%
% Note: str2num used because mask parameters are always read as type 'char'
% Note: mat2str used so that types are printed in the correct format

% Get all block names
blocks = find_system(bdroot,'Type','Block');

%% Reorder blocks
% Order blocks by class:
%    simu/waves, body, constraints, ptos, cables, moorings
iSimulation = [];
iBody = [];
iConstraint = [];
iPTO = [];
iCable = [];
iMooring = [];

for i=1:length(blocks)
    names = get_param(blocks{i},'MaskNames');
    if any(strcmp(names,'simu'))
        iSimulation = i;
    elseif any(strcmp(names,'body'))
        iBody(end+1) = i;
    elseif any(strcmp(names,'constraint'))
        iConstraint(end+1) = i;
    elseif any(strcmp(names,'pto'))
        iPTO(end+1) = i;
    elseif any(strcmp(names,'cable'))
        iCable(end+1) = i;
    elseif any(strcmp(names,'mooring'))
        iMooring(end+1) = i;
    end
end

% Order classes by number
iSorted = sortBlocksByNumber(blocks(iBody),'body');
iBody = iBody(iSorted);

iSorted = sortBlocksByNumber(blocks(iConstraint),'constraint');
iConstraint = iConstraint(iSorted);

iSorted = sortBlocksByNumber(blocks(iPTO),'pto');
iPTO = iPTO(iSorted);

iSorted = sortBlocksByNumber(blocks(iCable),'cable');
iCable = iCable(iSorted);

iSorted = sortBlocksByNumber(blocks(iMooring),'mooring');
iMooring = iMooring(iSorted);

% Order blocks
ind = [iSimulation iBody iConstraint iPTO iCable iMooring];
blocks = blocks(ind);

%% Write input file
fid = fopen(['./' inputFile '.m'],'w');
fprintf(fid,'%% %s\r\n','WEC-Sim Input File, written with custom Simulink parameters');
fprintf(fid,'%% %s\r\n',string(datetime));

% create default classes to compare values against
simu = simulationClass();
waves = waveClass('');
body = bodyClass('');
constraint = constraintClass('');
pto = ptoClass('');
cable = cableClass('','constraint','pto');
mooring = mooringClass('');

%% Write each mask to an input file section
for i=1:length(blocks)
    names = get_param(blocks{i},'MaskNames');
    values = get_param(blocks{i},'MaskValues');
    visibilities = get_param(blocks{i},'MaskVisibilities');

    % Create struct with mask variable name/value pairs
    maskVars = struct();
    maskViz = struct();
    for j = 1:length(names)
        % check if the value should be converted from a string to a float
        tmp = str2num(values{j});
        if ~isempty(tmp)
            values{j} = str2num(values{j});
        end
        % convert matlab to string to write to input file correctly
        values{j} = mat2str(values{j});
        maskVars.(names{j}) = values{j};
        maskViz.(names{j}) = visibilities{j};
    end; clear j;

    if isfield(maskVars,'simu') && isfield(maskVars,'waves')
        % Block is Global Reference Frame
        fprintf(fid,'\r\n%s\r\n','%% Simulation Class');
        fprintf(fid,'simu = simulationClass(); \r\n');
        fprintf(fid,'simu.simMechanicsFile = ''%s.slx''; \r\n',bdroot);

        fprintf(fid,writeLineFromVar(simu, 'mode', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'explorer', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'startTime', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'rampTime', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'endTime', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'solver', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'dt', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'cicEndTime', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(simu, 'stateSpace', maskVars, maskViz, [], []));

        % Wave Information
        fprintf(fid,'\r\n%s\r\n','%% Wave Class');
        fprintf(fid,'waves = waveClass(%s); \r\n',maskVars.WaveClass);

        fprintf(fid,writeLineFromVar(waves, 'height', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(waves, 'period', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(waves, 'direction', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(waves, 'spread', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(waves, 'spectrumType', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(waves, 'option', maskVars, maskViz, [], 'bem'));
        fprintf(fid,writeLineFromVar(waves, 'spectrumFile', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(waves, 'phaseSeed', maskVars, maskViz, [], []));
        fprintf(fid,writeLineFromVar(waves, 'elevationFile', maskVars, maskViz, [], []));

    elseif isfield(maskVars,'body')
        % Block is a body
        fprintf(fid,'\r\n%s\r\n','%% Body Class');
        tmp = string(maskVars.body);
        num = str2num(extractBetween(tmp,strfind(tmp,'('),strfind(tmp,')'),'Boundaries','Exclusive'));
        fprintf(fid,'body(%d) = bodyClass(%s); \r\n',num,maskVars.h5File);

        fprintf(fid,writeLineFromVar(body, 'geometryFile', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'mass', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'inertia', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'nonHydro', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'nonlinearHydro', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'flex', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'centerGravity', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'centerBuoyancy', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'dof', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'volume', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(body, 'displacement', maskVars, maskViz, num, 'initial'));
        fprintf(fid,writeLineFromVar(body, 'axis', maskVars, maskViz, num, 'initial'));
        fprintf(fid,writeLineFromVar(body, 'angle', maskVars, maskViz, num, 'initial'));
        fprintf(fid,writeLineFromVar(body, 'option', maskVars, maskViz, num, 'morisonElement'));
        fprintf(fid,writeLineFromVar(body, 'cd', maskVars, maskViz, num, 'morisonElement'));
        fprintf(fid,writeLineFromVar(body, 'ca', maskVars, maskViz, num, 'morisonElement'));
        fprintf(fid,writeLineFromVar(body, 'area', maskVars, maskViz, num, 'morisonElement'));
        fprintf(fid,writeLineFromVar(body, 'VME', maskVars, maskViz, num, 'morisonElement'));
        fprintf(fid,writeLineFromVar(body, 'rgME', maskVars, maskViz, num, 'morisonElement'));
        fprintf(fid,writeLineFromVar(body, 'z', maskVars, maskViz, num, 'morisonElement'));

    elseif isfield(maskVars,'constraint')
        % Block is a constraint
        fprintf(fid,'\r\n%s\r\n','%% Constraint Class');
        tmp = string(maskVars.constraint);
        num = str2num(extractBetween(tmp,strfind(tmp,'('),strfind(tmp,')'),'Boundaries','Exclusive'));
        fprintf(fid,'constraint(%d) = constraintClass(''constraint%d''); \r\n',num,num);

        fprintf(fid,['constraint(%d).location = ' maskVars.loc '; \r\n'],num);
        fprintf(fid,writeLineFromVar(constraint, 'y', maskVars, maskViz, num, 'orientation'));
        fprintf(fid,writeLineFromVar(constraint, 'z', maskVars, maskViz, num, 'orientation'));
        fprintf(fid,writeLineFromVar(constraint, 'displacement', maskVars, maskViz, num, 'initial'));
        fprintf(fid,writeLineFromVar(constraint, 'upperLimitSpecify', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'upperLimitBound', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'upperLimitStiffness', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'upperLimitDamping', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'upperLimitTransitionRegionWidth', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'lowerLimitSpecify', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'lowerLimitBound', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'lowerLimitStiffness', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'lowerLimitDamping', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(constraint, 'lowerLimitTransitionRegionWidth', maskVars, maskViz, num, 'hardStops'));

    elseif isfield(maskVars,'pto')
        % Block is a PTO
        fprintf(fid,'\r\n%s\r\n','%% PTO Class');
        tmp = string(maskVars.pto);
        num = str2num(extractBetween(tmp,strfind(tmp,'('),strfind(tmp,')'),'Boundaries','Exclusive'));
        fprintf(fid,'pto(%d) = ptoClass(''pto%d''); \r\n',num,num);

        fprintf(fid,writeLineFromVar(pto, 'stiffness', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(pto, 'damping', maskVars, maskViz, num, []));
        fprintf(fid,['pto(%d).location = ' maskVars.loc '; \r\n'],num);
        fprintf(fid,writeLineFromVar(pto, 'y', maskVars, maskViz, num, 'orientation'));
        fprintf(fid,writeLineFromVar(pto, 'z', maskVars, maskViz, num, 'orientation'));
        fprintf(fid,writeLineFromVar(pto, 'displacement', maskVars, maskViz, num, 'initial'));
        fprintf(fid,writeLineFromVar(pto, 'upperLimitSpecify', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'upperLimitBound', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'upperLimitStiffness', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'upperLimitDamping', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'upperLimitTransitionRegionWidth', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'lowerLimitSpecify', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'lowerLimitBound', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'lowerLimitStiffness', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'lowerLimitDamping', maskVars, maskViz, num, 'hardStops'));
        fprintf(fid,writeLineFromVar(pto, 'lowerLimitTransitionRegionWidth', maskVars, maskViz, num, 'hardStops'));

    elseif isfield(maskVars,'cable')
        % Block is a cable
        fprintf(fid,'\r\n%s\r\n','%% Cable Class');
        tmp = string(maskVars.cable);
        num = str2num(extractBetween(tmp,strfind(tmp,'('),strfind(tmp,')'),'Boundaries','Exclusive'));
        fprintf(fid,'cable(%d) = cableClass(''cable%d'',%s,%s); \r\n',num,num,...
            maskVars.baseName,maskVars.followerName);
        fprintf(fid,writeLineFromVar(cable, 'stiffness', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(cable, 'damping', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(cable, 'L0', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(cable, 'preTension', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(cable, 'y', maskVars, maskViz, num, 'orientation'));
        fprintf(fid,writeLineFromVar(cable, 'z', maskVars, maskViz, num, 'orientation'));
        fprintf(fid,writeLineFromVar(cable, 'displacement', maskVars, maskViz, num, 'initial'));
        fprintf(fid,writeLineFromVar(cable, 'axis', maskVars, maskViz, num, 'initial'));
        fprintf(fid,writeLineFromVar(cable, 'angle', maskVars, maskViz, num, 'initial'));

    elseif isfield(maskVars,'mooring') && isfield(maskVars,'stiffness')
        % Block is a Mooring system
        fprintf(fid,'\r\n%s\r\n','%% Mooring Class');
        tmp = string(maskVars.mooring);
        num = str2num(extractBetween(tmp,strfind(tmp,'('),strfind(tmp,')'),'Boundaries','Exclusive'));

        fprintf(fid,'mooring(%d) = mooringClass(''mooring%d''); \r\n',num,num);
        fprintf(fid,['mooring(%d).location = ' maskVars.loc '; \r\n'],num);
        fprintf(fid,writeLineFromVar(mooring, 'stiffness', maskVars, maskViz, num, 'matrix'));
        fprintf(fid,writeLineFromVar(mooring, 'damping', maskVars, maskViz, num, 'matrix'));
        fprintf(fid,writeLineFromVar(mooring, 'preTension', maskVars, maskViz, num, 'matrix'));

    elseif isfield(maskVars,'mooring') && isfield(maskVars,'moorDynlines')
        % Block is a Mooring system
        fprintf(fid,'\r\n%s\r\n','%% Mooring Class');
        tmp = string(maskVars.mooring);
        num = str2num(extractBetween(tmp,strfind(tmp,'('),strfind(tmp,')'),'Boundaries','Exclusive'));
        fprintf(fid,'mooring(%d) = mooringClass(''mooring%d''); \r\n',num,num);
        fprintf(fid,['mooring(%d).location = ' maskVars.loc '; \r\n'],num);
        fprintf(fid,writeLineFromVar(mooring, 'moorDynLines', maskVars, maskViz, num, []));
        fprintf(fid,writeLineFromVar(mooring, 'moorDynNodes', maskVars, maskViz, num, []));
    end
    clear names values maskVars
end

fclose(fid);

end

function iSorted = sortBlocksByNumber(blockList, className)
    % This function takes in a list of blocks (bodies or ptos or
    % constraints, but not bodies and ptos, etc) and orders the blocks
    % based on the class number
    classNums = [];
    for i=1:length(blockList)
        mask = Simulink.Mask.get(blockList{i});
        tmp = string(mask.getParameter(className).Value);
        num = str2num(extractBetween(tmp,strfind(tmp,'('),strfind(tmp,')'),'Boundaries','Exclusive'));
        classNums(i) = num;
    end
    [~,iSorted] = sort(classNums,'ascend');

end


text:
function varargout = sample(f, varargin)
%SAMPLE   Sample a CLASSICFUN on an "appropriate" grid.
%   VALUES = SAMPLE(F, N) returns a vector VALUES of the values of F at N
%   "appropriately-chosen" points.  What "appropriately-chosen" means depends
%   on the type of representation on which F is ultimately based.
%
%   [VALUES, POINTS] = SAMPLE(F, N) returns also the vector POINTS at which the
%   values were computed.
%
%   [...] = SAMPLE(F) uses N = LENGTH(F).

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

    [varargout{1:nargout}] = sample(f.onefun, varargin{:});
    if ( nargout > 1 )
        varargout{2} = f.mapping.For(varargout{2});
    end
end


text:
clc
clear all

source_dir = 'D:\Graduate\Comparison\Comparison_IAFusion\Dataset\RoadScene_VI';
save_dir = 'D:\Graduate\Comparison\Comparison_IAFusion\Dataset\RoadScene_vi1';
if exist(save_dir,'dir')==0.
	 mkdir(save_dir);
end
fileFolder=fullfile(source_dir);
dirOutput=dir(fullfile(source_dir,'*.bmp'));
fileNames = {dirOutput.name};
[m, num] = size(fileNames);
for i = 1:num
    fileName_source = fullfile(source_dir, fileNames{i})
    save_name = fullfile(save_dir, fileNames{i});
    source_image = imread(fileName_source);
    [h, w, c]=size(source_image)
    if c > 1
        source_image = rgb2gray(source_image);
    end
    save_image = source_image(1:floor(h/4) *4, 1:floor(w/4)*4);
    [h1, w1]=size(save_image)
    imwrite(save_image, save_name)
end

author: Linfeng-Tang

repo: Image-Fusion


text:
function results_image = PTKGetPrunedAirwayImageFromCentreline(parent_bronchi, child_bronchi, airway_root, template, colour_by_segment_index)
    % PTKGetPrunedAirwayImageFromCentreline.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD Pulmonary Toolkit. https://github.com/tomdoel/pulmonarytoolkit
    %     Author: Tom Doel, 2012.  www.tomdoel.com
    %     Distributed under the GNU GPL v3 licence. Please see website for details.
    %

    airways_image = PTKGetAirwayImageFromCentreline(parent_bronchi, airway_root, template, colour_by_segment_index);
    airways_image_child = PTKGetAirwayImageFromCentreline(child_bronchi, airway_root, template, colour_by_segment_index);

    results_image = airways_image.BlankCopy;
    results_image_raw = airways_image.RawImage;
    results_image_raw(airways_image_child.RawImage ~= 7) = 0;
    results_image.ChangeRawImage(results_image_raw);
    results_image.ImageType = PTKImageType.Colormap;
end

author: tomdoel

repo: pulmonarytoolkit


text:
%% This code allows complete manual reselection of every corner in the
%% images.
%% This tool is specifically useful in the case of highly distorted images.
%%
%% Use it when in memory efficient mode.
%% In standard mode, use manual_corner_extraction.m

if ~exist('n_ima'),
   fprintf(1,'No image data available\n');
   return;
end;

check_active_images;

if n_ima == 0,

    fprintf(1,'No image data available\n');

else

%if ~exist(['I_' num2str(ind_active(1))]),
%   n_ima_save = n_ima;
%   active_images_save = active_images;
%   ima_read_calib;
%   n_ima = n_ima_save;
%   active_images = active_images_save;
%   check_active_images;
%   if no_image_file,
%      disp('Cannot extract corners without images');
%      return;
%   end;
%end;

fprintf(1,'\nManual re-extraction of the grid corners on the images\n');

q_converge = input('Do you want to try to automatically find the closest corner? - only works with ckecker board corners  ([]=yes, other = no)','s');

if isempty(q_converge),
    q_converge = 1;
    fprintf(1,'Automatic refinement of the corner location after manual mouse click\n');
    disp('Window size for corner finder (wintx and winty):');
    wintx = input('wintx ([] = 5) = ');
    if isempty(wintx), wintx = 5; end;
    wintx = round(wintx);
    winty = input('winty ([] = 5) = ');
    if isempty(winty), winty = 5; end;
    winty = round(winty);

    fprintf(1,'Window size = %dx%d\n',2*wintx+1,2*winty+1);
else
    q_converge = 0;
    fprintf(1,'No attempt to refine the corner location after manual mouse click\n');
end;

ima_numbers = input('Number(s) of image(s) to process ([] = all images) = ');

if isempty(ima_numbers),
   ima_proc = 1:n_ima;
else
   ima_proc = ima_numbers;
end;

fprintf(1,'Processing image ');

for kk = ima_proc;

    if active_images(kk),

        fprintf(1,'%d...',kk);

        if ~type_numbering,
            number_ext =  num2str(image_numbers(kk));
        else
            number_ext = sprintf(['%.' num2str(N_slots) 'd'],image_numbers(kk));
        end;

        ima_name = [calib_name  number_ext '.' format_image];

        if exist(ima_name),

            if format_image(1) == 'p',
                if format_image(2) == 'p',
                    I = double(loadppm(ima_name));
                else
                    I = double(loadpgm(ima_name));
                end;
            else
                if format_image(1) == 'r',
                    I = readras(ima_name);
                else
                    I = double(imread(ima_name));
                end;
            end;

            if size(I,3)>1,
                I = 0.299 * I(:,:,1) + 0.5870 * I(:,:,2) + 0.114 * I(:,:,3);
            end;

            [ny,nx,junk] = size(I);

            eval(['x = x_' num2str(kk) ';']);

            Np = size(x,2);

            figure(2);
            image(I);
            colormap(map);
            hold on;
            hx = plot(x(1,:)+1,x(2,:)+1,'r+');
            hcp = plot(x(1,1)+1,x(2,1)+1,'co');
            hold off;

            for np = 1:Np,

                set(hcp,'Xdata',x(1,np)+1,'Ydata',x(2,np)+1);

                title(['Click on corner #' num2str(np) ' out of ' num2str(Np) ' (right button: keep point unchanged)']);

                [xi,yi,b] = ginput4(1);

                if b==1,
                    xxi = [xi;yi];
                    if q_converge,
                        [xxi] = cornerfinder(xxi,I,winty,wintx);
                    end;
                    x(1,np) = xxi(1) - 1;
                    x(2,np) = xxi(2) - 1;
                    set(hx,'Xdata',x(1,:)+1,'Ydata',x(2,:)+1);
                end;

            end;

            eval(['wintx_' num2str(kk) ' = wintx;']);
            eval(['winty_' num2str(kk) ' = winty;']);

            eval(['x_' num2str(kk) '= x;']);

        else
            fprintf(1,'Image %s not found!!!...',ima_name);
        end;

    else

        if ~exist(['omc_' num2str(kk)]),

            eval(['dX_' num2str(kk) ' = NaN;']);
            eval(['dY_' num2str(kk) ' = NaN;']);

            eval(['wintx_' num2str(kk) ' = NaN;']);
            eval(['winty_' num2str(kk) ' = NaN;']);

            eval(['x_' num2str(kk) ' = NaN*ones(2,1);']);
            eval(['X_' num2str(kk) ' = NaN*ones(3,1);']);

            eval(['n_sq_x_' num2str(kk) ' = NaN;']);
            eval(['n_sq_y_' num2str(kk) ' = NaN;']);

        end;

    end;

end;

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

end;

repo: ekfmonoslam


text:
%SE2 Representation of 2D rigid-body motion
%
% This subclasss of RTBPose is an object that represents rigid-body motion in 2D.
% Internally this is a 3x3 homogeneous transformation matrix (3x3) belonging to
% the group SE(2).
%
% Constructor methods::
%  SE2          general constructor
%  SE2.exp      exponentiate an se(2) matrix
%  SE2.rand     random transformation
%  new          new SE2 object
%
% Display and print methods::
%  animate          ^graphically animate coordinate frame for pose
%  display          ^print the pose in human readable matrix form
%  plot             ^graphically display coordinate frame for pose
%  print            ^print the pose in single line format
%
% Group operations::
%  *            ^mtimes: multiplication (group operator, transform point)
%  /            ^mrdivide: multiply by inverse
%  ^            ^mpower: exponentiate (integer only):
%  inv          inverse
%  prod         ^product of elements
%
% Methods::
%  det          determinant of matrix component
%  eig          eigenvalues of matrix component
%  log          logarithm of rotation matrix
%  inv          inverse
%  simplify*    apply symbolic simplication to all elements
%  interp       interpolate between poses
%  theta        rotation angle
%
% Information and test methods::
%  dim          ^returns 2
%  isSE         ^returns true
%  issym        ^test if rotation matrix has symbolic elements
%  SE2.isa      test if matrix is SE(2)
%
% Conversion methods::
%  char*         convert to human readable matrix as a string
%  SE2.convert   convert SE2 object or SE(2) matrix to SE2 object
%  double        convert to rotation matrix
%  R             convert to rotation matrix
%  SE3           convert to SE3 object with zero translation
%  SO2           convert rotational part to SO2 object
%  T             convert to homogeneous transformation matrix
%  Twist         convert to Twist object
%  t             get.t: convert to translation column vector
%
% Compatibility methods::
%  isrot2       ^returns false
%  ishomog2     ^returns true
%  tr2rt        ^convert to rotation matrix and translation vector
%  t2r          ^convert to rotation matrix
%  transl2      ^translation as a row vector
%  trprint2     ^print single line representation
%  trplot2      ^plot coordinate frame
%  tranimate2   ^animate coordinate frame
%
% ^ inherited from RTBPose class.
%
% See also SO2, SE3, RTBPose.

% Copyright (C) 1993-2019 Peter I. Corke
%
% This file is part of The Spatial Math Toolbox for MATLAB (SMTB).
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
% of the Software, and to permit persons to whom the Software is furnished to do
% so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
% FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
% COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
% IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%
% https://github.com/petercorke/spatial-math

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

classdef SE2 < SO2

    properties (Dependent = true)
        t
    end

    methods

        function obj = SE2(varargin)
            %SE2.SE2 Construct an SE(2) object
            %
            % Constructs an SE(2) pose object that contains a 3x3 homogeneous transformation
            % matrix.
            %
            % T = SE2() is the identity element, a null motion.
            %
            % T = SE2(X, Y) is an object representing pure translation defined by X and Y.
            %
            % T = SE2(XY) is an object representing pure translation defined by XY
            % (2x1). If XY (Nx2) returns an array of SE2 objects, corresponding to
            % the rows of XY.
            %
            % T = SE2(X, Y, THETA) is an object representing translation, X and Y, and
            % rotation, angle THETA.
            %
            % T = SE2(XY, THETA) is an object representing translation, XY (2x1), and
            % rotation, angle THETA.
            %
            % T = SE2(XYT) is an object representing translation, XYT(1) and XYT(2),
            % and rotation angle XYT(3). If XYT (Nx3) returns an array of SE2 objects, corresponding to
            % the rows of XYT.
            %
            % T = SE2(T) is an object representing translation and rotation defined by
            % the SE(2) homogeneous transformation matrix T (3x3).  If T (3x3xN) returns an
            % array (1xN) of SE2 objects, corresponding to the third index of T.
            %
            % T = SE2(R) is an object representing pure rotation defined by the
            % SO(2) rotation matrix R (2x2)
            %
            % T = SE2(R, XY) is an object representing rotation defined by the
            % orthonormal rotation matrix R (2x2) and position given by XY (2x1)
            %
            % T = SE2(T) is a copy of the SE2 object T. If T (Nx1) returns an array of SE2 objects,
            % corresponding to the index of T.
            %
            % Options::
            % 'deg'         Angle is specified in degrees
            %
            % Notes::
            % - Arguments can be symbolic
            % - The form SE2(XY) is ambiguous with SE2(R) if XY has 2 rows, the second form is assumed.
            % - The form SE2(XYT) is ambiguous with SE2(T) if XYT has 3 rows, the second form is assumed.
            % - R and T are checked to be valid SO(2) or SE(2) matrices.

            opt.deg = false;

            [opt,args] = tb_optparse(opt, varargin);

            if opt.deg
                scale = pi/180.0;
            else
                scale = 1;
            end

            % if any of the arguments is symbolic the result will be symbolic
            if any( cellfun(@(x) isa(x, 'sym'), args) )
                obj.data = sym(obj.data);
            end

            obj.data = eye(3,3);

            switch length(args)
                case 0
                    % null motion
                    return
                case 1
                    % 1 argument
                    a = args{1};

                    if isvec(a, 2)
                        % (t)
                        obj.data = [ 1 0 a(1); 0 1 a(2); 0 0 1];

                    elseif isvec(a, 3)
                        % ([x y th])
                        a = a(:);
                        obj.data(1:2,1:2) = rot2(a(3)*scale);
                        obj.t = a(1:2);

                    elseif SO2.isa(a)
                        % (R)
                        obj.data(1:2,1:2) = a;

                    elseif SE2.isa(a)
                        % (T)
                        for i=1:size(a, 3)
                            obj(i).data = a(:,:,i);
                        end
                    elseif isa(a, 'SE2')
                        % (SE2)
                        for i=1:length(a)
                            obj(i).data = a(i).data;
                        end

                    elseif any( numcols(a) == [2 3] )
                        for i=1:numrows(a)
                            obj(i) = SE2(a(i,:));
                        end
                        return
                    else
                        error('SMTB:SE2:badarg', 'unknown arguments');
                    end

                case 2
                    % 2 arguments
                    a = args{1}; b = args{2};
                    if isscalar(a) && isscalar(b)
                        % (x,y)
                        obj.data = [ 1 0 a; 0 1 b; 0 0 1];
                    elseif isvec(a,2) && isscalar(b)
                        % ([x y], th)
                        obj.data = [ rot2(b*scale) a(:); 0 0 1];
                    elseif SO2.isa(a) && isvec(b,2)
                        % (R, t)
                        obj.data = [a b(:); 0 0 1];
                    else
                        error('SMTB:SE3:badarg', 'unknown arguments');
                    end

                case 3
                    % 3 arguments
                    a = args{1}; b = args{2}; c = args{3};
                    if isscalar(a) && isscalar(b) && isscalar(c)
                        % (x, y, th)
                        obj.data = [ rot2(c*scale) [a b]'; 0 0 1];
                    else
                        error('SMTB:SE3:badarg', 'unknown arguments');
                    end
                otherwise
                    error('SMTB:SE3:badarg', 'unknown arguments');

            end

            % add the last row if required
%             if numrows(obj.data) == 2
%                 obj.data = [obj.data; 0 0 1];
%             end
            assert(all(size(obj(1).data) == [3 3]), 'SMTB:SE2:SE2', 'created wrong size data element');
            %% HACK
        end

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %  GET AND SET
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        function t = get.t(obj)
            %SE2.t  Get translational component
            %
            % P.t is a column vector (2x1) representing the translational component of
            % the rigid-body motion described by the SE2 object P.
            %
            % Notes::
            % - If P is a vector the result is a MATLAB comma separated list, in this
            %   case use P.transl().
            %
            % See also SE2.transl.
            t = obj.data(1:2,3);
        end

        function o = set.t(obj, t)
            %SE2.t  Set translational component
            %
            % P.t = TV sets the translational component of the rigid-body motion
            % described by the SE2 object P to TV (2x1).
            %
            % Notes::
            % - TV can be a row or column vector.
            % - If TV contains a symbolic value then the entire matrix becomes
            %   symbolic.

            if isa(t, 'sym') && ~isa(obj.data, 'sym')
                obj.data = sym(obj.data);
            end
            obj.data(1:2,3) = t;
            o = obj;
        end

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%  conversion methods
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        function v = xyt(obj)
            %SE2.xyt  Extract configuration
            %
            % XYT = P.xyt() is a column vector (3x1) comprising the minimum three
            % configuration parameters of this rigid-body motion: translation (x,y)
            % and rotation theta.

            % TODO VECTORISE
            v = obj.t;
            v(3) = atan2(obj.data(2,1), obj.data(1,1));
        end

        function [tx,ty] = transl(obj)
            %SE2.t  Get translational component
            %
            % TV = P.transl() is a row vector (1x2) representing the translational component of
            % the rigid-body motion described by the SE2 object P.  If P is a vector of
            % objects (1xN) then TV (Nx2) will have one row per object element.

            if nargout == 1 || nargout == 0
                tx = [obj.t]';
            else
                t = obj.t;
                tx = t(1);
                ty = t(2);
            end
        end

        function T = T(obj)
            %SE2.T  Get homogeneous transformation matrix
            %
            % T = P.T() is the homogeneous transformation matrix (3x3) associated with the
            % SE2 object P, and has zero translational component.  If P is a vector
            % (1xN) then T (3x3xN) is a stack of homogeneous transformation matrices, with the third
            % dimension corresponding to the index of P.
            %
            % See also SO2.T.
            for i=1:length(obj)
                T(:,:,i) = obj(i).data;
            end
        end

        function t = SE3(obj)
            %SE2.SE3 Lift to 3D
            %
            % Q = P.SE3() is an SE3 object formed by lifting the rigid-body motion
            % described by the SE2 object P from 2D to 3D.  The rotation is about the
            % z-axis, and the translation is within the xy-plane.
            %
            % See also SE3.
            t = SE3();
            t.data(1:2,1:2) = obj.data(1:2,1:2);
            t.data(1:2,4) = obj.data(1:2,3);
        end

        function out = SO2(obj)
            %SE2.SO2  Extract SO(2) rotation
            %
            % Q = SO2(P) is an SO2 object that represents the rotational component of
            % the SE2 rigid-body motion.
            %
            % See also SE2.R.

            out = SO2( obj.R );
        end

        function tw = Twist(obj)
            %SE2.Twist  Convert to Twist object
            %
            % TW = P.Twist() is the equivalent Twist object.  The elements of the twist are the unique
            % elements of the Lie algebra of the SE2 object P.
            %
            % See also SE2.log, Twist.
            tw = Twist( obj.log );
        end

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%  SE(2) OPERATIONS
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        function it = inv(obj)
            %SE2.inv  Inverse of SE2 object
            %
            % Q = inv(P) is the inverse of the SE2 object P.
            %
            % Notes::
            %  - This is formed explicitly, no matrix inverse required.
            %  - This is a group operator: input and output in the SE(2) group.
            %  - P*Q will be the identity group element (zero motion, identity matrix).

            it = SE2( obj.R', -obj.R'*obj.t);
        end

        function S = log(obj)
            %SE2.log  Lie algebra
            %
            % se2 = P.log() is the Lie algebra corresponding to the SE2 object P. It is
            % an augmented skew-symmetric matrix (3x3).
            %
            % See also SE2.Twist, logm, skewa, vexa.
            S = logm(obj.data);
        end

        function Ti = interp(obj1, varargin)
            %SE2.interp Interpolate between SO2 objects
            %
            % P1.interp(P2, s) is an SE2 object which is an interpolation
            % between poses represented by SE2 objects P1 and P2.  s varies from 0
            % (P1) to 1 (P2). If s is a vector (1xN) then the result will be a vector
            % of SE2 objects.
            %
            % Notes::
            % - It is an error if S is outside the interval 0 to 1.
            %
            % See also SO2.angle.

            if isa(varargin{1}, 'SE2')
                % interp(SE2, SE2, s)  interpolate between given values
                obj2 = varargin{1};
                varargin = varargin(2:end);
                try
                    Ti = SE2( trinterp2(obj1.T, obj2.T, varargin{:}) );
                catch me
                    switch me.identifier
                        case 'SMTB:trinterp2:badarg'
                            throw( MException('SMTB:SE2:interp:badarg', 'value of S outside interval [0,1]') );
                        otherwise
                            rethrow(me);
                    end
                end
            else
                % interp(SE2, s)  interpolate between null and given value
                try
                    Ti = SE2( trinterp2( obj1.T, varargin{:}) );
                catch me
                    switch me.identifier
                        case 'SMTB:trinterp2:badarg'
                            throw( MException('SMTB:SE2:interp:badarg', 'value of S outside interval [0,1]') );
                        otherwise
                            rethrow(me);
                    end
                end
            end

        end

        function print(obj, varargin)
            for T=obj
                theta = atan2(T.data(2,1), T.data(1,1)) * 180/pi;
                fprintf('t = (%.4g, %.4g), theta = %.4g deg\n', T.t, theta);
            end
        end

        function n = new(obj, varargin)
            %SE2.new  Construct a new object of the same type
            %
            % P2 = P.new(X) creates a new object of the same type as P, by invoking the SE2 constructor on the matrix
            % X (3x3).
            %
            % P2 = P.new() as above but defines a null motion.
            %
            % Notes::
            %  - Serves as a dynamic constructor.
            %  - This method is polymorphic across all RTBPose derived classes, and
            %    allows easy creation of a new object of the same class as an existing
            %    one without needing to explicitly determine its type.
            %
            % See also SE3.new, SO3.new, SO2.new.

            n = SE2(varargin{:});
        end

    end

    methods (Static)
        % Static factory methods for constructors from exotic representations

        function obj = exp(s)
            %SE2.exp  Construct SE2 from Lie algebra
            %
            % SE2.exp(SIGMA) is the SE2 rigid-body motion corresponding to the se(2)
            % Lie algebra element SIGMA (3x3).
            %
            % SE3.exp(TW) as above but the Lie algebra is represented
            % as a twist vector TW (1x1).
            %
            % Notes::
            %  - TW is the non-zero elements of X.
            %
            % Reference::
            % - Robotics, Vision & Control: Second Edition, P. Corke, Springer 2016; p25-31.
            %
            %
            % See also trexp2, skewa.

            obj = SE2( trexp2(s) );
        end

        function T = convert(tr)
            %SE2.check  Convert to SE2
            %
            % Q = SE2.convert(X) is an SE2 object equivalent to X where X is either
            % an SE2 object, or an SE(2) homogeneous transformation matrix (3x3).
            if isa(tr, 'SE2')
                T = tr;
            elseif SE2.isa(tr)
                T = SE2(tr);
            else
                error('expecting an SE2 or 3x3 matrix');
            end
        end

        function h = isa(tr, rtest)
            %SE2.ISA Test if matrix is SE(2)
            %
            % SE2.isa(T) is true (1) if the argument T is of dimension 3x3 or 3x3xN, else
            % false (0).
            %
            % SE2.isa(T, true) as above, but also checks the validity of the rotation
            % sub-matrix.
            %
            % Notes::
            %  - This is a class method.
            %  - The first form is a fast, but incomplete, test for a transform in SE(3).
            %  - There is ambiguity in the dimensions of SE2 and SO3 in matrix form.
            %
            % See also SO3.ISA, SE2.ISA, SO2.ISA, ishomog2.

            d = size(tr);
            if ndims(tr) >= 2
                h =  all(d(1:2) == [3 3]);

                if h && nargin > 1 && ~isa(tr, 'sym')
                    h = SO3.isa( tr(1:2,1:2) );
                    h = h && all(tr(4,:) == [0 0 0 1]);  % test the bottom row
                end
            else
                h = false;
            end
        end

        function T = rand()
            %SE2.rand Construct a random SE(2) object
            %
            % SE2.rand() is an SE2 object with a uniform random translation and a
            % uniform random orientation.  Random numbers are in the interval [-1 1]
            % and rotations in the interval [-pi pi].
            %
            % See also RAND.
            T = SE2(rand(1,3)*diag([2 2 2*pi]) + [-1 -1 -pi]);
        end
    end
end

author: petercorke

repo: spatialmath-matlab


text:
%
% Stochastic function that generates new examples from the prior,
% given a type-level specification from generate_character().
%
% Input
%  template: MotorProgram class with R,ids,shapes_type,invscales_types
%    defined
%
% Output
%  M: fully-specified MotorProgram
function [M,template] = generate_exemplar(template,libclass)

    M = MotorProgram(template);

    % sample stroke parameters
    for i=1:M.ns
        if strcmp(M.S{i}.R.type,'mid')
            M.S{i}.R.eval_spot_token = CPD.sample_relation_token(libclass,M.S{i}.R.eval_spot_type);
        end
        M.S{i}.pos_token = CPD.sample_position(libclass,M.S{i}.R,M.S(1:i-1));
        M.S{i}.shapes_token = CPD.sample_shape_token(libclass,M.S{i}.shapes_type);
        M.S{i}.invscales_token = CPD.sample_invscale_token(libclass,M.S{i}.invscales_type);
    end

    % sample affine warp
    M.A = CPD.sample_affine(libclass);

    % set rendering parameters to minimum noise
    M.blur_sigma = template.parameters.min_blur_sigma;
    M.epsilon = template.parameters.min_epsilon;

    % sample rendering parameters
    %M.blur_sigma = CPD.sample_image_blur(template.parameters);
    %M.epsilon = CPD.sample_image_noise(template.parameters);

    % sample the image
    M.I = CPD.sample_image(M.pimg);

end

author: brendenlake

repo: BPL

save_path: github-repos/MATLAB/brendenlake-BPL


text:
function [MSE, PSNR] = Calc_MSE_PSNR(clean,denoised)
% Compute MSE and PSNR.
%
% clean: inputted clean image
% denoised: inputted denoised image
% MSE: outputted mean squared error
% PSNR: outputted peak signal-to-noise ratio
%
% Author: Zhou Dengwen
% zdw@ncepu.edu.cn
% Department of Computer Science & Technology
% North China Electric Power University(Beijing)(NCEPU)
%
% Last time modified: Jul. 15, 2008
%

N = prod(size(clean));
clean = double(clean(:)); denoised = double(denoised(:));
t1 = sum((clean-denoised).^2); t2 = sum(clean.^2);
MSE = t1/N;
PSNR = 10*log10(255*255/MSE);

author: Sable

repo: mcbench-benchmarks


text:
disp('Installing proxTV with no multi-thread support...');
cd src
mex -lmwblas -lmwlapack -lm CXXOPTIMFLAGS=-O3 CXXFLAGS="\$CFLAGS" LDFLAGS="\$LDFLAGS" solveTV1_PNc.cpp TVopt.cpp
mex -lmwblas -llapack -lm CXXOPTIMFLAGS=-O3 CXXFLAGS="\$CFLAGS" LDFLAGS="\$LDFLAGS" solveTV2_morec2.cpp TVopt.cpp
mex -lmwblas -llapack -lm CXXOPTIMFLAGS=-O3 CXXFLAGS="\$CFLAGS" LDFLAGS="\$LDFLAGS" solveTVgen_PDykstrac.cpp TVopt.cpp
cd ..
disp('proxTV successfully installed.');

author: beckel

repo: nilm-eval

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


text:
function prob = logitFn(paramS,doseBinsC,volHistC)
% function prob = logitFn(paramS,doseBinsC,volHistC);
% This function returns the outcomes probabilities based on logistic fit.
%----------------------------------------------------------------------------
% INPUT parameters:
% paramS:
% Specify the variates using the following format:
% paramS.field1.val = 1;
% paramS.field1.weight = 2;
% paramS.field1.val can also be a string, in which case it will act as a
% function name. This function must have the signature
% x(doseBinsV,volHistV).
%---------------------------------------------------------------------------
% APA, 02/15/2017
% AI, 02/21/17
% AI , 11/14/17  Created separate function for appelt model
% AI, 11/16/17   Copy number of fractions, abRatio to any sub-parameter structures

%Extract parameters and corresponding weights
[weight,x] = getParCoeff(paramS,'weight',doseBinsC,volHistC);
%Compute TCP/NTCP
gx = sum(weight.*x);
prob = 1 / (1 + exp(-gx));

%%--- Functions to extract model parameters and weights ----
    function [coeff,par] = getParCoeff(paramS,fieldName,doseBinsC,volHistC)

        %Extract relevant parameters
        genFieldC = fields(paramS);
        for i = 1:numel(genFieldC)
            if strcmpi(genFieldC{i},'structures')
                structS = paramS.(genFieldC{i});
                structListC = fieldnames(structS);
                for j = 1:length(structListC)
                    strParamS = structS.(structListC{j});
                    strParamListC = fieldnames(strParamS);
                    for k = 1 : numel(strParamListC)
                        if isfield(strParamS.(strParamListC{k}),'cteg') |  isfield(strParamS.(strParamListC{k}),'weight')
                            parName = [structListC{j},strParamListC{k}];
                            keepParS.(parName) = strParamS.(strParamListC{k});
                        end
                    end
                end
            else
                 if isfield(paramS.(genFieldC{i}),'cteg') |  isfield(paramS.(genFieldC{i}),'weight')
                     parName = genFieldC{i};
                     keepParS.(parName) = paramS.(genFieldC{i});
                 end
            end
        end

       %Compute parameters, extract coefficients
        keepParC = fieldnames(keepParS);
        numStr = 0;
        par = zeros(1,length(keepParC));
        coeff = zeros(1,length(keepParC));
        for n = 1:length(keepParC)
            coeff(n) = keepParS.(keepParC{n}).(fieldName);
            if isnumeric(keepParS.(keepParC{n}).val)
               par(n) = keepParS.(keepParC{n}).val;
            else
                if ~iscell(doseBinsC)  %For single-structure models
                    doseBinsV = doseBinsC;
                    volHistV = volHistC;
                else
                numStr = numStr+1;
                doseBinsV = doseBinsC{numStr};
                volHistV = volHistC{numStr};
                end
                if ~isfield(keepParS.(keepParC{n}),'params')
                    par(n) = eval([keepParS.(keepParC{n}).val,...
                        '(doseBinsV, volHistV)']);
                else
                    %Copy number fo fractions, abRatio
                    if isfield(paramS,'numFractions')
                        keepParS.(keepParC{n}).params.numFractions.val = paramS.numFractions.val;
                    end
                    if isfield(paramS,'abRatio')
                        keepParS.(keepParC{n}).params.abRatio.val = paramS.abRatio.val;
                    end
                    par(n) = eval([keepParS.(keepParC{n}).val,...
                        '(doseBinsV, volHistV,keepParS.(keepParC{n}).params)']);
                end
            end
        end
    end

end

author: cerr

repo: CERR

save_path: github-repos/MATLAB/cerr-CERR


text:
function sine_transform_test01 ( )

%*****************************************************************************80
%
%% SINE_TRANSFORM_TEST01 demonstrates that the transform is its own inverse.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 February 2012
%
%  Author:
%
%    John Burkardt
%
  n = 10;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'SINE_TRANSFORM_TEST01:\n' );
  fprintf ( 1, '  SINE_TRANSFORM_DATA does a sine transform of data\n' );
  fprintf ( 1, '  defined by a vector.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Demonstrate that the transform is its own inverse.\n' );
  fprintf ( 1, '  Let R be a random N vector.\n' );
  fprintf ( 1, '  Let S be the transform of D.\n' );
  fprintf ( 1, '  Let T be the transform of E.\n' );
  fprintf ( 1, '  Then R and T will be equal.\n' );

% r = rand ( n, 1 );
  seed = 123456789;
  [ r, seed ] = r8vec_uniform_01 ( n, seed );
  s = sine_transform_data ( n, r );
  t = sine_transform_data ( n, s );

  fprintf ( 1, '\n' );
  fprintf ( 1, '     I      R(I)        S(I)        T(I)\n' );
  fprintf ( 1, '\n' );

  for i = 1 : n
    fprintf ( 1, '  %4d  %10f  %10f  %10f\n', i, r(i), s(i), t(i) );
  end

  return
end


text:
% BOOKKEEPING - Updates the status of example indss and modifies the corresponding
%               coefficient a(indss) in certain cases to avoid numerical errors.
%
% Syntax: [indco,i] = bookkeeping(indss,cstatus,nstatus)
%
%     indco: matrix row/col to remove from Rs and Q if removing a margin vector
%         i: when i > 0, the i-th element was removed from ind{RESERVE}
%     indss: the example changing status
%   cstatus: current status of the example
%   nstatus: new status of the example
%
%            example status values:
%            1: margin vector
%            2: error vector
%            3: reserve vector
%            4: unlearned vector
%
% Version 3.22 -- Comments to diehl@alumni.cmu.edu
%

function [indco,i] = bookkeeping(indss,cstatus,nstatus)

indco = -1;
i = 0;
if (cstatus ~= nstatus)

	% flags for example state
	MARGIN    = 1;
	ERROR     = 2;
	RESERVE   = 3;
    UNLEARNED = 4;

	% define global variables
	global a;     % the alpha coefficients
	global C;     % regularization parameters
	global ind;   % cell array containing indices of margin, error, reserve and unlearned vectors

	% adjust coefficient to avoid numerical errors if necessary
	switch nstatus
	case RESERVE
	   a(indss) = 0;
	case ERROR
	   a(indss) = C(indss);
	end;

	% if the example is currently a margin vector, determine the row
	% in the extended kernel matrix inverse that needs to be removed
	if (cstatus == MARGIN)
   	indco = find(indss == ind{MARGIN}) + 1;
	end;

	% change the status of the example
	switch nstatus
	case RESERVE
   	[ind{cstatus},i] = move_indr(ind{cstatus},indss);
	otherwise
	   [ind{cstatus},ind{nstatus}] = move_ind(ind{cstatus},ind{nstatus},indss);
	end;

end;

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function [data] = iHOSVD(core, U)

site = size(core);
data = core;

for i=1:ndims(core)
    [m n] = size(U{i});
    site(i) = m;
    data = folding(U{i}*unfolding(data,i), i, site);
end

author: andrewssobral

repo: lrslibrary


text:
function d = distToEpipolarLine(F, p1, p2)
%% Given a fundamental matrix F, compute the matched point pair to their
% corresponding epipolarlines' distances, then sum the two distances.
% Extracted from Matlab built-in function estimateFundamentalMatrix.m

% Very important: F must map a point p1 to an epipolar line in p2 image space, not the other way around.
% More details: http://stackoverflow.com/questions/26582960/sampson-error-for-five-point-essential-matrix-estimation

%% License
% ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
% Copyright (c) 2018 Bingyao Huang
% All rights reserved.

% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:

% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.

% If you publish results obtained using this software, please cite our paper.

% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.

% convert to homogenious
p1 = [p1, ones(size(p1,1),1)]';
p2 = [p2, ones(size(p2,1),1)]';

% euclidean distance
d = sum(p2.*(F*p1), 1) .^ 2;

% sampson distance
epl1 = F * p1;
epl2 = F' * p2;
d = d ./ (epl1(1,:).^2 + epl1(2,:).^2 + epl2(1,:).^2 + epl2(2,:).^2);
end

author: BingyaoHuang

repo: single-shot-pro-cam-calib


text:
function axesLabelsAlign3D
% Note: This function is taken from internet.
%Author: M Arthington
%Date: 02/05/2010
%Set the x and y axis labels of the current axes to be aligned to
%the orientation of the axes.
%This is intended to be used when the rotate3d command has been used.
[az,el] = view;
Raz = [cosd(az) sind(az) 0;-sind(az) cosd(az) 0;0 0 1];
Rel = [1 0 0;0 cosd(el) -sind(el);0 sind(el) cosd(el)];
%Calculate current orientation of x and y axes in view coordinates
xax = Rel*Raz*[1;0;0];yax = Rel*Raz*[0;1;0];
%Project x and y into current viewing plane
n1=cross(xax,[0;1;0]);x = cross([0;1;0],n1);
n1=cross(yax,[0;1;0]);y = cross([0;1;0],n1);
%If the view will show this label, orientate it to be aligned with the
%axis direction. Otherwise set its rotation to 0 (default).
if any(x)
	set(get(gca,'xlabel'),'rotation',atand(x(3)/x(1)));
else
	set(get(gca,'xlabel'),'rotation',0);
end
if any(y)
	set(get(gca,'ylabel'),'rotation',atand(y(3)/y(1)));
else
	set(get(gca,'ylabel'),'rotation',0);
end

path: github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34985-monte-carlo-simulation-of-three-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 3D square-lattice - microstructure/axesLabelsAlign3D.m


text:
% addpath(genpath('./matlab'));
% caffe('init_finetune', '/home/winsty/caffe/examples/objectness/imagenet_deploy_solver.prototxt', '/media/windisk/imagenet_snapshot/caffe_objectness_train_iter_100000');
% tic;

% test single frame
caffe('set_batch_size', 1);

track_dir = dir('../trackingDataset');
track_dir = track_dir(3:52);
for i = 1:50
    dataname = track_dir(i).name;
    im = imread(['../trackingDataset/' dataname '/img/0001.jpg' ]);
    if strcmp(dataname,'Jogging')
        grt = importdata(['../trackingDataset/' dataname '/groundtruth_rect.1.txt']);
        %[x,y,width,height] = importdata(['../trackingDataset/' dataname '/groundtruth_rect.2.txt']);
        x = grt(1,1); y = grt(1,2);
        width = grt(1,3); height = grt(1,4);
    else
        grt = importdata(['../trackingDataset/' dataname '/groundtruth_rect.txt']);
        x = grt(1,1); y = grt(1,2);
        width = grt(1,3); height = grt(1,4);
    end

    padding_x = max(x-width/2,1); padding_y = max(y-height/2,1);
    w = min(2*width, size(im,2)-padding_x);
    h = min(2*height, size(im,1)-padding_y);
    crop_img = im(padding_y:(padding_y+h), padding_x:(padding_x+w), :);

    crop_img = im;
    crop_img = imresize(crop_img, [100,100]);
    crop_img = single(crop_img);
    if(size(crop_img,3) == 1)
    	crop_img = repmat(crop_img, [1,1,3]);
    end
    ori_img = crop_img/255;
    crop_img = crop_img(:,:,[3 2 1]) - 120;
    box = zeros(1,1,4,8,'single');
    image_batch = zeros(100,100,3,8,'single');
    image_batch(:,:,:,1) = permute(crop_img, [2,1,3]);

    % dummy target
    box(:, :, :, 1) = [0, 0, -1, -1];
    input = {image_batch; box};
    caffe('forward', input);
    fea = caffe('extract_feature', 'fc11');
    fea = fea{1};
    fea = reshape(fea(1 : 2500), [50, 50]);
    fea = 1 ./ (1 + exp(-fea));
    mask = imresize(fea',[100,100]);
    for k = 1:3
        masked(:,:,k) = min(ori_img(:,:,k), mask);
    end
    h  = figure; imshow([ori_img, masked]);
    saveas(h, [num2str(i) dataname '.jpg']);

end

author: flyers

repo: drone-tracking


text:
function voronoiStats=getVoronoiStats(Fv_cell,Vv,np,numBins)

%Replace infinite entries by NaN
Vv(isinf(Vv))=NaN;

%Allocate memory for structure
voronoiStats.ellipse=nan(numel(Fv_cell),5);
voronoiStats.ellipticity=nan(numel(Fv_cell),1);
voronoiStats.circularity=nan(numel(Fv_cell),1);
voronoiStats.angle=nan(numel(Fv_cell),1);
voronoiStats.area=nan(numel(Fv_cell),1);
voronoiStats.radii=cell(numel(Fv_cell),1);
voronoiStats.minRad=nan(numel(Fv_cell),1);
voronoiStats.maxRad=nan(numel(Fv_cell),1);
voronoiStats.meanRad=nan(numel(Fv_cell),1);

%Loop through cells to compute statistics
for q=1:1:numel(Fv_cell);

    %Get current Voronoi cell
    fv=Fv_cell{q};
    vv=Vv(fv,:);

    if ~isnan(vv(:))
        %Compute ellips and ellipticity
        [A] = ellipseFit(vv,2,np);

        a=A(3); b=A(4);
        if b<a %Oblate
            E=sqrt((a^2-b^2)./a^2);
        else %Prolate
            E=sqrt((b^2-a^2)./b^2);
        end

        %Compute radii
        x=vv(:,1);
        y=vv(:,2);
        xCentre = mean(x);
        yCentre = mean(y);
        x = (x-xCentre);
        y = (y-yCentre);
        R=sqrt(x.^2+y.^2);

        %Compute area
        vv_area=patch_area(fv,Vv);

        %Compute circularity
        C=polyCircularity(vv);

        %Compute angle
        ellipseAngle=A(end);
        ellipseAngle(ellipseAngle<0)=(2*pi+ellipseAngle(ellipseAngle<0))-pi;

        %Store in stucture
        voronoiStats.ellipse(q,:)=A;
        voronoiStats.ellipticity(q)=E;
        voronoiStats.circularity(q)=C;
        voronoiStats.angle(q)=ellipseAngle;
        voronoiStats.area(q)=vv_area;
        voronoiStats.radii{q}=R;
        voronoiStats.minRad(q)=min(R);
        voronoiStats.maxRad(q)=max(R);
        voronoiStats.meanRad(q)=mean(R);

    else %Set empty
        voronoiStats.ellipse(q,:)=nan;
        voronoiStats.ellipticity(q)=nan;
        voronoiStats.circularity(q)=nan;
        voronoiStats.angle(q)=nan;
        voronoiStats.area(q)=nan;
        voronoiStats.radii{q}=nan;
        voronoiStats.minRad(q)=nan;
        voronoiStats.maxRad(q)=nan;
        voronoiStats.meanRad(q)=nan;
    end
end

%% Compute histograms

E=voronoiStats.ellipticity;
E=E(~isnan(E));
hbE=linspace(min(E(:)),max(E(:)),numBins)';
hcE = histc(E,hbE);
hcE=hcE./size(E,1); %Normalize
voronoiStats.ellipticityHist.hc=hcE;
voronoiStats.ellipticityHist.hb=hbE;

E=voronoiStats.angle;
E=E(~isnan(E));
hbE=linspace(min(E(:)),max(E(:)),numBins)';
% hbE=linspace(0,pi,numBins)';
hcE = histc(E,hbE);
hcE=hcE./size(E,1); %Normalize
voronoiStats.angleHist.hc=hcE;
voronoiStats.angleHist.hb=hbE;

E=voronoiStats.area;
E=E(~isnan(E));
hbE=linspace(min(E(:)),max(E(:)),numBins)';
hcE = histc(E,hbE);
hcE=hcE./size(E,1); %Normalize
voronoiStats.areaHist.hc=hcE;
voronoiStats.areaHist.hb=hbE;

E=voronoiStats.circularity;
E=E(~isnan(E));
hbE=linspace(min(E(:)),max(E(:)),numBins)';
% hbE=linspace(0,1,numBins)';
hcE = histc(E,hbE);
hcE=hcE./size(E,1); %Normalize
voronoiStats.circularityHist.hc=hcE;
voronoiStats.circularityHist.hb=hbE;

E=voronoiStats.meanRad;
E=E(~isnan(E));
hbE=linspace(min(E(:)),max(E(:)),numBins)';
hcE = histc(E,hbE);
hcE=hcE./size(E,1); %Normalize
voronoiStats.meanRadHist.hc=hcE;
voronoiStats.meanRadHist.hb=hbE;

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function pic = pptInsertInSlide(op, img, pos, units, slide_num);
% Paste an image matrix into an existing PowerPoint slide at a user-specified
% position.
%
%   pic = pptInsertInSlide(op, img, pos, [units='normalized'], [slide_num=last slide]);
%
% INPUTS:
%	op: ActiveX operation for PowerPoint. You get this by calling pptOpen.
%	img: image matrix. Can be 2D (grayscale) or 3D (truecolor), or can be a
%		handle to a MATLAB figure containing the contents to be pasted.
%	pos: 4-element matrix specifying the position of the image in the
%		slide. The format is:
%			[top left corner X, top left corner Y, widht, height]
%	units: either 'pixels' or 'norm' (or 'normalized'). Specifies the units
%		in the pos argument. If 'pixels', the units are pixels down or to the left
%		of the top-left corner of the slide. If 'norm', units are
%		normalized to the slide width (e.g., 0=at the top/left corner, 1=at
%		the bottom/right corner, .5=halfway). [Default 'norm']
%	slide_num: optional specification of the slide in which to insert the
%		image. Can also be the slide object itself.
%		[defaults to last slide in the PPT.]
%
% OUTPUTS:
%	pic: Microsoft shape object representing the inserted picture.
%
% SEE: pptOpen, pptPaste, pptClose.
%
% ras, 10/2008.
if notDefined('op'),	error('Need to run pptOpen first.');		end
if notDefined('img'),	error('Need an image to insert.');			end
if notDefined('pos'),	error('Need a position for the image.');	end
if notDefined('units'),	units = 'norm';								end
if notDefined('slide_num'),	slide_num = get(op.Slides, 'Count');	end

% copy the image into the clipboard
if length(img)==1 & ishandle(img)
	% 'img' is actually a handle to a figure: copy this figure
	figure(img)
	print('-dbitmap');
else
	% copy by making a figure, copying the image, then closing the
	% figure:
	hFig = figure('Units', 'norm', 'Position', [0 0 1 1], 'Color', 'w');
	imshow(img);
	print('-dbitmap');
	close(hFig);
end

%% get the selected slide
% allow the user to hand in a slide object
classType = 'Interface.Microsoft_PowerPoint_11.0_Object_Library._Slide';
if isequal( class(slide_num), classType )
	slide = slide_num;
else
	% get the slide based on the slide ID
	% (I think this is the way to do it, but I'm not 100% sure:
	%  it seems like the SlideID is 255 + the slide num...
	slide = invoke(op.Slides, 'FindBySlideID', (255 + slide_num));
end

% paste into the powerpoint slide
pic = invoke(slide.Shapes,'Paste');

% if using normalized units, convert into pixels
if strncmp( lower(units), 'norm', 4 )==1
	pos([1 3]) = pos([1 3]) .* op.PageSetup.SlideWidth;
	pos([2 4]) = pos([2 4]) .* op.PageSetup.SlideHeight;
end

% set the position in the slide
set(pic, 'Left', pos(1));
set(pic, 'Top', pos(2));
set(pic, 'Height', pos(4));
set(pic, 'Width', pos(3));

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
% plugin_getweb - support function to get plugin information from the web

% Copyright (C) 2012- Arnaud Delorme
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function [plugin,eeglabVersionStatus] = plugin_getweb(type, pluginOri, varargin)
plugin = [];
eeglabVersionStatus = [];

if nargin < 1, help plugin_getweb; return; end
if nargin < 2, pluginOri = []; end

% convert plugin list format if necessary
if isfield(pluginOri, 'plugin'), pluginOri = plugin_convert(pluginOri); end

[~,dateTmp] = version;
if datenum(dateTmp) < 736583
    error( [ 'The plugin manager is only available for Matlab version 2016b and later versions.' 10 ...
              'Download plugins from the internet and unzip them in the plugin folder instead.' ] );
end

% retrieving statistics
eeglab_options;
try
    disp( [ 'Retrieving download statistics...' ] );
    if exist('OCTAVE_VERSION', 'builtin') == 0
        [plugin, status] = plugin_urlread([ 'http://sccn.ucsd.edu/eeglab/plugin_uploader/plugin_getcountall_nowiki_json.php?type=' type '&upload=' num2str(option_showpendingplugins)]);
    else
        [plugin, status] = urlread([ 'http://sccn.ucsd.edu/eeglab/plugin_uploader/plugin_getcountall_nowiki_json.php?type=' type '&upload=' num2str(option_showpendingplugins)]);
    end
    if isempty(plugin)
        disp('Issue with retrieving statistics for extensions');
        return;
    end
    try
        plugin = jsondecode(plugin);
    catch
        disp('Issue with decoding plugin information, Octave 7.x required to decode JSON strings');
    end
catch
    disp('Cannot connect to the Internet to retrieve statistics for extensions');
    return
end

if status == 0
    disp('Cannot connect to the Internet to retrieve extension list');
    return
end

%% rename fields for backward compabitiligy
renameField = { 'plugin' 'name';
                'count'  'downloads';
                'curversion' 'version';
                'link'   'zip' };

if ~isempty(pluginOri)
    currentNames = lower({ pluginOri.name });
else
    currentNames = {};
end
for iRow = 1:length(plugin)

    % rename fields
    for iField = 1:size(renameField, 1)
        plugin(iRow).(renameField{iField, 2}) = plugin(iRow).(renameField{iField, 1});
    end

    % decode tags
    plugin(iRow).rawtags = plugin(iRow).tags;
    if ~isempty(plugin(iRow).rawtags)
        tmpTags = textscan(plugin(iRow).rawtags, '%s', 'delimiter', ',');
        plugin(iRow).tags = tmpTags{1}';
    end

    plugin(iRow).numrating =  str2double(plugin(iRow).numrating);
    plugin(iRow).rating    =  str2double(plugin(iRow).rating);
    plugin(iRow).critical  =  str2double(plugin(iRow).critical);
    plugin(iRow).downloads =  str2double(plugin(iRow).downloads);
    plugin(iRow).size      =  sscanf(plugin(iRow).size, '%f'); % Only numeric part is taken, possible KB or MB additions are ignored
    plugin(iRow).webrating = [ 'https://sccn.ucsd.edu/eeglab/plugin_uploader/simplestar.php?plugin=' plugin(iRow).name '&version=' plugin(iRow).version ];

    % match with existiting plugins
    indMatch = strmatch(lower(plugin(iRow).name), currentNames, 'exact');
    if isempty(indMatch)
        plugin(iRow).currentversion  = '-';
        plugin(iRow).installed       = 0;
        plugin(iRow).installorupdate = 1;
        plugin(iRow).status          = 'notinstalled';
    else
        if length(indMatch) > 1
            disp([ 'Warning: duplicate extension ' plugin(iRow).name ' installed' ]);
        end
        plugin(iRow).currentversion = pluginOri(indMatch).currentversion;
        plugin(iRow).foldername     = pluginOri(indMatch).foldername;
        plugin(iRow).status         = pluginOri(indMatch).status;
        plugin(iRow).installed      = 1;
        if strcmpi(plugin(iRow).currentversion, plugin(iRow).version)
            plugin(iRow).installorupdate = 0;
        else
            plugin(iRow).installorupdate = 1;
        end
    end
end
plugin = rmfield(plugin, renameField(:,1)');

% handle the special case of EEGLAB version
indEEGLAB = cellfun(@(x)isequal(x, 'eeglab'), lower( { plugin.name } ));
eeglabVersionStatus = plugin(indEEGLAB);
plugin(indEEGLAB) = [];

% remove plugins with no zip file
% -------------------------------
plugin(cellfun(@isempty, {plugin.zip })) = [];

function plugin = plugin_convert(pluginOri)

for iRow = 1:length(pluginOri)
    plugin(iRow).currentversion = pluginOri(iRow).version;
    plugin(iRow).foldername     = pluginOri(iRow).foldername;
    plugin(iRow).status         = pluginOri(iRow).status;
    plugin(iRow).name           = pluginOri(iRow).plugin;
    plugin(iRow).installed      = 1;
end

author: sccn

repo: eeglab

save_path: github-repos/MATLAB/sccn-eeglab


text:
function DoubleStanceConstraints(nlp, bounds, varargin)

    ip = inputParser;
    ip.addParameter('LoadPath',[],@ischar);
    ip.parse(varargin{:});

    domain = nlp.Plant;

    %% step distance
    opt.constraint.step_distance(nlp, bounds);

    opt.constraint.yaw_start(nlp, bounds);

end

author: ayonga

repo: frost-dev

save_path: github-repos/MATLAB/ayonga-frost-dev


text:
classdef DeclusterWindowingMethods < int32
    % methods used for declustering a catalog
    % for a complete list
    % >> enumeration('DeclusterWindowingMethods')
    enumeration
        GardinerKnopoff1974     (1) % Gardener & Knopoff, 1974
        GruenthalPersCom        (2) % Gruenthal pers. communication
        Urhammer1986            (3) % Urhammer, 1986
        % Gruenthal1985           (4) % Gruenthal, 1985 (from Figure)
        % ModifiedYoungs1987Max   (5) % Modified Youngs, 1987 Maximum window
        % ModifiedYoungs1987Min   (6) % Modified Youngs, 1987 Minimum window
    end

    methods(Static)
        function s = description(val)

            switch DeclusterWindowingMethods(val)
                case DeclusterWindowingMethods.GardinerKnopoff1974
                    s = "Gardener & Knopoff, 1974";
                case DeclusterWindowingMethods.GruenthalPersCom
                    s = "Gruenthal pers. communication";
                case DeclusterWindowingMethods.Urhammer1986
                    s = "Urhammer, 1986";
            end
        end
    end
end

author: CelsoReyes


text:
function geometry_test203235 ( )

%*****************************************************************************80
%
%% TEST203235 tests TETRAHEDRON_RHOMBIC_SIZE_3D and TETRAHEDRON_RHOMBIC_SHAPE_3D.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 July 2007
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST203235\n' );
  fprintf ( 1, '  For the cube,\n' );
  fprintf ( 1, '  TETRAHEDRON_RHOMBIC_SIZE_3D returns dimension information;\n' );
  fprintf ( 1, '  TETRAHEDRON_RHOMBIC_SHAPE_3D returns face and order information.\n' );
  fprintf ( 1, '  SHAPE_PRINT_3D prints this information.\n' );
%
%  Get the data sizes.
%
  [ point_num, edge_num, face_num, face_order_max ] = ...
    tetrahedron_rhombic_size_3d ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of points =   %d\n', point_num );
  fprintf ( 1, '  Number of edges =    %d\n', edge_num );
  fprintf ( 1, '  Number of faces =    %d\n', face_num );
  fprintf ( 1, '  Maximum face order = %d\n', face_order_max );
%
%  Get the data.
%
  [ point_coord, face_order, face_point ] = ...
    tetrahedron_rhombic_shape_3d ( point_num, face_num, face_order_max );
%
%  Print the data.
%
  shape_print_3d ( point_num, face_num, face_order_max, ...
    point_coord, face_order, face_point );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% test for Fethalah code and Prados code
n = 500;

rep = 'results/anisotropic-feth/';
if not(exist(rep))
    mkdir(rep);
end

%% compute random tensor field
randn('seed', 12345);
U = randn(n,n,2);
sigma = (n/200)*30;
options.bound = 'per';
for it=1:10
    U = perform_vf_normalization( perform_blurring(U, sigma,options) );
end
U = perform_vf_normalization( U );

aniso_list = [1 .5 .2 .1 .05 .01 .001];

p = 5;
x = round( n/(p*2):n/p:n-n/(p*2) );
[Y,X] = meshgrid(x,x);
% start_points = round( start_points*(n-1)+1 );
start_points = cat(1, X(:)', Y(:)');

s = randperm(size(start_points,2));
for i=1:length(aniso_list)

    aniso = aniso_list(i);
    V = cat(3, -U(:,:,2), U(:,:,1)); % orthogonal vector
    T = perform_tensor_recomp(U,V, ones(n),ones(n)*aniso );
    Ti = perform_tensor_recomp(U,V, ones(n),ones(n)*1/aniso );

    options.use_feth_code = 0;
    tic;
    [D,S,Q] = perform_fast_marching(T, start_points, options);
    disp(['Prados: ' num2str(toc)]);

    hx = 1/n; hy = 1/n;
    tic;
    [D1,dUx,dUy, Vor, L] = fm2dAniso([hx;hy], Ti, start_points);
    disp(['Feth: ' num2str(toc)]);

    imageplot(s(Q), 'Prados', 1,2,1);
    imageplot(s(Vor+1), 'Feth', 1,2,2);
    colormap jet(256);
    saveas(gcf, [rep 'voronoi-' num2str(aniso) '.png'], 'png');

    clf;
    plot_tensor_field(T, perform_histogram_equalization(D, 'linear'));
    colormap jet(256);
    saveas(gcf, [rep 'distance-aniso-' num2str(aniso) '-prados.png'], 'png');

    clf;
    plot_tensor_field(T, perform_histogram_equalization(D1, 'linear'));
    colormap jet(256);
    saveas(gcf, [rep 'distance-' num2str(aniso) '-feth.png'], 'png');

end

author: alecjacobson

repo: gptoolbox