text:
function f = dtlz7a(x)

%% cost functions
f(:,1) = x(:,1);
f(:,2) = x(:,2);

%% g function
sum1 = 0;
sum2 = 0;
for i = 3:8
sum1 = sum1 + x(:,i);
end
g = 1+(9/6)*sum1;
for i = 1:2
sum2 = sum2 + (f(:,i)/(1+g))*(1+sin(3*pi*f(:,i)));
end
h = 3 - sum2;

%% cost functions
f(:,3) = (1+g)*h;

author: Eric-Bradford

repo: TS-EMO


text:
function W = Unfold(W, dim, i)
    W = reshape(shiftdim(W,i-1), dim(i), []);
end

author: andrewssobral


text:
function [rho,theta,R]=findTrigMomentFromSamp(n,x,w)
%%FINDTRIGMOMENTFROMSAMPLE Given a set of samples of a circular
%          distribution, determine a particular trigonometric sample
%          moment.
%
%INPUTS: n The order of the moment desired. This is >=1.
%        x The 1XN or NX1 vector of possibly weighted samples.
%        w The NX1 weights associated with the samples. If this parameter
%          is omitted or an empty matrix is passed, then the samples are
%          uniformly weighted.
%
%OUTPUTS: rho The (complex) mean resultant value for the nth moment. Note
%             that rho=R*exp(1j*theta).
%       theta The (real) trigonometric mean angle in radians for the nth
%             moment. This is between -pi and pi.
%           R The (real) mean resultant length for the nth moment.
%
%An expression for the complex trigonometric moments is given in Equation
%14 of [1]. This is just a weighted version of the definition in Chapter
%2.4 of [2].
%
%REFERENCES:
%[1] G. Kurz, I. Gilitschenski, R. Y. Siegwart, and U. D. Hanebeck,
%    "Methods for deterministic approximation of circular densities,"
%    Journal of Advances in Information Fusion, vol. 11, no. 2, pp.
%    138-156, Dec. 2016.
%[2] K. V. Mardia and P. E. Jupp, Directional Statistics. Chichester: John
%    Wiley and Sons, 2000.
%
%April 2018 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

N=length(x);
if(nargin<3||isempty(w))
    w=ones(N,1);
end

%Normalize.
w=w/sum(w);

rho=sum(exp(1i*n*x(:)).*w(:));
if(nargout>1)
    theta=angle(rho);
    R=abs(rho);
end
end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
classdef Rx < adi.AD9361.Rx
    % adi.AD9364.Rx Receive data from the AD9364 transceiver
    %   The adi.AD9361.Rx System object is a signal source that can receive
    %   complex data from the AD9364.
    %
    %   rx = adi.AD9364.Rx;
    %   rx = adi.AD9364.Rx('uri','192.168.2.1');
    %
    %   AD9364 Datasheet
    %
    %   See also adi.FMComms4.Rx

    methods
        %% Constructor
        function obj = Rx(varargin)
            % Returns the matlabshared.libiio.base object
            coder.allowpcode('plain');
            obj = obj@adi.AD9361.Rx(varargin{:});
        end
    end

end

author: analogdevicesinc


text:
function showPropulsionModel(propulsionModel)
%
% Shows propulsion model details: (See function 'TEST_definePropulsionModel.m')
%   - Location of propellers in aircraft body frame
%   - Plots for:
%       RPM vs throttle
%       Thrust vs RPM
%       Torque vs RPM
%
% Input:
%   propulsionModel (See function 'definePropulsionModel.m')
%
% Written by Conrad McGreal

%% plot propellers
n_motors = numel(propulsionModel) ;
legendcell = cell(n_motors,1) ;

%% Plot propulsion system geometry
figure
for i=1:n_motors
    d_prop = propulsionModel(i).d_prop ;
    loc = propulsionModel(i).thrustLocation ;
    ax = propulsionModel(i).thrustAxis ;
    plotPropLoc(d_prop, loc, ax) ;

    % labeling this motor
    x = loc(1) ;
    y = loc(2) ;
    z = loc(3) ;
    dx = 0.1 ; % label offset (from datapoint)
    dy = 0.1 ;

    this_label = strcat(['Motor ',num2str(i)]);
    legendcell{i} = this_label ;
    if propulsionModel(i).isSpinDirectionCCW
        dir_label = 'Spins CCW' ;
    else
        dir_label = 'Spins CW' ;
    end
    c1 = cellstr(this_label) ; % make it a cell
    c2 = cellstr(dir_label) ;
    text(x+dx, y+dy,z, c1) ; % print label to figure
    text(x+dx, y, z, c2) ; % print label to figure
end
title('Propeller Locations - Top view')
xlabel('x position [m]'); ylabel('y position [m]'); zlabel('z position [m]');
axis equal
drawnow

%% Plot performance; i.e. Thrust, Torque, & RPM vs throttle
figure
rho = 1.225 ; % set default air density

for i = 1:n_motors
motorid = i ; % select motor to plot for; at the moment only plots figure for one motor
RPM = 0:100:propulsionModel(motorid).maxRPM ;
throttle = linspace(0,1,numel(RPM)) ;
d_prop = propulsionModel(motorid).d_prop ;
C_t = propulsionModel(motorid).C_t ;
C_q = propulsionModel(motorid).C_q ;
[thrust, torque] = computePropOpPoint(RPM, rho, d_prop, C_t, C_q) ;

% plot it
ax1 = subplot(3,1,1) ;
plot(throttle,RPM); grid on; hold on;
xlabel('throttle []'); ylabel('RPM');

subplot(3,1,2)
plot(RPM,thrust); grid on; hold on;
xlabel('RPM'); ylabel('thrust [N]');

subplot(3,1,3)
plot(RPM,torque); grid on; hold on;
xlabel('RPM'); ylabel('torque [Nm]');
end
titleCell = 'motor model performance details' ;
title(ax1, titleCell)
legend(ax1, legendcell,'location','southeast')
drawnow

author: MatthewPeterKelly

repo: OptimTraj


text:
function SO3VF = quadrature(f, varargin)
%
% Syntax
%   SO3VF = SO3VectorFieldHarmonic.quadrature(rot, value)
%   SO3VF = SO3VectorFieldHarmonic.quadrature(f)
%   SO3VF = SO3VectorFieldHarmonic.quadrature(f, 'bandwidth', bw)
%
% Input
%   rot - @rotation, @orientation
%   value - @vector3d
%   f - function handle in @SO3VectorField
%
% Output
%   SO3VF - @SO3VectorFieldHarmonic
%
% Options
%   bw - degree of the Wigner-D functions (default: 128)
%

if isa(f,'rotation')
  v = f;
  y = getClass(varargin,'vector3d'); % function values
  y = y.xyz;
  SO3F = SO3FunHarmonic.quadrature(v, y, varargin{:});
  SO3VF = SO3VectorFieldHarmonic(SO3F);
  return
end

if isa(f,'function_handle')
  [SRight,SLeft] = extractSym(varargin);
  f = SO3FunHandle(f,SRight,SLeft);
end

SO3F = SO3FunHarmonic.quadrature(@(rot) g(rot),f.CS,f.SS,varargin{:});
SO3VF = SO3VectorFieldHarmonic(SO3F);

function g = g(rot)
g = f.eval(rot);
g = g.xyz;
end

end

author: mtex-toolbox

repo: mtex

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


text:
function [pvals,is_significant] = test_significance(TestData,W,p,nnull)
%
% USAGE:
%
% [pvals,is_significant] = test_significance(TestData,W,0.01)
%
% ------------------------------------------------------------------------
% DESCRIPTION:
%
% Tests each factor in W for significance using a held out test dataset at
% a p-value of p using Bonferroni correction.
%
% ------------------------------------------------------------------------
%
% INPUTS:
%
% Name              Default                 Description
% TestData                                  Held out data matrix (NxT)
% W                                         NxKxL tensor containing factor exemplars
% p                 0.05                    Desired p-value to test
% nnull             ceil(K/p)*2             Number of null datasets to use
%
% ------------------------------------------------------------------------
% OUTPUTS:
%
% pvals                      A vector (1xK) containing the p-value of each factor
% is_significant             A boolean vector (1xK) which is 1 if a factor
%                            is significant using the specified pvalue with correction
%
% ------------------------------------------------------------------------
% CREDITS:
%   Emily Mackevicius and Andrew Bahle, 2/1/2018
%
%   Please cite our paper:
%       XXXXXXXXXXXXXXXXXXXXX
% Remove factors where there is obviously no sequence
% That is, W is empty, or has one neuron with >99.9% of the power

indempty = sum(sum(W>0,1),3)==0; % W is literally empty
Wflat = sum(W,3);
indempty = indempty | (max(Wflat,[],1).^2> .999*sum(Wflat.^2,1)); % or one neuron has >99.9% of the power
W(:,indempty,:) = []; % Delete factors that meet the above critera

[N,K,L] = size(W);
[~,T] = size(TestData);

if nargin < 3
    p = 0.05;
end

if nargin < 4
    nnull = ceil(K/p)*2;
end

% make nnull shifted datasets
skewnull = zeros(K,nnull);

X = TestData;

for n = 1:nnull
    % Make a null dataset
    Wnull = zeros(N,K,L);
    for k = 1:K
        for ni = 1:N
            %Wnull(ni,k,:) = circshift(W(ni,k,:),randi(L));
            Wnull(ni,k,:) = circshift(W(ni,k,:),[0,0,randi(L)]);
        end
    end
    %figure, imagesc(squeeze(Wnull(:,1,:))), colormap(gca, flip(gray)),axis off
    % Calculate WTX
    WTX = zeros(K, T);
    for l = 1 : L
        %X_shifted = circshift(X,-l+1,2);
        X_shifted = circshift(X,[0,-l+1]);
        WTX = WTX + Wnull(:, :, l)' * X_shifted;
    end
    %figure, histogram(WTX(1,:),0:1:100,'FaceColor','k')
    %set(gca,'yscale','log'), ylim([0,10e2])
    % Get skewness of each
    skewnull(:,n) = skewness(WTX,1,2);
end

WTX = zeros(K, T);
for l = 1 : L
    %X_shifted = circshift(X,-l+1,2);
    X_shifted = circshift(X,[0,-l+1]);
    WTX = WTX + W(:, :, l)' * X_shifted;
end
skew = skewness(WTX,1,2);
for k = 1:K
    % Assign pvals from skewness
    pvals(k) = (1+sum(skewnull(k,:)>skew(k)))/nnull;
end
allpvals(indempty) = Inf;
allpvals(~indempty) = pvals;
pvals = allpvals;
is_significant = (pvals <= p/K);
end

author: FeeLab

repo: seqNMF

save_path: github-repos/MATLAB/FeeLab-seqNMF


text:
%% Example
% An example script, it is used to show how to use the different
% functions of the KUKA iiwa matlab toolbox

% First run the following script in Matlab
% Then start the client on the KUKA iiwa controller

% Mohammad SAFEEA, 24th of April 2018

close all,clear all,clc
warning('off');
ip='172.31.1.147'; % The IP of the controller
% start a connection with the server
t_Kuka=net_establishConnection( ip );

if ~exist('t_Kuka','var') || isempty(t_Kuka) || strcmp(t_Kuka.Status,'closed')
  warning('Connection could not be establised, script aborted');
  return;
else

    %% move to initial position
pinit={0,pi*20/180,0,-pi*70/180,0,pi*90/180,0}; % initial confuguration
relVel=0.15; % relative velocity
movePTPJointSpace( t_Kuka , pinit, relVel); % point to point motion in joint space

      %% Get position roientation of end effector
      disp('Cartesian position')
      Pos=getEEFPos( t_Kuka )

      relVel=50; % velocity of the end effector, mm/sec

      disp=50;
      %% Move the endeffector in the X direction
      index=1;
      Pos{index}=Pos{index}+disp;

       movePTPLineEEF( t_Kuka , Pos, relVel)
      pause(0.1)
      Pos{index}=Pos{index}-disp;

      movePTPLineEEF( t_Kuka , Pos, relVel)

      %% Move the endeffector in the z direction

       index=3;
      Pos{index}=Pos{index}+disp;

       movePTPLineEEF( t_Kuka , Pos, relVel)
       pause(0.1)
       Pos{index}=Pos{index}-disp;

      movePTPLineEEF( t_Kuka , Pos, relVel)

      %% Move the endeffector to a distination frame,

       Pos={400,0,580,-pi,0,-pi}; % first configuration
       % the coordinates are:
       % x=400mm, y=0mm, z=580 mm.
       % the rotation angles are:
       % alpha=-180 degrees, beta=0 degrees, gama=-180 degrees

       movePTPLineEEF( t_Kuka , Pos, relVel)

       Pos={500,0,580,-pi,0,-pi+pi/4}; %% second configuration
       % the coordinates are:
       % x=400mm, y=0mm, z=580 mm.
       % the rotation angles are:
       % alpha=-180 degrees, beta=0 degrees, gama=-165 degrees,
       setBlueOn(t_Kuka);
       movePTPLineEEF( t_Kuka , Pos, relVel)
       setBlueOff(t_Kuka);
      %% turn off the server
       net_turnOffServer( t_Kuka );

       fclose(t_Kuka);
end
warning('on');

repo: KST-Kuka-Sunrise-Toolbox


text:
% Copyright (C) 2017-2018 Titus Cieslewski, RPG, University of Zurich,
%   Switzerland
%   You can contact the author at <titus at ifi dot uzh dot ch>
% Copyright (C) 2017-2018 Siddharth Choudhary, College of Computing,
%   Georgia Institute of Technology, Atlanta, GA, USA
% Copyright (C) 2017-2018 Davide Scaramuzza, RPG, University of Zurich,
%   Switzerland
%
% This file is part of dslam_open.
%
% dslam_open 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.
%
% dslam_open 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 dslam_open. If not, see <http://www.gnu.org/licenses/>.

%% Prep: Do once, writes to files
%% Generate NetVLAD vectors for dataset
getNetVladFeats(dataset_path, sequence_id);
%% Parse VO and merge with NetVLAD
% Prereq: Run C++ executable dataset_to_vo
parseAllData(dataset_path, sequence_id);
%% Split full dataset into n robots
splitAndSave(dataset_path, sequence_id, num_robots);
%% Generate verification requests.
generateVerificationRequests(dataset_path, sequence_id, num_robots);
%% Parse verification response
% Prereq: Run C++ exec process_verification_request
parseVerificationResponse(dataset_path, sequence_id, num_robots);

%% Load vanilla
root = [dataset_path '/' sequence_id '/'];
dpath = [root 'dslam/'];
load([dpath 'robot_data_' num2str(num_robots) '.mat']);
%% Plot vanilla
plotGeoverError(robot_data, [1], 'vanilla');

%% Create prototype
proto_data = robot_data;
%%
consistency_range = 20;
position_tolerance = 4;

for robot_i = 1:numel(proto_data)
    r_i_data = proto_data{robot_i};
    % For each robot, keep track of last seen rel pose that is floating or
    % accepted. Floating: rel pose that is neither accepted or rejected.
    last_floating = cell(num_robots, 1);
    last_accepted = cell(num_robots, 1);
    match_accepted = false(numel(r_i_data.place_matches), 1);
    for query_i = 1:numel(r_i_data.place_matches)
        match = r_i_data.place_matches{query_i};
        if (numel(match) > 0)
            this.frame_i = query_i;
            this.match = match;
            % Case there is a last accepted rel pose
            if (numel(last_accepted{match.robot_i}) > 0)
                assert(numel(last_floating{match.robot_i}) == 0);
                % If they are within range, accept if consistent.
                if areFramesWithinRange(r_i_data, ...
                        last_accepted{match.robot_i}.frame_i, query_i, ...
                        consistency_range)
                    if areMatchesConsistent(proto_data, robot_i, ...
                            last_accepted{match.robot_i}, this, ...
                            position_tolerance)
                        match_accepted(query_i) = true;
                        last_accepted{match.robot_i} = this;
                        disp('Acc consistent acc');
                        continue;
                    else
                        match_accepted(query_i) = false;
                        disp('Rej inconsistent acc');
                        continue;
                    end
                else % Frames are not within range: Forget last_accepted.
                    last_accepted{match.robot_i} = [];
                    % Will drop to case no previous floating.
                end
            end
            % Case there is a last floating rel pose
            if (numel(last_floating{match.robot_i}) > 0)
                % If they are within range, accept both if consistent.
                if areFramesWithinRange(r_i_data, ...
                        last_floating{match.robot_i}.frame_i, query_i, ...
                        consistency_range)
                    if areMatchesConsistent(proto_data, robot_i, ...
                            last_floating{match.robot_i}, this, ...
                            position_tolerance)
                        match_accepted(...
                            last_floating{match.robot_i}.frame_i) = true;
                        match_accepted(query_i) = true;
                        last_floating{match.robot_i} = [];
                        last_accepted{match.robot_i} = this;
                        disp('Acc consistent float');
                        continue;
                    % If not consistent, replace floating with this.
                    else
                        match_accepted(...
                            last_floating{match.robot_i}.frame_i) = false;
                        last_floating{match.robot_i} = this;
                        disp('Rej inconsistent float');
                        continue;
                    end
                else % Frames are not within range: Replace last_floating.
                    match_accepted(...
                        last_floating{match.robot_i}.frame_i) = false;
                    last_floating{match.robot_i} = this;
                    disp('Reinit float');
                    continue;
                end
            % Case there is neither a last accepted nor last floating.
            else
                % Set floating to this.
                last_floating{match.robot_i} = this;
                disp('Init float');
            end
        end
    end
    % Eliminate non-accepted matches.
    proto_data{robot_i}.place_matches(~match_accepted) = {[]};
    disp(['Accepted ' num2str(nnz(match_accepted)) ' of ' ...
        num2str(numel(match_accepted)) ' matches!']);
end

%%
plotGeoverError(proto_data, [2], 'robustified');

author: uzh-rpg


text:
%% Test all the Simulink models

function tests = SimulinkTest
  tests = functiontests(localfunctions);
end

function setupOnce(testCase)
    testCase.TestData.StopTime = 0.5;
end

function teardownOnce(tc)
    delete('*.slxc')
    bdclose
end

function braitenberg_test(testCase)
    sim('sl_braitenberg', testCase.TestData.StopTime);
	bdclose all

end

function lanechange_test(testCase)
    sim('sl_lanechange', testCase.TestData.StopTime);
	bdclose all
end

function pursuit_test(testCase)
    sim('sl_pursuit', testCase.TestData.StopTime);
	bdclose all
end

function drivepoint_test(testCase)
    assignin('base', 'xg', [5 5]);
    assignin('base', 'x0', [0 0 pi/2]);
    sim('sl_drivepoint', testCase.TestData.StopTime);
	bdclose all
end

function driveline_test(testCase)
    assignin('base', 'L', [1 -2 4]);
    assignin('base', 'x0', [0 -4 pi]);
    sim('sl_driveline', testCase.TestData.StopTime);
	bdclose all
end

function drivepose_test(testCase)
    assignin('base', 'xg', [5 5 pi/2]);
    assignin('base', 'x0', [8 5 pi]);
    r = sim('sl_drivepose', testCase.TestData.StopTime);
	bdclose all
end

function jspace_test(testCase)
    mdl_puma560
    assignin('base', 'p560', p560);
    sim('sl_jspace', testCase.TestData.StopTime);
	bdclose all
end

function rrmc_test(testCase)
    mdl_puma560
    assignin('base', 'p560', p560);
    assignin('base', 'qn', qn);
    sim('sl_rrmc', testCase.TestData.StopTime);
	bdclose all
end

function rrmc2_test(testCase)
    mdl_puma560
    assignin('base', 'p560', p560);
    assignin('base', 'qn', qn);
    sim('sl_rrmc2', testCase.TestData.StopTime);
	bdclose all
end

function ztorque_test(testCase)
    mdl_puma560
    p560 = p560.nofriction();
    assignin('base', 'p560', p560);
    sim('sl_ztorque', testCase.TestData.StopTime);
	bdclose all
end

function vlooptest_test(testCase)
    sim('vloop_test', testCase.TestData.StopTime);
	bdclose all
end

function plooptest_test(testCase)
    G = 107.815;   % in case not previously set by vloop_test
    sim('ploop_test', 1);
	bdclose all
end

function ctorque_test(testCase)
    mdl_puma560
    p560 = p560.nofriction();
    assignin('base', 'p560', p560);
    sim('sl_ctorque', testCase.TestData.StopTime);
	bdclose all
end

function feedforward_test(testCase)
    mdl_puma560
    p560 = p560.nofriction();
    assignin('base', 'p560', p560);
    sim('sl_fforward', testCase.TestData.StopTime);
	bdclose all
end

function flexlink_test(testCase)
    mdl_twolink
    assignin('base', 'twolink', twolink);
    sim('sl_flex', testCase.TestData.StopTime);
	bdclose all
end

function quadcopter_test(testCase)
    sim('sl_quadrotor', testCase.TestData.StopTime);
	bdclose all
end

function quadcopter_vs_test(testCase)
    testCase.assumeTrue( exist('SphericalCamera') == 2 );

    sim('sl_quadrotor_vs', testCase.TestData.StopTime/10);
	bdclose all
end

author: petercorke

repo: robotics-toolbox-matlab


text:
% demo for SINEFIT program.
% % Written by Dr Chen YangQuan <yqchen@ieee.org>
echo on

% test codes:
A0=2;sigma=2;
omega=2*pi*2; % f=2 Hz
theta0=pi/2;
t=0:.005:2;
dn=sigma*randn(size(t));
s0=A0*sin(omega*t + theta0) + dn;
t0=0;Ts=0.005;

%Assume frequency f = 2.5 Hz which is 25% larger than the theoretical value of 2 Hz.
% Calling [Ahat,Theta,Omega,RMS]=sinefit(s0,0.4,0,0.005)
pause
[Ahat,Theta,Omega,RMS]=sinefit(s0,1/2.5,0,0.005);
%gives the filtering results shown in Fig. 4.

pause

%Now, increase sigma from 1 to 2. The filtering
%results are shown in Fig. 5 by calling  [Ahat,Theta,Omega,RMS]=sinefit(s0,1/1.5,0,0.005).
[Ahat,Theta,Omega,RMS]=sinefit(s0,1/1.5,0,0.005);
%Note that in this case, the frequency f = 1:5 Hz which is 25% lower than the theoretical value
%of 2 Hz. It can be concluded that the optimal feature extraction can be used as a means of
%filtering.

author: Sable

repo: mcbench-benchmarks


text:
%% GENERATE CODE FOR VARIABLES
% This document demonstrates the usage of GENCODE, GENCODE_RVALUE and
% GENCODE_SUBSTRUCT to show and modify the contents of complicated MATLAB
% variables.
%%
%% A TEST VARIABLE
% The variable x is a struct with two fields: f1 and f2. f1 is a cell array
% of arbitrary items.
x.f1        = {1 'somestring' false};
%%
% f2 is a struct array with 2 members and fields f21, f22, f23. The fields
% in f2(1) hold different numeric types.
x.f2(1).f21 = diag([1 1 -Inf NaN]);
x.f2(1).f22 = speye(5);
x.f2(1).f23 = 17 * ones(5,6,2,'int8');
%%
% The fields in f2(2) hold a cell string array, a logical array and a
% (anonymous) function handle.
x.f2(2).f21 = {'string 1'; 'string 2'; 'A third string'};
x.f2(2).f22 = rand(5) > .5;
x.f2(2).f23 = @(x)mod(x,2);
%% GENERATE CODE FOR RIGHT HAND SIDE OF ASSIGNMENTS
% GENCODE uses GENCODE_RVALUE to generate code for the right hand side of
% assignments. This works for
%
% * all scalar, vector, 2D data
% * cells with scalar, vector, 2D members
% * function handles
%
[str, sts] = gencode_rvalue(x.f1);
display(sts)
char(str)
%%
% x.f2(1).f23 is a 3D array, therefore GENCODE_RVALUE does not work here -
% sts is false
size(x.f2(1).f23)
[str, sts] = gencode_rvalue(x.f2(1).f23);
display(sts)
char(str)
%% GENERATE CODE FOR TEST VARIABLE
% The simplest way to invoke GENCODE is with just the variable as input
% argument. Code for arrays with more than 2 dimensions is split up into
% code for 2D subarrays.
% Code for sparse matrices is generated using three temporary variables
% tmpi, tmpj and tmps.
strx = gencode(x);
char(strx)
%%
% If the name of the variable should be different from the input variable
% name, GENCODE can be called with an alternative name. This can also be an
% struct reference (|y.a|) or cell entry (|y{2}|) or array index (|y(1)|).
stry = gencode(x,'y.a');
char(stry)
%% USE GENERATED CODE TO RECREATE VARIABLE
% The generated code can be used to recreate the variable:
clear x
eval(sprintf('%s\n', strx{:}))
display(x)
%%
% Usually, one would write the code to a file using a sequence of commands
% like this:
%
% <html>
% <pre class="codeinput">
% fid = fopen('test.m','w');
% fprintf(fid, '%s\n', strx{:});
% fclose(fid)
% </pre>
% </html>
%
% This file can then be modified to recreate new instances of x.

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
% ------------------------------------------------------------------------
%  Copyright (C)
%  Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain
%  University of California Berkeley (UCB) - USA
%
%  Jordi Pont-Tuset <jordi.pont@upc.edu>
%  Pablo Arbelaez <arbelaez@berkeley.edu>
%  June 2014
% ------------------------------------------------------------------------
% This file is part of the MCG package presented in:
%    Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J,
%    "Multiscale Combinatorial Grouping,"
%    Computer Vision and Pattern Recognition (CVPR) 2014.
% Please consider citing the paper if you use this code.
% ------------------------------------------------------------------------

function stats = get_single_hier_stats(params,hier_id,gt_set)

if nargin<3
    gt_set = params.gt_set_pareto;
    res_file = params.files.pareto_singles{hier_id};
else
    res_file = strrep(params.files.pareto_singles{hier_id},[params.gt_set_pareto '_pareto_single'],[gt_set '_pareto_single']);
end

% Sampled number of candidates from each hierarchy
n_cands = [10:10:100,200:100:1000,2000:1000:10000];

for ii=1:params.n_r_cand
    n_max_cands(ii) = max(n_cands); %#ok<*AGROW>
end

% Are the results already computed?
if exist(res_file, 'file')
    load(res_file)
    disp(['Loaded: ' res_file '.'])
    recompute = 0;
else
    disp(['RECOMPUTING: ' res_file '.'])
    recompute = 1;
end

if recompute
    % Load which images to consider from the database (train, val, etc.)
    im_ids = database_ids(params.database,gt_set);

    for ll=1:params.n_r_cand
        % Store number of regions and gt_set
        stats(ll).n_cands = n_cands;
        stats(ll).gt_set = gt_set;
        stats(ll).num_objects = 0;
        stats(ll).obj_classes = [];
    end

    % Sweep all images
    num_images = length(im_ids);
    for ii = 1:num_images

        % Read the UCM as a hierarchy
        hier = ucm2hier(fullfile(params.hier_dirs{hier_id}, [im_ids{ii} '.mat']));
        n_regs = hier.ms_struct(end).parent;

        % Get all pairs of neighboring leave regions
        [~, idx_neighbors] = seg2gridbmap(hier.leaves_part);
        K = max(idx_neighbors.matrix_max(:)) + 1;
        neigh_pairs = unique(idx_neighbors.matrix_min+K*idx_neighbors.matrix_max);
        neigh_pairs(neigh_pairs==0) = [];
        neigh_pairs_min = mod(neigh_pairs,K);
        neigh_pairs_max = (neigh_pairs-neigh_pairs_min)/K;

        if isrow(neigh_pairs_min)
            neigh_pairs_min = neigh_pairs_min';
        end
        if isrow(neigh_pairs_max)
            neigh_pairs_max = neigh_pairs_max';
        end

        % Get the 'n_cands' top candidates from each hierarchy

        % Singletons
        if n_regs<=n_max_cands(1)
            all_cands{1} = (n_regs:-1:1)';
        else
            all_cands{1} = (n_regs:-1:(n_regs-n_max_cands(1))+1)';
        end

        % Pairs, triplets, etc.
        all_cands(2:params.n_r_cand) = ...
        mex_get_tree_cands(double(hier.leaves_part)-1, double(hier.ms_matrix)-1,...
                             neigh_pairs_min-1, neigh_pairs_max-1,...
                             n_max_cands(2:end));

        % Load ground truth
        curr_gt = get_ground_truth( params.database, im_ids{ii} );

        for ll=1:params.n_r_cand
            % Evaluate the candidates
            [jaccards,inters,false_pos,false_neg,true_areas,obj_classes] = eval_cands(hier,all_cands{ll},curr_gt); %#ok<ASGLU>

            % Get best candidate at different number of candidates
            for jj=1:length(stats(ll).n_cands)
                curr_n_regs = min(stats(ll).n_cands(jj), size(inters,2));
                to_consider = 1:curr_n_regs;
                stats(ll).all_n_masks(ii,jj) = length(to_consider);
                if (stats(ll).all_n_masks(ii,jj)>0)
                    for kk=1:size(inters,1)
                        [stats(ll).max_J(stats(ll).num_objects+kk,jj), which_one] = max(jaccards(kk,to_consider));
                        stats(ll).max_indicator(stats(ll).num_objects+kk,jj) = to_consider(which_one);
                        stats(ll).max_fp(stats(ll).num_objects+kk,jj)        = false_pos(kk,to_consider(which_one));
                        stats(ll).max_fn(stats(ll).num_objects+kk,jj)        = false_neg(kk,to_consider(which_one));
                        stats(ll).max_inters(stats(ll).num_objects+kk,jj)    = inters(kk,to_consider(which_one));
                    end
                end
            end
            stats(ll).obj_classes = [stats(ll).obj_classes; obj_classes(1:size(inters,1))'];
            stats(ll).num_objects = stats(ll).num_objects + size(jaccards,1);
        end
    end

    for ll=1:params.n_r_cand
        stats(ll).jaccard_object = mean(stats(ll).max_J);
        stats(ll).mean_n_masks   = mean(stats(ll).all_n_masks);

        % ----- Compute jaccard at pixel level (J_p) ----
        class_ids = unique(stats(ll).obj_classes);

        % Compute per-class statistics and then mean
        for ii=1:length(class_ids)
            curr_class = class_ids(ii);
            stats(ll).per_class_results{ii}.num_objects = sum(stats(ll).obj_classes==curr_class);

            stats(ll).per_class_results{ii}.max_fp     = stats(ll).max_fp(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.max_fn     = stats(ll).max_fn(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.max_inters = stats(ll).max_inters(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.max_J      = stats(ll).max_J(logical(stats(ll).obj_classes==curr_class),:);
            stats(ll).per_class_results{ii}.meanmax    = mean(stats(ll).per_class_results{ii}.max_J);

            stats(ll).per_class_results{ii}.global_fp      = sum(stats(ll).per_class_results{ii}.max_fp,1);
            stats(ll).per_class_results{ii}.global_fn      = sum(stats(ll).per_class_results{ii}.max_fn,1);
            stats(ll).per_class_results{ii}.global_inters  = sum(stats(ll).per_class_results{ii}.max_inters,1);

            % Compute per-class total inters, fp, fn
            stats(ll).per_class_results{ii}.global_J = ...
                 stats(ll).per_class_results{ii}.global_inters ./...
                (stats(ll).per_class_results{ii}.global_inters+...
                 stats(ll).per_class_results{ii}.global_fp    +...
                 stats(ll).per_class_results{ii}.global_fn);
        end

        % Compute global mean
        tmp = [];
        for ii=1:length(class_ids)
            tmp = [tmp; stats(ll).per_class_results{ii}.global_J];
        end
        stats(ll).jaccard_class = mean(tmp);
    end

    % Store
    save(res_file,'stats');
end

author: jponttuset

repo: mcg

save_path: github-repos/MATLAB/jponttuset-mcg


text:
function obslik = mk_hmm_obs_lik_matrix(engine, evidence)

T  = size(evidence,2);
Q = length(engine.startprob);
obslik = ones(Q, T);
bnet = bnet_from_engine(engine);
% P(o1,o2| Q1,Q2) = P(o1|Q1,Q2) * P(o2|Q1,Q2)
onodes = bnet.observed;
for i=1:length(onodes)
  data = cell2num(evidence(onodes(i),:));
  if bnet.auto_regressive(onodes(i))
    params = engine.obsprob{i};
    mu = params.big_mu;
    Sigma = params.big_Sigma,
    W = params.big_W;
    mu0 = params.big_mu0;
    Sigma0 = params.big_Sigma0;
    %obslik_i = mk_arhmm_obs_lik(data, mu, Sigma, W, mu0, Sigma0
    obslik_i = clg_prob(data(:,1:T-1), data(:,2:T), mu, Sigma, W);
    obslik_i = [mixgauss_prob(data(:,1), mu0, Sigma0) obslik_i];
  elseif myismember(onodes(i), bnet.dnodes)
    %obslik_i = eval_pdf_cond_multinomial(data, engine.obsprob{i}.big_CPT);
    obslik_i = multinomial_prob(data, engine.obsprob{i}.big_CPT);
  else
    %obslik_i = eval_pdf_cond_gauss(data, engine.obsprob{i}.big_mu, engine.obsprob{i}.big_Sigma);
    obslik_i = mixgauss_prob(data, engine.obsprob{i}.big_mu, engine.obsprob{i}.big_Sigma);
  end
  obslik = obslik .* obslik_i;
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
function r = subsasgn(r,s,b)
% overloads subsasgn

if isnumeric(r)
  r = b;
  r.a = [];
  r.b = [];
  r.c = [];
  r.d = [];
  r.i = [];
end

if ~isstruct(s)

  if isempty(b)
    r.a(s) = [];
    r.b(s) = [];
    r.c(s) = [];
    r.d(s) = [];
    r.i(s) = [];
  else
    b = rotation(b);
    r.a(s) = b.a;
    r.b(s) = b.b;
    r.c(s) = b.c;
    r.d(s) = b.d;
    r.i(s) = b.i;
  end

else
  switch s(1).type

    case '()'

      if numel(s)>1, b =  builtin('subsasgn',subsref(r,s(1)),s(2:end),b); end

      if isnumeric(b)
        r.a = subsasgn(r.a,s(1),b);
        r.b = subsasgn(r.b,s(1),b);
        r.c = subsasgn(r.c,s(1),b);
        r.d = subsasgn(r.d,s(1),b);
        if isempty(b)
          r.i = subsasgn(r.i,s(1),[]);
        else
          r.i = subsasgn(r.i,s(1),false(size(b)));
        end
      else
        b = rotation(b);
        r.a = subsasgn(r.a,s(1),b.a);
        r.b = subsasgn(r.b,s(1),b.b);
        r.c = subsasgn(r.c,s(1),b.c);
        r.d = subsasgn(r.d,s(1),b.d);
        r.i = subsasgn(r.i,s(1),b.i);
      end
    otherwise
      r =  builtin('subsasgn',r,s,b);
  end
end

end


text:
function Fmat = extForce_gen(tsave, start_T, duration, mag, direction)

% Direction vector of the external force (unit vector)
dir_F = direction/norm(direction);
F = mag * dir_F;
Fmat = zeros(length(tsave),3);

% time frame : tsave - duration - tsave

for i = 1:length(tsave)
    if tsave(i) >= start_T && tsave(i) < start_T + duration/6
        Fmat(i,:) = F*(sin(2*pi/(duration/3)*(tsave(i)-start_T)-pi/2) + 1)/2;

    elseif tsave(i) >= start_T + duration/6 && tsave(i) < start_T + duration*5/6
        Fmat(i,:) = F;

    elseif tsave(i) >= start_T + duration*5/6 && tsave(i) < start_T + duration
        Fmat(i,:) = F*(sin(2*pi/(duration/3)*(tsave(i)-(start_T+duration*5/6)) + pi/2) + 1)/2;
    end
end
Fmat = [tsave', Fmat];

end

author: yorgoon

repo: minimum-snap-geometric-control


text:
function varargout = DEMO(varargin)
% Last Modified by GUIDE v2.5 05-Mar-2009 14:13:52

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @DEMO_OpeningFcn, ...
                   'gui_OutputFcn',  @DEMO_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);

if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end

return

% --- Executes just before DEMO is made visible.
function DEMO_OpeningFcn(hObject, eventdata, handles, varargin)
global FSSettings StopByUser

FSSettings.ErrorEstMethod      = 'ProposedAB';
FSSettings.FSMethod            = 'SFS';
%------- Classifier Settings -------
FSSettings.GammaParam          = 0.015;
FSSettings.ConfMatSwitch       = 0;
FSSettings.PercTest            = 10;
%-- Sequential Selection Settings -----
FSSettings.MahalInfoLossMethod = 'on';
FSSettings.TotalNStepsThres    = 250;
FSSettings.LogViewOfIntStep    = 1;
%------------- ReliefF --------------
FSSettings.NCorePatterns  = 250;
FSSettings.NHits          = 10;
%------------------------------------

handles.output = hObject;
StopByUser = 0;
axes(handles.YelLinesAxes); set(gca, 'Visible', 'off');
handles.SliderValue = 10;
warning off all
guidata(hObject, handles);

% --- Outputs from this function are returned to the command line.
function varargout = DEMO_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
varargout{1} = handles.output;

% -----------------Data Load and View -----------------------------
function OpenDataFile_ClickedCallback(hObject, eventdata, handles)
handles.file = uigetfile('*.*');

global StopByUser

if handles.file~=0
    % Only for viewing purpose
    [Patterns, Targets] = DataLoadAndPreprocess(handles.file);
    handles.PatternsToRunFS = Patterns;
    handles.TargetsToRunFS  = Targets;
    StopByUser = 0;

    [NPatterns, KFeatures] = size(Patterns);
    axes(handles.FeatSelCurve);cla reset;
    axes(handles.ClassResAxes); cla reset;
    axes(handles.ClassesLegendAxes); cla reset;
    set(gca,'Visible','off');
    axes(handles.YelLinesAxes); set(gca, 'Visible', 'off');
    axis manual
    axes(handles.PatternsFeaturesAxes);cla reset;

    if NPatterns>KFeatures
        imagesc(1.00001*Patterns');
        xlabel('Patterns')
        ylabel('Features','Rotation',0,'Position',[0 0]);
    else
        imagesc(1.00001*Patterns);
        xlabel('Features')
        ylabel('Patterns','Rotation',0,'Position',[0 0]);
    end
    title(handles.file);
    colorbar;

     set(findobj(gcf,'Tag','ListSelFeats'), 'String', ...
         'Press Start to select features');
    guidata(hObject, handles);
end
return

% -----------------------------------------------------------------
function RunFeatSelection_ClickedCallback(hObject, eventdata, ...
                                                           handles)
global StopByUser  FSSettings

set(findobj(gcf,'Tag','ListSelFeats'), 'String', []);
axes(handles.FeatSelCurve); cla reset;
axes(handles.YelLinesAxes); cla reset; set(gca,'Visible','off',...
                                                'YDir','reverse');
StopByUser = 0;
guidata(hObject, handles);

FSSettings.FSMethod

if strcmp(FSSettings.FSMethod,'SFS')|| strcmp(FSSettings.FSMethod,'SFFS')
[ResultMat, ConfMatOpt, Tlapse, handles.OptimumFeatureSet,...
      OptimumCCR]= ForwSel_main(handles.file, FSSettings, handles);
elseif strcmp(FSSettings.FSMethod,'ReliefF')
[FeatureWeightsOrdered, FeaturesIndexOrdered, ...
    handles.OptimumFeatureSet] = ReliefF(handles.file,...
                                               FSSettings,handles);
elseif strcmp(FSSettings.FSMethod,'SBS') || ...
                                 strcmp(FSSettings.FSMethod,'SFBS')
[ResultMat, ConfMatOpt, Tlapse, handles.OptimumFeatureSet,...
     OptimumCCR]= BackSel_main(handles.file, FSSettings, handles);
end
handles.OptimumFeatureSet = sort(handles.OptimumFeatureSet);
guidata(hObject, handles);

% -----------------------------------------------------------------
function StopFeatSelButton_ClickedCallback(hObject, eventdata,...
                                                           handles)
global StopByUser
StopByUser = 1;
guidata(hObject, handles);
return

%------------------------------------------------------------------
function ListSelFeats_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), ...
                         get(0,'defaultUicontrolBackgroundColor'));
    set(hObject,'BackgroundColor','white');
end
set(hObject,'String','None Selected yet');

%------------------------------------------------------------------
function LoadAndClassifyButton_ClickedCallback(hObject,...
                                                eventdata, handles)

handles.fileToClassify = uigetfile('*.mat');
PatternsToClassify = DataLoadAndPreprocess(handles.fileToClassify);

handles.PatternsToClassify = PatternsToClassify(:,...
                                        handles.OptimumFeatureSet);

NPatternsToClassify = size(PatternsToClassify,1);

if NPatternsToClassify >= 10
 set(findobj(gcf,'Tag','ClassResSlider'), ...
                 'Max', NPatternsToClassify,...
                 'Min', 10, ...
                 'Value', 10, ...
       'SliderStep',[1 1]/(NPatternsToClassify-10),'Enable', 'on');
else
  set(findobj(gcf,'Tag','ClassResSlider'), 'Enable', 'off');
end
  handles.SliderValue = 10;

guidata(hObject, handles);
DEMO('ClassifyAndPlot',guidata(gcbo));
guidata(hObject, handles);

%------------------------------------------------------------------
function ClassResSlider_Callback(hObject, eventdata, handles)
handles.SliderValue = get(hObject,'Value');
guidata(hObject, handles);
DEMO('ClassifyAndPlot',guidata(gcbo));
guidata(hObject, handles);

%------------------------------------------------------------------
function ClassResSlider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), ...
                          get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

%------------------------------------------------------------------
function ClassifyAndPlot(handles)

PatternsToRunFS = handles.PatternsToRunFS(:,...
                                        handles.OptimumFeatureSet);

ProbsClass = BayesClassValidationSet(PatternsToRunFS,...
               handles.TargetsToRunFS, handles.PatternsToClassify);

NPatternsToClassify = size(ProbsClass,1);
SumProbsClass       = sum(ProbsClass,2);

for IndexPatterns = 1:NPatternsToClassify
    ProbsClass(IndexPatterns,:) = ProbsClass(IndexPatterns, :) ...
                                     /SumProbsClass(IndexPatterns);
end

[Dummy, PredictionClass] = max(ProbsClass, [], 2);
[NPatterns, CClasses]    = size(ProbsClass);
axes(handles.ClassResAxes); cla reset;
set(gca,'YDir','reverse','Color',[.925 .914 .847]);
axis([-0.5 1.5 0.5 10.5]);

CumProbsClass = [zeros(NPatterns,1) cumsum(ProbsClass,2)];
ColorsToUse   = 'rgbycmk';
YLocat        = 0;

handles.SliderValue = 10 + NPatterns - ceil(handles.SliderValue);

for IndexPattern = (handles.SliderValue-9):handles.SliderValue
    YLocat = YLocat + 1;
    if IndexPattern <= NPatterns
        for IndexClass = 1:CClasses
            hold on
            text(-0.15, YLocat, num2str(IndexPattern),...
                                   'HorizontalAlignment', 'right');
            plot(CumProbsClass(IndexPattern, ...
                IndexClass:(IndexClass+1)), ...
                YLocat*ones(1,2), ...
                ColorsToUse(IndexClass), 'LineWidth', 5);
        end
        text(1.2, YLocat, num2str(PredictionClass(IndexPattern)));
    end
end

text(-0.9  ,0.5,'Pattern #');
text(0.2   ,0.5,'P(x|\Omega_i)');
text(1     ,0.5,'Predict');
axis([-0.5 1.5 0.5 10.5]);
set(gca,'Visible','off');
drawnow

axes(handles.ClassesLegendAxes);
for IndexClass = 1:CClasses
    text(0.1, IndexClass*0.5, ['Class ' num2str(IndexClass)],...
                          'Color', ColorsToUse(IndexClass));
end
axis([0 1.5 0.5 5])

% ------------- Menu Functions ------------------------------------
function OpenDataMenu_Callback(hObject, eventdata, handles)
DEMO('OpenDataFile_ClickedCallback',gcbo,[],guidata(gcbo));

function RunFsMenu_Callback(hObject, eventdata, handles)
DEMO('RunFeatSelection_ClickedCallback',gcbo,[],guidata(gcbo));

function StopFSMenu_Callback(hObject, eventdata, handles)
DEMO('StopFeatSelButton_ClickedCallback',gcbo,[],guidata(gcbo));

function StandardCrossMenu_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.ErrorEstMethod = 'Standard';
set(hObject,'Checked','on');
set(findobj(gcf,'Tag','ResubMenu'),'Checked','off');
set(findobj(gcf,'Tag','ProposedACrossMenu'),'Checked','off');
set(findobj(gcf,'Tag','ProposedABCrossMenu'),'Checked','off');
guidata(hObject, handles);

function ProposedACrossMenu_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.ErrorEstMethod = 'ProposedA';
set(hObject,'Checked','on');
set(findobj(gcf,'Tag','ResubMenu'),'Checked','off');
set(findobj(gcf,'Tag','ProposedABCrossMenu'),'Checked','off');
set(findobj(gcf,'Tag','StandardCrossMenu'),'Checked','off');
guidata(hObject, handles);

function ProposedABCrossMenu_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.ErrorEstMethod = 'ProposedAB';
set(hObject,'Checked','on');
set(findobj(gcf,'Tag','ResubMenu'),'Checked','off');
set(findobj(gcf,'Tag','ProposedACrossMenu'),'Checked','off');
set(findobj(gcf,'Tag','StandardCrossMenu'),'Checked','off');
guidata(hObject, handles);

function ResubMenu_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.ErrorEstMethod = 'Resubstitution';
set(hObject,'Checked','on');
set(findobj(gcf,'Tag','ProposedABCrossMenu'),'Checked','off');
set(findobj(gcf,'Tag','ProposedACrossMenu'),'Checked','off');
set(findobj(gcf,'Tag','StandardCrossMenu'),'Checked','off');
guidata(hObject, handles);

%---------------- FS Menu Functions -------------------------------
function SFS_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.FSMethod  =  'SFS';
FS_Method_ClearAllChecks(hObject, handles)
set(hObject,'Checked','on');
guidata(hObject, handles);

function SFFS_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.FSMethod  = 'SFFS';
FS_Method_ClearAllChecks(hObject, handles)
set(hObject,'Checked','on');
guidata(hObject, handles);

function ReliefF_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.FSMethod  = 'ReliefF';
FS_Method_ClearAllChecks(hObject, handles)
set(hObject,'Checked','on');
guidata(hObject, handles);

function SBS_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.FSMethod  =  'SBS';
FS_Method_ClearAllChecks(hObject, handles)
set(hObject,'Checked','on');
guidata(hObject, handles);

function SFBS_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings.FSMethod  = 'SFBS';
FS_Method_ClearAllChecks(hObject, handles)
set(hObject,'Checked','on');
guidata(hObject, handles);

function FS_Method_ClearAllChecks(hObject, handles)
set(findobj(gcf,'Tag','ReliefF'),'Checked','off');
set(findobj(gcf,'Tag','SFFS'),'Checked','off');
set(findobj(gcf,'Tag','SFS'),'Checked','off');
set(findobj(gcf,'Tag','SFBS'),'Checked','off');
set(findobj(gcf,'Tag','SBS'),'Checked','off');
guidata(hObject, handles);

%------------ Help Menu -------------------------------------------
function InstructionsMenu_Callback(hObject, eventdata, handles)
web([pwd '\Help\Readme.htm'])

function PubMenu_1_Callback(hObject, eventdata, handles)
open('Help\Verver_ElsSigPro_08.pdf')

function AuthorsVerverMenu_Callback(hObject, eventdata, handles)
web([pwd '\Help\AuthorsVerveridis.htm'])

function AuthorsKotroMenu_Callback(hObject, eventdata, handles)
web(['http://poseidon.csd.auth.gr/LAB_PEOPLE/CKotropoulos.htm'])
%------------------------------------------------------------------
function SettingsMenu_Callback(hObject, eventdata, handles)
global FSSettings
FSSettings = SettingsMenuFig;


text:
function [out,out_se,out_dist] = testM(M,n)
% function [out,out_se,out_dist] = testM(M,n)
%
% tests an M structure against n random permutations
% returns structures with info on the design goodness
% of the random designs.
%
% tor wager, 11/18/01

M = modelDiagnostics2(M,'noplot');

    out.energy = zeros(1,size(M.energy,2));
    out.conEnergy = zeros(1,size(M.conEnergy,2));
    out.eff_fitness = zeros(1,size(M.eff_fitness,2));
    out.eff = zeros(1,size(M.eff,2));
    out.se_contrasts = zeros(1,size(M.se_contrasts,2));
    out.resample_eff_loss = zeros(1,size(M.resample_eff_loss,2));
    out.smoothing_eff_loss = zeros(1,size(M.smoothing_eff_loss,2));
    out.vif = zeros(1,size(M.vif,2));
    out.conVif = zeros(1,size(M.conVif,2));
    out.cond = zeros(1,size(M.cond,2));
    out.conCond = zeros(1,size(M.conCond,2));
    out.conColin = zeros(size(M.conColin));
    out.hrf_eff_fitness = zeros(1,size(M.hrf_eff_fitness,2));
    out.hrf_eff = zeros(1,size(M.hrf_eff,2));
    out.hrf_eff_avg = zeros(1,size(M.hrf_eff_avg,2));
    out.cBal = zeros(1,size(M.cBal,2));

    out_se = out;
    out_dist = out;

    N = fieldnames(out);

    for j = N'
        eval([j{1} ' = [];']);
    end

warning off

for i = 1:n

    Mr = M;
    Mr.stimlist = getRandom(Mr.stimlist);

    Mr = modelDiagnostics2(Mr,'noplot');

    for j = N'
        eval(['out.' j{1} ' = out.' j{1} ' + Mr.' j{1} ';'])
        eval(['out_dist.' j{1} ' = [out_dist.' j{1} '; (Mr.' j{1} ')];'])
    end

    if mod(i,100) == 0, fprintf(1,'.'), end

end

warning on

for j = N'
    eval(['out.' j{1} ' = out.' j{1} ' / n;'])
    eval(['out_se.' j{1} ' = std(out_dist.' j{1} ') ./ sqrt(n);'])
end

return

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function y=rotqrvec(q,x)
%ROTQRVEC applies a quaternion rotation ot a vector array y=[q,x]
%
% Inputs:   q(4,1)    quaternion rotation (possibly unnormalized)
%           x(3n,...) array of 3D column vectors
%
% Outputs:  y(3n,...) array of 3D column vectors

%      Copyright (C) Mike Brookes 2011-2012
%      Version: $Id: rotqrvec.m 1640 2012-03-16 07:43:08Z dmb $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: 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
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
s=size(x);
y=reshape(rotqr2ro(q)*reshape(x,3,[]),s);

author: jtkim-kaist

repo: VAD

save_path: github-repos/MATLAB/jtkim-kaist-VAD


text:
function p = predict(theta, X)
    %PREDICT Predict whether the label is 0 or 1 using learned logistic
    %regression parameters theta
    %   p = PREDICT(theta, X) computes the predictions for X using a
    %   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)

    % we can tweak this for an AUC curve
    THRESHOLD = 0.5;

    % probably some better syntatic sugar here...
    p = sigmoid(X * theta);
    p(p >= THRESHOLD) = 1;
    p(p < THRESHOLD) = 0;

end

author: worldveil

repo: coursera-ml


text:
% UTILS Utility package for MATLAB xUnit Test Framework
%
% Array Comparison
%   compareFloats            - Compare floating-point arrays using tolerance
%
% Test Case Discovery Functions
%   isTestCaseSubclass       - True for name of TestCase subclass
%
% String Functions
%   arrayToString            - Convert array to string for display
%   comparisonMessage        - Assertion message string for comparing two arrays
%   containsRegexp           - True if string contains regular expression
%   isSetUpString            - True for string that looks like a setup function
%   isTearDownString         - True for string that looks like teardown function
%   isTestString             - True for string that looks like a test function
%   stringToCellArray        - Convert string to cell array of strings
%
% Miscellaneous Functions
%   generateDoc              - Publish test scripts in mtest/doc
%   parseFloatAssertInputs   - Common input-parsing logic for several functions

%   Steven L. Eddins
%   Copyright 2008-2009 The MathWorks, Inc.

author: ricedsp


text:
%UPQ Central image moments
%
% M = UPQ(IM, P, Q) is the PQ'th central moment of the image IM.  That is,
% the sum of I(x,y).(x-x0)^P.(y-y0)^Q where (x0,y0) is the centroid.
%
% Notes::
% - The central moments are invariant to translation.
%
% See also UPQ_POLY, MPQ, NPQ.

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB 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.
%
% MVTB 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 MVTB.  If not, see <http://www.gnu.org/licenses/>.

function m = upq(im, p, q)

    [X,Y] = imeshgrid(im);

	m00 = mpq(im, 0, 0);
	xc = mpq(im, 1, 0) / m00;
	yc = mpq(im, 0, 1) / m00;

    m = sum(sum( im.*(X-xc).^p.*(Y-yc).^q ) );

repo: machinevision-toolbox-matlab


text:
%SHAPE Abstract superclass for primitive shapes
%
% Defines concrete and abstract properties and methods which are common
% to all shape subclasses (primitives). Also contains some functions
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% Syntax:
%  (1) shape = Shape(T, s, ...)
%
% Outputs:
%  shape : Shape object. Note as Shape is abstract it cannot be
%           instantiated, hence shape is an object of a Shape subclass.
%
% Inputs:
%  T   : See transform property
%  s   : See scale property (can be input as scalar or 3-vector)
%  ... : Options - other properties in name-value pairs
%
% See documentation for information on properties and methods
% (type doc Shape into the command window)
%
% See also Box.Box CollisionModel Cone Curvilinear Cylinder.Cylinder
% Ellipsoid.Ellipsoid Sphere.Sphere surface

% LICENSE STATEMENT:
%
% This file is part of pHRIWARE.
%
% pHRIWARE 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.
%
% pHRIWARE 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 Lesser General Public
% License along with pHRIWARE.  If not, see <http://www.gnu.org/licenses/>.

classdef (Abstract) Shape

    properties
        % Short text description of object for user reference
        note = '<Add a description with note property>'
        transform = eye(4) % Transformation matrix of the shape
        scale = [1 1 1] % Scale vector of the shape, [s_x s_y s_z]
        FaceColor = pHRIWARE('blue'); % The surface property
        FaceAlpha = 1 % The surface property
        EdgeColor = pHRIWARE('navy'); % The surface property
        EdgeAlpha = 1 % The surface property
    end

    properties (Abstract)
        volume % Volume of shape

        %FACES  Logical vector of which faces to plot
        % For Boxes, faces is a 1x6 vector, whose elements correspond
        % to the faces in the negative y-z, x-z, x-y and positive y-z,
        % x-z, x-y planes, with respect to that shape's frame,
        %  in that order
        % For Curvilinears, faces is a 1x2 vector, whose elements
        %  correspond to the end faces whose centres are at the origin
        %  and not at the origin, with respect to that shape's frame,
        %  in that order
        % For Ellipsoids, faces is not currently used
        faces

        %N "Resolution" of the shape, for plotting
        % For Boxes, each face will comprise of an nxn grid of points
        % For Curvilinears, it is the equivalent of cylinder(n)
        % For Ellipsoids, it is the equivalent of sphere(n)
        n
    end

    properties (Constant)
        sym = exist('sym','class'); % Symbolic Math Toolbox install flag
    end

    methods (Abstract)
        %PLOT Plot the shape
        %
        % Plots the shape object to the current figure as a surface
        % object or objects. Only a few options are included, but a
        % graphics handle can be optionally returned for more advanced
        % demands.
        %
        % Copyright (C) Bryan Moutrie, 2013-2014
        % Licensed under the GNU General Public License, see file for
        % statement
        %
        % Syntax:
        %  (1) shape.plot()
        %  (2) shape.plot(...)
        %  (3) h = shape.plot(...)
        %
        %  (1) Plots the shape with the options specified by its
        %       various properties
        %  (2) is as per (1) but can specify over-riding values for
        %       options for the plot only, in name-value pairs
        %  (3) is as per (1) or (2) but returns a handle or vecor of
        %       handles to the surface objects plotted
        %
        % Outputs:
        %  h : graphics handle for each surface plotted
        %
        % Inputs:
        %  ... : Plotting options (which are Shape properties), in
        %         name-value pairs
        %
        % See also Shape.cloud Shape.parseopts
        h = plot(shape, varargin)

        %CLOUD Generate point cloud from shape
        %
        % Generates three arrays corresponding to the x, y and z points
        % of a shape's point data which is readable by the surface
        % function. If the shape is a Box, the third dimension of X, Y,
        % and Z is the points for each face - therefore some points are
        % duplicated (more specifically the corner and edge points)
        %
        % Copyright (C) Bryan Moutrie, 2013-2014
        % Licensed under the GNU General Public License, see file for
        % statement
        %
        % Syntax:
        %  (1) [X, Y, Z] = shape.cloud()
        %
        % Outputs:
        %  X : array of x-coordinates
        %  Y : array of y-coordinates
        %  Z : array of z-coordinates
        %
        % See also Shape.plot surface
        [X, Y, Z] = cloud(shape)

        %CHECK Check if point(s) are inside the shape
        %
        % Check to see if point(s) lie inside a primitive shape.
        % Points on the surface are treated as outside the shape.
        %
        % Copyright (C) Bryan Moutrie, 2013-2014
        % Licensed under the GNU General Public License, see file for
        % statement
        %
        % Syntax:
        %  (1) c = shape.check(x, y, z)
        %  (2) c = shape.check(p)
        %  (3) f = shape.check()
        %  (4) h = shape.check()
        %
        %  (2) is as per (1) where p = [x, y, z]
        %  (3) Requires the MuPAD symbolic mathematics toolbox
        %  (4) Repalces (3) if no MuPAD symbolic mathematics toolbox
        %
        % Outputs:
        %  c : mx1 vector, where there are m points. Each element is
        %       the logical value of the mth point being inside the
        %       shape
        %  f : anonymous function, f(x, y, z), which reduces check to a
        %       simplified, one-line evaluation
        %  h : function handle, h(x, y, z), OR h(p), which reduces
        %       check to a simplified, one-line evaluation
        %
        % Inputs:
        %  x : x-coordinate(s) of point(s), may be any size/shape
        %  y : y-coordinate(s) of point(s), may be any size/shape
        %  z : z-coordinate(s) of point(s), may be any size/shape
        %  p : An mx3 matrix, where each column is x, y, z. m may be 1.
        %
        % See also CollisionModel SerialLink.collisions sym2func
        c = check(shape, varargin)
    end

    methods
        function shape = Shape(T, s, varargin)
            shape = shape.parseopts(varargin{:});
            if ~isempty(T), shape.transform = T; end
            if ~isempty(s), shape.scale = s; end
        end

        function disp(shape)
            w = whos('shape');
            line1 = [w.class,': ',shape.note];
            line2(1:length(line1)) = '-';
            line3 = 'transform =';
            line4 = ['scale = ',mat2str(shape.scale)];
            line5 = ['volume = ',num2str(shape.volume), ' u^3'];
            if isprop(shape,'radius'),
                if ~isa(shape.radius,'function_handle') %#ok<*MCNPN>
                    line6 = ['radius = ',num2str(shape.radius)];
                else
                    line6 = ['radius = ',func2str(shape.radius)];
                end
            else
                line6 = [];
            end
            line7 = line2;
            line8 = 'Plot options:';
            line9 = ['FaceColor = ',mat2str(shape.FaceColor,2),...
                ' | FaceAlpha = ',num2str(shape.FaceAlpha)];
            line10 = ['EdgeColor = ',mat2str(shape.EdgeColor,2),...
                ' | EdgeAlpha = ',num2str(shape.EdgeAlpha)];
            line11 = ['n = ',num2str(shape.n),' | faces = ',...
                mat2str(shape.faces),];

            disp(line1);
            disp(line2);
            disp(line3);
            disp(shape.transform);
            disp(line4);
            disp(line5);
            disp(line6);
            disp(line7);
            disp(line8);
            disp(line9);
            disp(line10);
            disp(line11);
        end

        function [shape, frames] = parseopts(shape, varargin)
            %PARSEOPTS Set plot options (and more) in one line
            %
            % Parses multiple plot options to shape properties (faces,
            % n, FaceColor, FaceAlpha, EdgeColor, EdgeAlpha) in
            % name-value pairs. The note property can also be set.
            % Additionally, the pair "'animate', frames" may be used to
            % animate the shape with the transformations in frames
            % within the plot method. If not specified, is identity.
            %
            % Copyright (C) Bryan Moutrie, 2013-2014
            % Licensed under the GNU General Public License, see file
            % for statement
            %
            % Syntax:
            %  (1) [shape, frames] = shape.parseopts(...)
            %
            % Outputs:
            %  shape  : Shape object with new property values
            %  frames : Coordinate frames to animate shape. Relative to
            %            the shape's own transform.
            %
            % Inputs:
            %  ... : Options - plotting properties in name-value pairs

            frames = [];
            for i = 1: 2: length(varargin)-1
                if strcmp(varargin{i},'FaceColor')
                    shape.FaceColor = varargin{i+1};
                elseif strcmp(varargin{i},'FaceAlpha')
                    shape.FaceAlpha = varargin{i+1};
                elseif strcmp(varargin{i},'EdgeColor')
                    shape.EdgeColor = varargin{i+1};
                elseif strcmp(varargin{i},'EdgeAlpha')
                    shape.EdgeAlpha = varargin{i+1};
                elseif strcmp(varargin{i},'animate')
                        frames = varargin{i+1};
                elseif strcmp(varargin{i},'n')
                    shape.n = varargin{i+1};
                elseif strcmp(varargin{i},'faces')
                    shape.faces = varargin{i+1};
                elseif strcmp(varargin{i},'note')
                    shape.note = varargin{i+1};
                else
                    error(pHRIWARE('error','inputValue'));
                end
            end
        end

        function vargout = animate(shape, h, frames)
            %ANIMATE Animate a plotted shape
            %
            % Animate a plotted shape by applying a series of
            % transformations to its graphics handle. A handle can be
            % returned by a call to plot. Transformations for each
            % frame are applied before the shape's own transformation.
            % Animation is at a fixed 100 fps.
            %
            % Copyright (C) Bryan Moutrie, 2013-2014
            % Licensed under the GNU General Public License, see file
            % for statement
            %
            % Syntax:
            %  (1) shape.animate(h, frames)
            %  (2) h = shape.animate(h, frames)
            %
            %  (2) is as per (1) but returns graphics handle of
            %       animated shape
            %
            % Outputs:
            %  h : Modified graphics handle(s)
            %
            % Inputs:
            %  h     : Graphics handle(s) of a Shape object
            %  frames: 4x4xm array of m frames/transformation matrices
            %
            % See also Shape.plot

            t = hgtransform;
            set(h,'Parent',t);
            for i = 1: size(frames,3)
                set(t, 'Matrix', frames(:,:,i));
                pause(0.01);
            end

            if nargout == 1, vargout = h; end
        end

        function shape = set.note(shape, note)
            if ~ischar(note)
                error(pHRIWARE('error','inputType'));
            else
                shape.note = note;
            end
        end

        function shape = set.scale(shape, scale)
            shape.scale = scale .* [1 1 1]; % Allows scalar or 3-vector
        end

%         function f = dyncheck(s, points)
%             s.transform = symT * s.transform;
%             switch nargin
%                 case 1
%                     dyncheck = s.check;
%                     f = @(T,x,y,z) dyncheck(T(1),T(5),T(9),...
%                         T(2),T(6),T(10),...
%                         T(3),T(7),T(11),...
%                         T(13),T(14),T(15),x,y,z);
%                 case 2
%                     dyncheck = s.check(points);
%                     f = @(T) dyncheck(T(1),T(5),T(9),...
%                         T(2),T(6),T(10),...
%                         T(3),T(7),T(11),...
%                         T(13),T(14),T(15));
%             end
%         end
    end

    methods (Access = protected)
        function [Xst, Yst, Zst] = sat(shape, X, Y, Z)
            %SAT Scale and transform point cloud data
            X_sz = size(X);
            Y_sz = size(Y);
            Z_sz = size(Z);

            X = X(:) * shape.scale(1);
            Y = Y(:) * shape.scale(2);
            Z = Z(:) * shape.scale(3);

            P = shape.transform * [X, Y, Z, ones(size(X))]';
            Xst = reshape(P(1,:), X_sz);
            Yst = reshape(P(2,:), Y_sz);
            Zst = reshape(P(3,:), Z_sz);
        end
    end
end

author: Allopart

repo: rbpf-gmapping


text:
function [ line_num, line_data_num ] = xyl_header_read ( input_filename )

%*****************************************************************************80
%
%% XYL_HEADER_READ determines the number of line items in an XYL file.
%
%  Discussion:
%
%    This routine assumes that the file contains exactly three kinds of
%    records:
%
%    COMMENTS which begin with a '#' character in column 1;
%    BLANKS which contain nothing but 'whitespace';
%    LINE ITEMS, which are indices of points on a line.
%
%    The routine ignores comments and blanks and returns
%    the number of line items.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 February 2010
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Output, integer LINE_NUM, the number of lines.
%
%    Output, integer LINE_DATA_NUM, the number of line items.
%
  line_data_num = 0;
  line_num = 0;
%
%  Open the file.
%
  input_unit = fopen ( input_filename, 'r' );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'XYL_HEADER_READ - Error!\n' );
    fprintf ( 1, '  Could not open the input file "%s".\n', input_filename );
    error ( 'XYL_HEADER_READ - Error!' );
  end
%
%  Use FGETL, not FGETS, so we don't pick up the NEWLINE character.
%
  while ( 1 )

    text = fgetl ( input_unit );

    if ( text == -1 )
      break;
    end

    if ( text(1) == '#' || s_len_trim ( text ) == 0 )
      continue
    end

    n = s_word_count ( text );

    line_data_num = line_data_num + n;

    line_num = line_num + 1;

  end
%
%  Close the file.
%
  fclose ( input_unit );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function determinant = orth_random_determinant ( n, key )

%*****************************************************************************80
%
%% ORTH_RANDOM_DETERMINANT returns the determinant of the ORTH_RANDOM matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    17 June 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Input, integer KEY, a positive value that selects the data.
%
%    Output, real DETERMINANT, the determinant.
%
  determinant = 1.0;

  return
end


text:
function flatten_dir(in_dir, out_dir, sep_symbol)
% flatten directory (1 level only)

if ~exist('sep_symbol','var'),
  sep_symbol = '_';
end

if ~exist(out_dir,'dir'),
  mkdir(out_dir);
end

contents = dir(in_dir);
d_list = {contents.name};
d_list = setdiff(d_list([contents.isdir]),{'.','..'});

for d_name = d_list,
  d_name = d_name{1};
  % d_name = fullfile(d_name, 'allFrames');
  contents = dir(fullfile(in_dir,d_name));
  f_list = {contents.name};
  f_list = f_list(~[contents.isdir]);
  for f_name = f_list,
    f_name = f_name{1};
    copyfile(fullfile(in_dir,d_name,f_name), ...
      fullfile(out_dir,sprintf('%s%s%s',strrep(d_name,filesep,sep_symbol),sep_symbol,f_name)));
end

end

repo: ResNet-Matconvnet


text:
function obj = runPipeline(obj,varargin)
	% DESCRIPTION
	% Biafra Ahanonu
	% started: 2014.07.31 - branch from calciumImagingAnalysis 2020.05.07 [15:47:29]
	% inputs
		%
	% outputs
		%

	% changelog
		% 2020.05.09 [18:36:01] - Added a check to make sure certain directories are unloaded after running a module if they are not needed.
		% 2021.08.10 [09:57:36] - Updated to handle CIAtah v4.0 switch to all functions inside ciapkg package.
		% 2022.02.25 [09:54:56] - Eliminate the close all figure when initializing the main GUI. Unexpected for some users and undesirable in certain cases. Instead close all figures if a method is selected, this avoids user not getting feedback if figures are re-used and focus is not shifted.
	% TODO
		%

	import ciapkg.api.* % import CIAtah functions in ciapkg package API.

	try
		setFigureDefaults();
	catch err
		disp(repmat('@',1,7))
		disp(getReport(err,'extended','hyperlinks','on'));
		disp(repmat('@',1,7))
		obj.loadBatchFunctionFolders();
	end
	try
		set(0, 'DefaultUICOntrolFontSize', obj.fontSizeGui)
	catch
		set(0, 'DefaultUICOntrolFontSize', 11)
	end
	% close all;
	clc;

	fxnsToRun = obj.methodsList;
	%========================
	options.fxnsToRun = fxnsToRun;
	% get options
	options = getOptions(options,varargin);
	% disp(options)
	% unpack options into current workspace
	% fn=fieldnames(options);
	% for i=1:length(fn)
	%	eval([fn{i} '=options.' fn{i} ';']);
	% end
	%========================
	fxnsToRun = options.fxnsToRun;
	% initialDir = pwd;
	% set back to initial directory in case exited early
	% restoredefaultpath;
	% loadBatchFxns();
	if strcmp(obj.defaultObjDir,pwd)~=1
		cd(obj.defaultObjDir);
	end

	if ischar(obj.videoDir)
		obj.videoDir = {obj.videoDir};
	end

	% ensure private folders are set
	if ~exist(obj.picsSavePath,'dir');mkdir(obj.picsSavePath);end
	if ~exist(obj.dataSavePath,'dir');mkdir(obj.dataSavePath);end
	if ~exist(obj.logSavePath,'dir');mkdir(obj.logSavePath);end

	props = properties(obj);
	totSize = 0;
	% for ii=1:length(props)
	%	  currentProperty = getfield(obj, char(props(ii)));
	%	  s = whos('currentProperty');
	%	  totSize = totSize + s.bytes;
	% end
	% sprintf('%.f',totSize*1.0e-6)
	% fprintf(1, '%d bytes\n', totSize*1.0e-6);
	% runs all currently implemented view functions

	scnsize = get(0,'ScreenSize');
	dlgSize = [scnsize(3)*0.4 scnsize(4)*0.6];

	currentIdx = find(strcmp(fxnsToRun,obj.currentMethod));
	% Only keep the 1st method if it is twice in the function list.
	[~,duplicateIdx] = unique(fxnsToRun,'stable');
	currentIdx = intersect(currentIdx,duplicateIdx);
	% [idNumIdxArray, ok] = listdlg('ListString',fxnsToRun,'InitialValue',currentIdx(1),'ListSize',dlgSize,'Name','Sir! I have a plan! Select a calcium imaging analysis method or procedure to run:');

	[idNumIdxArray, fileIdxArray, ok] = obj.ciatahMainGui(fxnsToRun,['"Sir! I have a plan!" Hover over ' ciapkg.pkgName ' methods for tooltips.'],currentIdx);
	obj.foldersToAnalyze = fileIdxArray;
	bypassUI = 1;

	% [idNumIdxArray, ok] = obj.pipelineListBox(fxnsToRun,['"Sir! I have a plan!" Select a calciumImagingAnalysis method or procedure to run. Hover over items for tooltip descriptions.'],currentIdx);
	if ok==0;
		subfxnCheckDirs();
		return;
	end

	% excludeList = {'showVars','showFolders','setMainSettings','modelAddNewFolders','loadDependencies','saveObj','setStimulusSettings','modelDownsampleRawMovies'};
	% excludeListVer2 = {'modelEditStimTable','behaviorProtocolLoad','modelPreprocessMovie','modelModifyMovies','removeConcurrentAnalysisFiles'};
	% excludeListStimuli = {'modelVarsFromFiles'};
	excludeList = obj.methodExcludeList;
	excludeListVer2 = obj.methodExcludeListVer2;
	excludeListStimuli = obj.methodExcludeListStimuli;

	if isempty(intersect(fxnsToRun,excludeList))&isempty(intersect(fxnsToRun,excludeListVer2))
		% [guiIdx, ok] = listdlg('ListString',{'Yes','No'},'InitialValue',1,'ListSize',dlgSize,'Name','GUI Enabled?');
		[guiIdx, ok] = obj.pipelineListBox({'Yes','No'},['GUI Enabled?'],1);
		if ok==0; return; end
		% idNumIdxArray
		% turn off gui elements, run in batch
		obj.guiEnabled = guiIdx==1;
	end

	fxnsToRun = {fxnsToRun{idNumIdxArray}};
	obj.currentMethod = fxnsToRun{1};

	if bypassUI==0&isempty(intersect(fxnsToRun,excludeList))
		scnsize = get(0,'ScreenSize');
		usrIdxChoiceStr = obj.usrIdxChoiceStr;
		usrIdxChoiceDisplay = obj.usrIdxChoiceDisplay;
		% use current string as default
		currentIdx = find(strcmp(usrIdxChoiceStr,obj.signalExtractionMethod));
		% [sel, ok] = listdlg('ListString',usrIdxChoiceDisplay,'InitialValue',currentIdx,'ListSize',dlgSize,'Name','Get to the data! Cell extraction algorithm to use for analysis?');
		[sel, ok] = obj.pipelineListBox(usrIdxChoiceDisplay,['"Get to the data!" Cell extraction algorithm to use for analysis?'],currentIdx);

		if ok==0; return; end
		% (Americans love a winner)
		usrIdxChoiceList = {2,1};
		obj.signalExtractionMethod = usrIdxChoiceStr{sel};
	end
	if bypassUI==0&~isempty(obj.inputFolders)&isempty(intersect(fxnsToRun,excludeList))&isempty(intersect(fxnsToRun,excludeListVer2))
		if isempty(obj.protocol)
			obj.modelGetFileInfo();
		end
		folderNumList = strsplit(num2str(1:length(obj.inputFolders)),' ');
		selectList = strcat(folderNumList(:),'/',num2str(length(obj.inputFolders)),' | ',obj.date(:),' _ ',obj.protocol(:),' _ ',obj.fileIDArray(:),' | ',obj.inputFolders(:));
		% set(0, 'DefaultUICOntrolFontSize', 16)
		% select subjects to analyze
		subjectStrUnique = unique(obj.subjectStr);
		% [subjIdxArray, ok] = listdlg('ListString',subjectStrUnique,'ListSize',dlgSize,'Name','Which subjects to analyze?');
		[subjIdxArray, ok] = obj.pipelineListBox(subjectStrUnique,['Which subjects to analyze?'],1);
		if ok==0; return; end
		subjToAnalyze = subjectStrUnique(subjIdxArray);
		subjToAnalyze = find(ismember(obj.subjectStr,subjToAnalyze));
		% get assays to analyze
		assayStrUnique = unique(obj.assay(subjToAnalyze));
		% [assayIdxArray, ok] = listdlg('ListString',assayStrUnique,'ListSize',dlgSize,'Name','Which assays to analyze?');
		[assayIdxArray, ok] = obj.pipelineListBox(assayStrUnique,['Which assays to analyze?'],1);
		if ok==0; return; end
		assayToAnalyze = assayStrUnique(assayIdxArray);
		assayToAnalyze = find(ismember(obj.assay,assayToAnalyze));
		% filter for folders chosen by the user
		validFoldersIdx = intersect(subjToAnalyze,assayToAnalyze);
		% if isempty(validFoldersIdx)
		%	  continue;
		% end
		useAltValid = {'no additional filter','manual index entry','manually sorted folders','not manually sorted folders','manual classification already in obj',['has ' obj.signalExtractionMethod ' extracted cells'],['missing ' obj.signalExtractionMethod ' extracted cells'],'fileFilterRegexp','valid auto',['has ' obj.fileFilterRegexp ' movie file']};
		useAltValidStr = {'no additional filter','manual index entry','manually sorted folders','not manually sorted folders','manual classification already in obj',['has extracted cells'],'missing extracted cells','fileFilterRegexp','valid auto','movie file'};
		% [choiceIdx, ok] = listdlg('ListString',useAltValid,'ListSize',dlgSize,'Name','Choose additional folder sorting filters');
		[choiceIdx, ok] = obj.pipelineListBox(useAltValid,['Choose additional folder sorting filters'],1);
		if ok==0; return; end

		if ok==1
			useAltValid = useAltValidStr{choiceIdx};
		else
			useAltValid = 0;
		end
		% useAltValid = 0;
		[validFoldersIdx] = pipelineFolderFilter(obj,useAltValid,validFoldersIdx);

		% [fileIdxArray, ok] = listdlg('ListString',selectList,'ListSize',dlgSize,'Name','Which folders to analyze?','InitialValue',validFoldersIdx);
		[fileIdxArray, ok] = obj.pipelineListBox(selectList,['Which folders to analyze?'],validFoldersIdx);
		if ok==0; return; end

		obj.foldersToAnalyze = fileIdxArray;
		if isempty(obj.stimulusNameArray)|~isempty(intersect(fxnsToRun,excludeListVer2))|~isempty(intersect(fxnsToRun,excludeListStimuli))
			obj.discreteStimuliToAnalyze = [];
		else
			% [idNumIdxArray, ok] = listdlg('ListString',obj.stimulusNameArray,'ListSize',dlgSize,'Name','which stimuli to analyze?');
			[idNumIdxArray, ok] = obj.pipelineListBox(obj.stimulusNameArray,['Which stimuli to analyze?'],1);
			if ok==0; return; end

			obj.discreteStimuliToAnalyze = idNumIdxArray;
		end
	elseif bypassUI==0&~isempty(intersect(fxnsToRun,excludeListVer2))
		folderNumList = strsplit(num2str(1:length(obj.inputFolders)),' ');
		selectList = strcat(folderNumList(:),'/',num2str(length(obj.inputFolders)),' | ',obj.date(:),' _ ',obj.protocol(:),' _ ',obj.fileIDArray(:),' | ',obj.inputFolders(:));
		% [fileIdxArray, ok] = listdlg('ListString',selectList,'ListSize',dlgSize,'Name','Which folders to analyze?','InitialValue',1);
		[fileIdxArray, ok] = obj.pipelineListBox(selectList,['Which folders to analyze?'],1);
		if ok==0; return; end

		obj.foldersToAnalyze = fileIdxArray;
	else
		if isempty(obj.stimulusNameArray)|~isempty(intersect(fxnsToRun,excludeListVer2))|~isempty(intersect(fxnsToRun,excludeListStimuli))
			obj.discreteStimuliToAnalyze = [];
		else
			% [idNumIdxArray, ok] = listdlg('ListString',obj.stimulusNameArray,'ListSize',dlgSize,'Name','which stimuli to analyze?');
			[idNumIdxArray, ok] = obj.pipelineListBox(obj.stimulusNameArray,['Which stimuli to analyze?'],1);
			if ok==0; return; end

			obj.discreteStimuliToAnalyze = idNumIdxArray;
		end
	end

	for thisFxn = fxnsToRun
		try
			disp(repmat('!',1,21))
			close all;
			if ismethod(obj,thisFxn)
				disp(['Running: obj.' thisFxn{1}]);
				obj.(thisFxn{1});
			else
				disp(['Method not supported, skipping: obj.' thisFxn{1}]);
			end
		catch err
			disp(repmat('@',1,7))
			disp(getReport(err,'extended','hyperlinks','on'));
			disp(repmat('@',1,7))
			if strcmp(obj.defaultObjDir,pwd)~=1
				restoredefaultpath;
				cd(obj.defaultObjDir);
				ciapkg.loadBatchFxns();
				% cnmfVersionDirLoad('current','displayOutput',0);
			end
		end
	end
	obj.guiEnabled = 1;
	obj.foldersToAnalyze = [];
	% set back to initial directory in case exited early
	% restoredefaultpath;
	% loadBatchFxns();
	if strcmp(obj.defaultObjDir,pwd)~=1
		cd(obj.defaultObjDir);
	end

	subfxnCheckDirs();

	% Force back to command window.
	commandwindow

	disp([10 10 ...
	'Run processing pipeline by typing below (or clicking link) into command window (no semi-colon!):' 10 ...
	'obj'])
end
function subfxnCheckDirs()
	% Re-run load folders if certain functions are still present in the path
	fxnCheckList = {'CELLMax_Wrapper.m','extractor.m','normcorre.m'};
	if any(cellfun(@(x) ~isempty(which(x)),fxnCheckList))==1
		ciapkg.loadBatchFxns;
	end
end

author: bahanonu

repo: ciatah

save_path: github-repos/MATLAB/bahanonu-ciatah


text:
function Qa = aggfcn(Q)
%AGGFCN Aggregation function for a fuzzy system.
%   QA = AGGFCN(Q) creates an aggregation function, QA, from a set of
%   implication functions, Q. Q is a cell array of function handles as
%   returned by IMPLFCNS. QA is a function handle that can be called
%   with a single input V using the syntax: q = QA(V).
%
%   Copyright 2002-2020 Gatesmark
%
%   This function, and other functions in the DIPUM Toolbox, are based
%   on the theoretical and practical foundations established in the
%   book Digital Image Processing Using MATLAB, 3rd ed., Gatesmark
%   Press, 2020.
%
%   Book website: http://www.imageprocessingplace.com
%   License: https://github.com/dipum/dipum-toolbox/blob/master/LICENSE.txt

Qa = @aggregate;

    function q = aggregate(v)
        q = Q{1}(v);
        for i = 2:numel(Q)
            q = max(q, Q{i}(v));
        end
    end

end

author: dipum

repo: dipum-toolbox

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


text:
function sensor = sensorfield(x, y)
    xc = 60; yc = 90;
    sensor = 200./((x-xc).^2 + (y-yc).^2 + 200);


text:
% The COBRAToolbox: testRestrictModelsToFields.m
%
% Purpose:
%     - test the restrictModelsToFields function
%
% Authors:
%     - Jacek Wachowiak
global CBTDIR
% save the current path
currentDir = pwd;

% initialize the test
fileDir = fileparts(which('testRestrictModelsToFields'));
cd(fileDir);

% test variables
models{1} = getDistributedModel('ecoli_core_model.mat');
models{2} = getDistributedModel('Abiotrophia_defectiva_ATCC_49176.xml');

fieldNames = fieldnames(models{1});
fieldNames2 = fieldnames(models{2});

%test whether fields are removed:
commonfields = intersect(fieldNames,fieldNames2);
restrictedModels = restrictModelsToFields(models, commonfields);

for i = 1:numel(models)
    assert(isempty(setxor(commonfields,fieldnames(restrictedModels{i}))));
end

%Test whether random fields are retained.

fieldsKept = commonfields([1,2,3]);
restrictedModels = restrictModelsToFields(models, fieldsKept);
for i = 1:numel(models)
    assert(isempty(setxor(fieldsKept,fieldnames(restrictedModels{i}))));
end

%leave all fields in
allFields = union(fieldNames,fieldNames2);
restrictedModels = restrictModelsToFields(models, allFields);

% test
assert(isSameCobraModel(restrictedModels{1}, models{1}));
assert(isSameCobraModel(restrictedModels{2}, models{2}));

% change to old directory
cd(currentDir);

author: opencobra

repo: cobratoolbox


text:
function [pos_dot, vel_dot] = satellite_motion_diff_eq(pos, vel, acc, a, GM, J2, Omegae_dot)

% SYNTAX:
%   [pos_dot, vel_dot] = satellite_motion_diff_eq(pos, vel, acc, a, GM, J2, Omegae_dot);
%
% INPUT:
%   pos = satellite position (XYZ)
%   vel = satellite velocity
%   acc = acceleration due to lunar-solar gravitational perturbation
%   a   = ellipsoid semi-major axis [m]
%   GM  = gravitational constant (mass of Earth) [m^3/s^2]
%   J2  = second zonal harmonic of the geopotential
%   Omegae_dot = angular velocity of the Earth rotation [rad/s]
%                (if provided, an Earth-fixed system will be used)
%
% OUTPUT:
%   pos_dot = differential position
%   vel_dot = differential velocity
%
% DESCRIPTION:
%   Computation of the differential equations of perturbed orbital motion.

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:
%  Contributors:     ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

if (nargin < 6)
    %do the computation in an inertial system
    Omegae_dot = 0;
end

%differential position
pos_dot = vel;

%renaming variables for better readability
%
%position
x = pos(1);
y = pos(2);
z = pos(3);
%velocity
vx = vel(1);
vy = vel(2);
%acceleration (i.e. perturbation)
ax = acc(1);
ay = acc(2);
az = acc(3);

%parameters
r = sqrt(x^2 + y^2 + z^2);
g = -GM/r^3;
h = J2*1.5*(a/r)^2;
k = 5*z^2/r^2;

%differential velocity
vel_dot = zeros(size(vel));
vel_dot(1) = g*x*(1 - h*(k - 1)) + ax + Omegae_dot^2*x + 2*Omegae_dot*vy;
vel_dot(2) = g*y*(1 - h*(k - 1)) + ay + Omegae_dot^2*y - 2*Omegae_dot*vx;
vel_dot(3) = g*z*(1 - h*(k - 3)) + az;

author: goGPS-Project


text:
function cvt_test04 ( )

%*****************************************************************************80
%
%% CVT_TEST04 repeats test 1 with uniform initialization and Halton sampling.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 November 2006
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST04\n' );
  fprintf ( 1, '  CVT computes a Centroidal Voronoi Tessellation.\n' );
  fprintf ( 1, '  Repeat test 1, but with Halton sampling.\n' );

  dim_num = 2;
  n = 10;
  batch = 1000;
  init = 0;
  init_string = 'uniform';
  it_max = 40;
  it_fixed = 1;
  sample = 1;
  sample_num = 10000;
  sample_string = 'halton';
  seed = 123456789;
  r = [];

  seed_init = seed;

  [ r, seed, it_num, it_diff, energy ] = cvt ( dim_num, n, batch, init, ...
    sample, sample_num, it_max, it_fixed, seed, r );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Dimension DIM_NUM =        %12d\n', dim_num );
  fprintf ( 1, '  Number of points N =       %12d\n', n );
  fprintf ( 1, '  Initial SEED =             %12d\n', seed_init );
  fprintf ( 1, '  Current SEED =             %12d\n', seed );
  fprintf ( 1, '  INIT =                    "%s".\n', init_string );
  fprintf ( 1, '  Max iterations IT_MAX =    %12d\n', it_max );
  fprintf ( 1, '  IT_FIXED (fixed samples) = %12d\n', it_fixed );
  fprintf ( 1, '  Iterations IT_NUM =        %12d\n', it_num );
  fprintf ( 1, '  Difference IT_DIFF =       %14f\n', it_diff );
  fprintf ( 1, '  CVT ENERGY =               %14f\n', energy );
  fprintf ( 1, '  SAMPLE =                  "%s".\n', sample_string );
  fprintf ( 1, '  Samples SAMPLE_NUM    =    %12d\n', sample_num );
  fprintf ( 1, '  Sampling BATCH size =      %12d\n', batch );
  fprintf ( 1, '  EPSILON (unit roundoff) =  %12e\n', eps );

  r8mat_transpose_print ( dim_num, n, r, '  Generators (rows):' );

  return
end


text:
function rpy = quat2elu(qw, qx, qy, qz)

sinr_cosp = 2 * qw .* qx + qy .* qz;
cosr_cosp = 1 - 2 * qx .* qx + qy .* qy;
roll = atan2(sinr_cosp, cosr_cosp);

sinp = 2 * (qw .* qy - qz .* qx);
% remove out of range
sinp(sinp > 1) = 1;
sinp(sinp < -1) = -1;

pitch = asin(sinp);

siny_cosp = 2 * (qw .* qz + qx .* qy);
cosy_cosp = 1 - 2 * (qy .* qy + qz .* qz);
yaw = atan2(siny_cosp, cosy_cosp);

rpy = [roll, pitch, yaw];

author: TakaHoribe


text:
function [node,elem,u] = ellipsoidPoisson

maxIt = 5;
err = zeros(maxIt,1);
% ----------------------- generate initial mesh ---------------
node = [1,0,0; 0,1,0; -1,0,0; 0,-1,0; 0,0,1; 0,0,-1];
elem = [6,1,2; 6,2,3; 6,3,4; 6,4,1; 5,1,4; 5,3,4; 5,3,2; 5,2,1];
% node = [1,0,0; 0,1,0; -1,0,0; 0,-1,0; 0,0,1];
% elem = [5,1,4; 5,3,4; 5,3,2; 5,2,1];
showmesh(node,elem)
for i=1:3
    [node,elem] = uniformrefine(node,elem);
    %[node,elem] = uniformbisect(node,elem);
end
% project the mesh to the ellipsoid
r = sqrt(node(:,1).^2+node(:,2).^2+node(:,3).^2);
node = node./[r r r];
node(:,1) = 3*node(:,1); node(:,2) = 2*node(:,2);
showmesh(node,elem);

for k=1:maxIt
%    [u,A] = surfacePoisson(node,elem,[],@f,@g_D,[]);
    [u,A] = surfacePoisson(node,elem,[],@f,[],[]);
    uI = exactu(node);
    err(k) = sqrt(u-uI)'*A*(u-uI);
    [node,elem] = uniformbisect(node,elem);
    r = sqrt(node(:,1).^2+node(:,2).^2+node(:,3).^2);
    node = node./[r r r];
    node(:,1) = 3*node(:,1); node(:,2) = 2*node(:,2);
end
plot(err)
end

%---------------- Data of PDE-----------------------------
function z = f(p) % load data (right hand side function)
z = 2*p(:,1);
end
%--------------------------------------------------------------------------
function z = g_D(p) % Dirichlet boundary condition
z = exactu(p);
end
%--------------------------------------------------------------------------
function z = exactu(p)   % exact solution
z = p(:,1);
end
%--------------------------------------------------------------------------

repo: Aero-matlab


text:
% Fixed-budget kernel least mean squares (FB-KLMS) algorithm.
%
% D. Rzepka, "Fixed-budget kernel least mean squares," 2012 IEEE 17th
% Conference on Emerging Technologies & Factory Automation (ETFA), Krakow,
% Poland, Sept. 2012, http://dx.doi.org/10.1109/ETFA.2012.6489767
%
% Remark: code contributed by Dominik Rzepka
%
% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.
% https://github.com/steven2358/kafbox/

classdef fbklms < kernel_adaptive_filter

    properties (GetAccess = 'public', SetAccess = 'private') % parameters
        nu = .05; % growth criterion threshold
        M = 500; % dictionary size
        eta = .5; % learning rate
        kerneltype = 'gauss'; % kernel type
        kernelpar = 1; % kernel parameter
    end

    properties (GetAccess = 'private', SetAccess = 'private') % variables
        dict = []; % dictionary
        diagkdict = []; % diagonal of kernel matrix for dictionary
        alpha = []; % expansion coefficients
    end

    methods
        function kaf = fbklms(parameters) % constructor
            if (nargin > 0) % copy valid parameters
                for fn = fieldnames(parameters)'
                    if ismember(fn,fieldnames(kaf))
                        kaf.(fn{1}) = parameters.(fn{1});
                    end
                end
            end
        end

        function y_est = evaluate(kaf,x) % evaluate the algorithm
            if size(kaf.dict,1)>0
                k = kernel(kaf.dict,x,kaf.kerneltype,kaf.kernelpar);
                y_est = k'*kaf.alpha;
            else
                y_est = zeros(size(x,1),1);
            end
        end

        function train(kaf,x,y) % train the algorithm
            if size(kaf.dict,2)==0 % initialize
                kaf.dict = x;
                k = kernel(kaf.dict,x,kaf.kerneltype,kaf.kernelpar);
                kaf.diagkdict(1) = k;
                kaf.alpha = kaf.eta*y*k/(k'*k);
            else

                kt = kernel([kaf.dict;x],x,kaf.kerneltype,kaf.kernelpar);
                k = kt(1:end-1);
                y_est = k'*kaf.alpha;
                e = y - y_est;

                kaf.alpha = kaf.alpha + kaf.eta*e*k/(k'*k);

                % growth criterion
                kx = kt(end);
                dependency = kx - k./kaf.diagkdict;
                if min(dependency) >= kaf.nu % expand dictionary
                    kaf.dict = [kaf.dict; x];
                    kaf.diagkdict = [kaf.diagkdict; kx];
                    kaf.alpha = [kaf.alpha; kaf.eta*e/(k'*k)];

                    if length(kaf.alpha) > kaf.M % prune dictionary
                        [~, id] = min(abs(kaf.alpha));
                        kaf.dict(id,:) = [];
                        kaf.diagkdict(id) = [];
                        kaf.alpha(id) = [];
                    end
                end
            end
        end
    end
end

repo: kafbox


text:
function [CIX,RegThres] = ChooseTopPercentOfFish(nCells_total,prct_const,Corr_cols)
[Corr_sorted,IX_corr] = sort(Corr_cols,2,'descend');

nCells_target = round(prct_const/100 * nCells_total);

% if 0
%     Msk_IDs = 114; % mask for full hindbrain
%
%     % isScreenMskFromAllCells
%     cIX = (1:length(absIX))';
%     gIX = ones(size(cIX));
%     [cIX_hb,gIX_hb] = ScreenCellsWithMasks(Msk_IDs,cIX,gIX,MASKs,CellXYZ_norm,absIX);
%
%     I_hb = ismember(IX_corr,cIX_hb);
%     cum_I_hb1 = cumsum(I_hb(1,:));
%     cum_I_hb2 = cumsum(I_hb(2,:));
%     lastIX{1} = find(cum_I_hb1==nCells_target,1,'first');
%     lastIX{2} = find(cum_I_hb2==nCells_target,1,'first');
% else

%%
nCol = size(Corr_cols,1);
lastIX = cell(1,nCol);
CIX = cell(1,nCol);
RegThres = cell(1,nCol);
for i_col = 1:nCol
    lastIX{i_col} = nCells_target;
    CIX{i_col} = IX_corr(i_col,1:lastIX{i_col})';
    RegThres{i_col} = Corr_sorted(i_col,lastIX{i_col});
end
% end

author: xiuyechen

repo: FishExplorer


text:
%% brute_force_tune
% Code to test the performance of various tuning parameters
% Works sorta like RANSAC I guess?
% Adam Werries 2016, see Apache 2.0 license.

k_max = 40;
% Specify ranges
init_b_a_unc = linspace(10,3000,100);
init_b_g_unc = linspace(0,500,100);
% Repeat arrays
init_b_a_unc = repmat(init_b_a_unc, [1 k_max]);
init_b_g_unc = repmat(init_b_g_unc, [1 k_max]);
% Generate random selections of each vector
num_items = length(init_b_a_unc);
ba_i = randperm(num_items);
bg_i = randperm(num_items);
rms_error_filter = zeros(1,num_items);
max_error_filter = zeros(1,num_items);
parfor i = 1:num_items
    fprintf('Iteration: %d, aBiasUnc: %08.3f, gBiasUnc: %08.3f\n', i, init_b_a_unc(ba_i(i)), init_b_g_unc(bg_i(i)));
    temp_conf = LC_KF_config;
    temp_conf.init_b_a_unc = init_b_a_unc(ba_i(i)) * mug_to_mps2;
    temp_conf.init_b_g_unc = init_b_g_unc(bg_i(i)) * deg_to_rad / 3600;
    [out_profile,out_IMU_bias_est,out_KF_SD] = Loosely_coupled_INS_GNSS(init_cond, filter_time, epoch, lla, gps, imu, temp_conf, est_IMU_bias);
    xyz = out_profile(:,2:4);
    llh = ecef2lla(xyz);
    [x,y] = deg2utm(llh(:,1),llh(:,2));
    x = x-min_x;
    y = y-min_y;

    distance = ((ground_truth_full(:,1)-x).^2 + (ground_truth_full(:,2)-y).^2).^0.5;
    rms_error_filter(i) = rms(distance);
    max_error_filter(i) = max(distance);
end

[minmax, i] = min(max_error_filter);
fprintf('\nBest max: %08.3f, rms is %08.3f\n', minmax, rms_error_filter(i));
fprintf('Best iteration for max: %d, aBiasUnc: %08.3f, gBiasUnc: %08.3f\n', i, init_b_a_unc(ba_i(i)), init_b_g_unc(bg_i(i)));
[minrms, i] = min(rms_error_filter);
fprintf('Best rms: %08.3f, max is %08.3f\n', minrms, max_error_filter(i));
fprintf('Best iteration for rms: %d, aBiasUnc: %08.3f, gBiasUnc: %08.3f\n', i, init_b_a_unc(ba_i(i)), init_b_g_unc(bg_i(i)));

author: awerries

repo: kalman-localization


text:
function [J, grad] = costFunction(theta, X, y)
    %COSTFUNCTION Compute cost and gradient for logistic regression
    %   J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
    %   parameter for logistic regression and the gradient of the cost
    %   w.r.t. to the parameters.

    % Initialize some useful values
    n = length(y); % number of training examples

    % cost: J
    J = -1/n * sum(...
        y      .* log(sigmoid(X * theta)) + ...
        (1 - y) .* log(1 - sigmoid(X * theta)) ...
    );

    % gradient: compute as the derivative of the cost function
    grad = 1/n * X' * ((sigmoid(X * theta)) - y);

end


text:
%demo
clc;
clear
a0=10;a1=5;a2=-4;a3=0;a4=-2;a5=0;
b1=-3;b2=15;b3=0;b4=0;b5=0;
w0=2; % a pulse (rd/s) of a signal y
pas=pi/10
t=0:pas:pi-pas; % in this examle a period is T=2pi/w0=2pi/2=pi
y=a0+a1*cos(w0*t)+b1*sin(w0*t)+a2*cos(2*w0*t)+b2*sin(2*w0*t)+a4*cos(4*w0*t);
%note that a wmax=4*w0=8rd/s which means that a sample pulse we must be
%>=2*wmax , we>= 16rd/s, then pas<= 2pi/16 (Shanon theorem)
plot(t,y);
[wc,w0,a0,ak,bk,c0,ck]=get_harmonics(y,pas);
figure;
stem(wc,abs(ck));
xlabel('pulse w(rd/s)');
ylabel('abs(C_k)')
title ('Amplitude spectrum')
[a0 ak(1:5) bk(1:5)]
%check the ak and bk

author: Sable

repo: mcbench-benchmarks


text:
function closeAllFigures(fig_handle)
% Close all the dockable figures
% goGPS main windows are not dockable and will remain open ^_^
%
% SINTAX:
%   closeAllFigures(<fig_handles>);
%   closeAllFigures()
%
% EXAMPLE:
%   dockAllFigures();
%
% INPUT:
%   fig_handles = listo of handlers to the figure to close        <optional argument>
%
% DEFAULT VALUES:
%   fig_handle all the figures
%

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:       Andrea Gatti
%  Contributors:     Andrea Gatti ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   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/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------
    if (nargin == 1)
        set(fig_handle,'WindowStyle','docked');
    else
        all_fh = findall(0,'Type','figure');
        for fid = 1:length(all_fh)
            if numel(all_fh(fid).DockControls) ~= 3
                delete(all_fh(fid));
            end
        end
    end
end


text:
function display(pot)

disp('moment Gaussian potential object');
disp(struct(pot));

repo: bnt