text:
function [all_theta] = oneVsAll(X, y, num_labels, lambda)
%ONEVSALL trains multiple logistic regression classifiers and returns all
%the classifiers in a matrix all_theta, where the i-th row of all_theta
%corresponds to the classifier for label i
%   [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels
%   logistic regression classifiers and returns each of these classifiers
%   in a matrix all_theta, where the i-th row of all_theta corresponds
%   to the classifier for label i

% Some useful variables
m = size(X, 1);
n = size(X, 2);

% You need to return the following variables correctly
all_theta = zeros(num_labels, n + 1);

% Add ones to the X data matrix
X = [ones(m, 1) X];

% ====================== YOUR CODE HERE ======================
% Instructions: You should complete the following code to train num_labels
%               logistic regression classifiers with regularization
%               parameter lambda.
%
% Hint: theta(:) will return a column vector.
%
% Hint: You can use y == c to obtain a vector of 1's and 0's that tell you
%       whether the ground truth is true/false for this class.
%
% Note: For this assignment, we recommend using fmincg to optimize the cost
%       function. It is okay to use a for-loop (for c = 1:num_labels) to
%       loop over the different classes.
%
%       fmincg works similarly to fminunc, but is more efficient when we
%       are dealing with large number of parameters.
%
% Example Code for fmincg:
%
%     % Set Initial theta
%     initial_theta = zeros(n + 1, 1);
%
%     % Set options for fminunc
%     options = optimset('GradObj', 'on', 'MaxIter', 50);
%
%     % Run fmincg to obtain the optimal theta
%     % This function will return theta and the cost
%     [theta] = ...
%         fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
%                 initial_theta, options);
%

for c = 1:num_labels
    initial_theta = zeros(n + 1, 1);
    options = optimset('GradObj', 'on', 'MaxIter', 50);
    [theta] = ...
         fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
                 initial_theta, options);
    all_theta(c, :) = theta(:)';
end

% =========================================================================

end

author: imLogM


text:
function x = flush(x)
x.leftfactors = [];
x.rightfactors = [];
x.midfactors = [];

author: zarathustr

repo: LibQPEP

save_path: github-repos/MATLAB/zarathustr-LibQPEP


text:
% Version 1.000
%
% Code provided by Ruslan Salakhutdinov and Geoff Hinton
%
% Permission is granted for anyone to copy, use, modify, or distribute this
% program and accompanying programs and documents for any purpose, provided
% this copyright notice is retained and prominently displayed, along with
% a note saying that the original programs are available from our
% web page.
% The programs and documents are distributed without any warranty, express or
% implied.  As the programs were written for research purposes only, they have
% not been tested to the degree that would be advisable in any important
% application.  All use of these programs is entirely at the user's own risk.

% This program reads raw MNIST files available at
% http://yann.lecun.com/exdb/mnist/
% and converts them to files in matlab format
% Before using this program you first need to download files:
% train-images-idx3-ubyte.gz train-labels-idx1-ubyte.gz
% t10k-images-idx3-ubyte.gz t10k-labels-idx1-ubyte.gz
% and gunzip them. You need to allocate some space for this.

% This program was originally written by Yee Whye Teh

% Work with test files first
fprintf(1,'You first need to download files:\n train-images-idx3-ubyte.gz\n train-labels-idx1-ubyte.gz\n t10k-images-idx3-ubyte.gz\n t10k-labels-idx1-ubyte.gz\n from http://yann.lecun.com/exdb/mnist/\n and gunzip them \n');

f = fopen('t10k-images.idx3-ubyte','r');
[a,count] = fread(f,4,'int32');

g = fopen('t10k-labels.idx1-ubyte','r');
[l,count] = fread(g,2,'int32');

fprintf(1,'Starting to convert Test MNIST images (prints 10 dots) \n');
n = 1000;

Df = cell(1,10);
for d=0:9,
  Df{d+1} = fopen(['test' num2str(d) '.ascii'],'w');
end;

for i=1:10,
  fprintf('.');
  rawimages = fread(f,28*28*n,'uchar');
  rawlabels = fread(g,n,'uchar');
  rawimages = reshape(rawimages,28*28,n);

  for j=1:n,
    fprintf(Df{rawlabels(j)+1},'%3d ',rawimages(:,j));
    fprintf(Df{rawlabels(j)+1},'\n');
  end;
end;

fprintf(1,'\n');
for d=0:9,
  fclose(Df{d+1});
  D = load(['test' num2str(d) '.ascii'],'-ascii');
  fprintf('%5d Digits of class %d\n',size(D,1),d);
  save(['test' num2str(d) '.mat'],'D','-mat');
end;

% Work with trainig files second
f = fopen('train-images.idx3-ubyte','r');
[a,count] = fread(f,4,'int32');

g = fopen('train-labels.idx1-ubyte','r');
[l,count] = fread(g,2,'int32');

fprintf(1,'Starting to convert Training MNIST images (prints 60 dots)\n');
n = 1000;

Df = cell(1,10);
for d=0:9,
  Df{d+1} = fopen(['digit' num2str(d) '.ascii'],'w');
end;

for i=1:60,
  fprintf('.');
  rawimages = fread(f,28*28*n,'uchar');
  rawlabels = fread(g,n,'uchar');
  rawimages = reshape(rawimages,28*28,n);

  for j=1:n,
    fprintf(Df{rawlabels(j)+1},'%3d ',rawimages(:,j));
    fprintf(Df{rawlabels(j)+1},'\n');
  end;
end;

fprintf(1,'\n');
for d=0:9,
  fclose(Df{d+1});
  D = load(['digit' num2str(d) '.ascii'],'-ascii');
  fprintf('%5d Digits of class %d\n',size(D,1),d);
  save(['digit' num2str(d) '.mat'],'D','-mat');
end;

dos('rm *.ascii');

repo: DeepFi


text:
function [data,Qgp,Qvb,ax] = novac2010_mohsst5(data, Qgp, Qvb)

if nargin < 1 || isempty(data)
  data = mohsst5_loaddata;
end

if nargin < 2 || isempty(Qgp)
  % GPPCA dates, e.g., 20091001 (crashed), 20090824, 20090820 (crashed),
  % 20090819 (crashed)
  Qgp = load(['mohsst5_weighted_testsize=20_D=80_Wcov=se_Wden=30_Xcov=se-' ...
              'per-cs_Xden=5_iter=200_date=20090824'], 'W', 'varW', 'X', ...
             'varX', 'tau', 'pseudoX', 'Xp', 'CovXp', 'logthetaX', ...
             'covfuncX');
% $$$   Qgp = load(['mohsst5_weighted_testsize=20_D=80_Wcov=se_Wden=30_Xcov=se-' ...
% $$$               'per-cs_Xden=5_iter=50_date=20090604'], 'W', 'varW', 'X', ...
% $$$              'varX', 'tau', 'loglikelihood');
end

if nargin < 3
  % VBPCA
  Qvb = load(['mohsst5_weighted_VBPCA_testsize=20_D=80_iter=50_date=' ...
              '20090601']);
  % Do rotation for some components
  Qvb.A(:,4) = -Qvb.A(:,4);
  Qvb.S(4,:) = -Qvb.S(4,:);

end

weights = sqrt(cosd(data.coordinates(2,:)));
lands = colsum(~isnan(data.observations)) == 0;
if rows(Qgp.W) == 1727 % t
  D = cols(Qgp.W);
  disp('The results are not ready? Fill the lands and use inverse weights..')
  W = zeros([rows(data.observations),D]);
  varW = W;
  W(~lands,:) = Qgp.W;
  varW(~lands,:) = Qgp.varW;
  Qgp.W = bsxfun(@rdivide, W, weights(:));
  Qgp.varW = bsxfun(@rdivide, varW, weights(:).^2);
end

% $$$ totally_missing_columns = sum( sum(~isnan(data.observations),1) == 0)
% $$$ return

[M,N] = size(data.observations);

% Choose what to show
plot_comps = false;
mixing_weights = true;

% $$$
% $$$ % Plot spatial and temporal components
% $$$ if plot_comps
% $$$
% $$$   % GPFA
% $$$   [mapfigh, tsfigh] = mohsst5_plotexperiment(data, Qgp, true, 1:4);
% $$$
% $$$   % Saturate the second component
% $$$   warning('Saturating the second spatial component of GPFA!')
% $$$   ax = findobj(mapfigh, 'type', 'axes')
% $$$   set(ax(6), 'clim', [-0.7 0.7]);
% $$$   set(ax(4), 'clim', [-0.9 0.9]);
% $$$ %  return
% $$$
% $$$ % $$$   print(mapfigh, '-depsc2', ['/home/jluttine/papers/2009NIPS/' ...
% $$$ % $$$                     'fig_experiment_loadings_gppca.eps']);
% $$$ % $$$   print(tsfigh, '-depsc2', ['/home/jluttine/papers/2009NIPS/' ...
% $$$ % $$$                     'fig_experiment_timeseries_gppca.eps']);
% $$$
% $$$   % VBPCA
% $$$   [mapfigh, tsfigh] = mohsst5_plotexperiment(data, Qvb, false, 1:4);
% $$$
% $$$   % Saturate the VBPCA components
% $$$   warning('Saturating VBPCA components');
% $$$   ax = findobj(mapfigh, 'type', 'axes')
% $$$   set(ax(8), 'clim', [-1 1]);
% $$$   set(ax(6), 'clim', [-0.8 0.8]);
% $$$   set(ax(4), 'clim', [-0.7 0.7]);
% $$$   set(ax(2), 'clim', [-0.7 0.7]);
% $$$
% $$$ % $$$   print(mapfigh, '-depsc2', ['/home/jluttine/papers/2009NIPS/' ...
% $$$ % $$$                     'fig_experiment_loadings_vbpca.eps']);
% $$$ % $$$   print(tsfigh, '-depsc2', ['/home/jluttine/papers/2009NIPS/' ...
% $$$ % $$$                     'fig_experiment_timeseries_vbpca.eps']);
% $$$ end

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

% Mixing weights from the GP components to PCA components
if mixing_weights

  indsX = 1:N;

  %%%% FOR VBPCA %%%%

  if true

    % DON'T ROTATE VBPCA RESULTS BECAUSE THE COVARIANCE MATRIX Av IS
    % CORRUPTED!!!!
    %
    % An adhoc solution:
    Av = covcell_to_covarray(Qvb.Av);
    Av(:) = 0;

    plot_pca_components(Qvb.A, Av, Qvb.S, covcell_to_covarray(Qvb.Sv), ...
                        data,'VBPCA', indsX, false);

  end

  %%%% FOR GPPCA %%%%

  %% Preprocess

  spatial_pca = false;

  if ~spatial_pca
    % First, remove bias and scale the GP components to unit variance
    X0 = bsxfun(@minus, Qgp.X, mean(Qgp.X,2));
    % Scale to unit variance
    xx = var(X0,1,2) + mean(Qgp.varX,2); % variance whitening
    sqrtxx = sqrt(xx);
    varX = bsxfun(@rdivide, Qgp.varX, xx);
    X = bsxfun(@rdivide, X0, sqrtxx);
    varW = bsxfun(@times, Qgp.varW, xx');
    W = bsxfun(@times, Qgp.W, sqrtxx');
  else
    disp('Plotting spatial PCA, is this correct??')
    % First, remove bias and scale the GP components to unit variance
    W0 = bsxfun(@minus, Qgp.W, mean(Qgp.W,1));
    % Scale to unit variance
    xx = mean(Qgp.X.^2,2) + mean(Qgp.varX,2); % 2nd moment whitening
    % xx = var(Qgp.X,1,2) + mean(Qgp.varX,2); % variance whitening
    sqrtxx = sqrt(xx);
    varX = bsxfun(@rdivide, Qgp.varX, xx);
    X = bsxfun(@rdivide, Qgp.X, sqrtxx);
    varW = bsxfun(@times, Qgp.varW, xx');
    W = bsxfun(@times, W0, sqrtxx');
  end

  % Variances to covariance matrices
  [M,D] = size(W);
  [D,N] = size(X);
  CovX = zeros([D D N]);
  for n=1:N
    CovX(:,:,n) = diag(varX(:,n));
  end
  CovW = zeros([D D M]);
  for m=1:M
    CovW(:,:,m) = diag(varW(m,:));
  end

  plot_pca_components(W,CovW,X, CovX,data,'GPPCA', indsX, true);

end

function [W,CovW,X,CovX,R,scaledR] = plot_pca_components(W,CovW,X,CovX, ...
                                                  data,method, indsX, rotate)

[M,D] = size(W);
[D,N] = size(X);

if nargin < 7 || isempty(indsX)
  indsX = 1:N;
end
if nargin < 8 || isempty(rotate)
  rotate = true;
end

% Ignore the not requested indices
X(:,setdiff(1:N,indsX)) = 0;
CovX(:,:,setdiff(1:N,indsX)) = 0;

% Ignore land areas
lands = colsum(~isnan(data.observations)) == 0;
W(lands,:) = 0;
CovW(:,:,lands) = 0;

weights2 = cosd(data.coordinates(2,:));
if rotate
  % Rotate to pca
  [W,CovW,X,CovX,R] = rotate_to_pca(W,CovW,X,CovX,weights2);
else
  R = eye(D);
end

% Evaluate explained variance for each component
WW = W'*diag(weights2)*W;
for m=1:M
  WW = WW + weights2(m) * CovW(:,:,m);
end

% Debug stuff:
%XX = X*X' + sum(CovX,3)
%error = mean(mean( abs(W*X - W_old*X_old) ))

%WW10 = WW(1:20,1:20)
S = sqrt(diag(diag(WW/size(W,1))));
scaledR = S*R;

if strcmpi(method, 'gppca')
  % Change the sign of some components
  R = eye(D);
  R(1,1) = -1;
  R(2,2) = -1;
  W = W * R;
  X = R * X;
end
if strcmpi(method, 'vbpca')
  % Change the sign of some components
  R = eye(D);
  R(3,3) = -1;
  W = W * R;
  X = R * X;
end

if true
  % Plot temporal PCA components
  Xpca = X;
  varXpca = zeros(size(X));
  for n=1:N
    varXpca(:,n) = diag(CovX(:,:,n));
  end
  eX = 2*sqrt(varXpca);
  hax = tsgpplot(data.time, Xpca(1:4,:)', eX(1:4,:)');

  % Publication style
  for j = 1:length(hax)
    xlim(hax(j), [min(data.time) max(data.time)]);
    set( hax(j), 'YTick', [] )
    set( hax(j), 'YTickLabel', [] )
    datetick(hax(j), 'x', 10, 'keeplimits');
    if j ~= length(hax)
      set(hax(j), 'xticklabel', []);
    end
  end
% $$$   set(gcf, 'Units', 'centimeters');
% $$$   pos = get(gcf, 'Position');
% $$$   figw = 35;
% $$$   figh = 8;
% $$$   set(gcf, 'Position', [pos(1) pos(2) figw figh]);
% $$$   set(gcf, 'PaperPositionMode', 'auto', 'PaperSize', [figw figh]);
  set_subplot_positions(hax, 4,1, [0.01 0.01 0.01 0.3], [0.01 0.01]);
  set_ticks_fontsize(hax, 5);
  set_figure_size(gcf, 13, 7);
  filename = sprintf(['/home/jluttine/thesis/figures/' ...
                      'novac2010_experiment_timeseries_%s.eps'], lower(method));
  print(gcf, '-depsc2', filename);
end

if true
  % Plot spatial PCA components
  figure
  mapproj('global-ellipse');
  [LON,LAT] = meshgrid(data.longitude, data.latitude);
  comps = 1:4;
  hax = [];
  h_cb = [];
  for d=comps
    subplot(1,4,d)
    set(gca, 'xtick', [], 'ytick', []);
    mappcolor(LON, LAT, reshape(W(:,d), size(LON)));
    h_cb(d) = colorbar('SouthOutside');
    hax(d) = gca;
    mapcoast;

    if strcmpi(method, 'vbpca')
      switch d
       case 1
        disp('Saturating vbpca 1-component')
        set(gca, 'clim', [-0.8 0.8]);
       case 2
        disp('Saturating vbpca 2-component')
        set(gca, 'clim', [-0.8 0.8]);
       case 4
        disp('Saturating vbpca 4-component')
        set(gca, 'clim', [-0.8 0.8]);
      end
    end
  end

  % Publication style:
  set_subplot_positions(hax, 1,4, [0.01 0.01 0.01 0.3], [0.01 0.01]);
  set_colorbar_position(h_cb, hax, 0.04, 0.04);
  set(h_cb, 'FontSize', 5);
  set_figure_size(gcf, 13, 2.3);
  filename = sprintf(['/home/jluttine/thesis/figures/' ...
                      'novac2010_experiment_loadings_%s.eps'], lower(method));
  print(gcf, '-depsc2', filename);

end

author: jluttine

repo: matlab

save_path: github-repos/MATLAB/jluttine-matlab


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Max manipulability index ALONG A LINE.
% Use stomp like to optimize along a surface/line
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function experiment1B
close all;
global robot
global parameters
global hfigures

%STOMP PARAMETERS
%conversion from cost to Prob factor
parameters.lambda = .4;
parameters.lambda_obstacles = .2;
%height of the obstacle
parameters.yo = 2.5;
%cost function starts at this distance
%must be below 0.3 for the 4 DOF robot
parameters.epsilon = 0.2;
%multiply noise by this facto
%parameters.noise_k = 5;
%parameters.noise_sigma_null_space = 0.01;
parameters.alpha=0.02;
parameters.time_step=0.01;

%number of waypoints
parameters.N = 12;
%number of particles
parameters.K = 10;
parameters.n_repeat = 30;
parameters.experiment_name = 'experiment1B_K10_N30.mat';

parameters.animate = 0;

parameters.obstacles = [];

%LINE 1
x1 = -1.5;
y1 = .5; %m
x2 = 0;
y2 = 2; %m
phi = 3*pi/4;
p0 = [x1 y1 0]';
pf = [x2 y2 0]';
T0 = build_T_4dof(p0, phi);
parameters.obstacles{1}.line = [p0 pf];
parameters.obstacles{1}.T0 = T0;

%repeat the experiment E times
random_manips=[];
Gout = [];
for i=1:parameters.n_repeat
    close all
    [pk, final_manip] = stomp_null_space(robot);
    Gout{i}=pk;
    random_manips = [random_manips; final_manip];
    save(parameters.experiment_name)
end

function T = build_T_4dof(p, phi)
T = [cos(phi) -sin(phi) 0 p(1);
     sin(phi) cos(phi) 0 p(2);
     0            0     1  p(3);
     0             0    0   1];

 function T = build_T_sawyer(p, phi)
T = [1  -sin(phi) 0 p(1);
     0  cos(phi) 0 p(2);
     0            0     1  p(3);
     0             0    0   1];

repo: ARTE


text:
function Script_CLNF_cross_data_general()

addpath(genpath('../'));

% Replace this with the location of the Menpo dataset
[images, detections, labels] = Collect_menpo_imgs('G:\Datasets\menpo/');

%% loading the patch experts

[ patches, pdm, clmParams ] = Load_CLNF_general();
views = [0,0,0; 0,-30,0; 0,30,0; 0,-55,0; 0,55,0; 0,0,30; 0,0,-30; 0,-90,0; 0,90,0; 0,-70,40; 0,70,-40];
views = views * pi/180;

[ patches_51, pdm_51, clmParams_51, inds_full, inds_inner ] = Load_CLNF_inner();

shapes_all = zeros(size(labels,2),size(labels,3), size(labels,1));
labels_all = zeros(size(labels,2),size(labels,3), size(labels,1));
lhoods = zeros(numel(images),1);

% for recording purposes
experiment.params = clmParams;

num_points = numel(pdm.M)/3;

shapes_all = cell(numel(images), 1);
labels_all = cell(numel(images), 1);
lhoods = zeros(numel(images),1);
all_lmark_lhoods = zeros(num_points, numel(images));
all_views_used = zeros(numel(images),1);

verbose = false; % set to true to visualise the fitting

tic
for i=1:numel(images)

    image = imread(images(i).img);
    image_orig = image;

    if(size(image,3) == 3)
        image = rgb2gray(image);
    end

    bbox = detections(i,:);

    [shape,~,~,lhood,lmark_lhood,view_used] = Fitting_from_bb_multi_hyp(image, [], bbox, pdm, patches, clmParams, views);

    % Perform inner landmark fitting now
    [shape, shape_inner] = Fitting_from_bb_hierarch(image, pdm, pdm_51, patches_51, clmParams_51, shape, inds_full, inds_inner);

    all_lmark_lhoods(:,i) = lmark_lhood;
    all_views_used(i) = view_used;

    shapes_all{i} = shape;
    labels_all{i} = labels{i};

    if(mod(i, 200)==0)
        fprintf('%d done\n', i );
    end

    lhoods(i) = lhood;

    if(verbose)
        v_points = logical(patches(1).visibilities(view_used,:))';
        DrawFaceOnFig(image_orig, shape, bbox, v_points);
    end

end
toc

experiment.lhoods = lhoods;
experiment.shapes = shapes_all;
experiment.labels = labels_all;
experiment.all_lmark_lhoods = all_lmark_lhoods;
experiment.all_views_used = all_views_used;

%%
output_results = 'results/results_clnf_cross-data_general.mat';
save(output_results, 'experiment');

end

author: TadasBaltrusaitis

repo: OpenFace


text:
%% Demo: fMRI searchlights with split-half correlations, classifier, and representational similarity analysis
%
% The data used here is available from http://cosmomvpa.org/datadb.zip
%
% This example uses the following dataset:
% - 'ak6' is based on the following work (please cite if you use it):
%    Connolly et al (2012), Representation of biological classes in the
%    human brain. Journal of Neuroscience,
%    doi 10.1523/JNEUROSCI.5547-11.2012
%
%    Six categories (monkey, lemur, mallard, warbler, ladybug, lunamoth)
%    during ten runs in an fMRI study. Using the General Linear Model
%    response were estimated for each category in each run, resulting
%    in 6*10=60 t-values.
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #

%% Set data paths
% The function cosmo_config() returns a struct containing paths to tutorial
% data. (Alternatively the paths can be set manually without using
% cosmo_config.)
config=cosmo_config();

ak6_study_path=fullfile(config.tutorial_data_path,'ak6');

% show readme information
readme_fn=fullfile(ak6_study_path,'README');
cosmo_type(readme_fn);

% reset citation list
cosmo_check_external('-tic');

% set result directory
output_path=config.output_data_path;

%% Example: split-half correlation measure (Haxby 2001-style)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% This example uses the 'ak6' dataset

% define data filenames & load data from even and odd runs

data_path=fullfile(ak6_study_path,'s01'); % data from subject s01
mask_fn=fullfile(data_path, 'brain_mask.nii'); % whole brain mask

data_odd_fn=fullfile(data_path,'glm_T_stats_odd.nii');
ds_odd=cosmo_fmri_dataset(data_odd_fn,'mask',mask_fn,...
                            'targets',1:6,'chunks',1);

data_even_fn=fullfile(data_path,'glm_T_stats_even.nii');
ds_even=cosmo_fmri_dataset(data_even_fn,'mask',mask_fn,...
                            'targets',1:6,'chunks',2);

% Combine even and odd runs
ds_odd_even=cosmo_stack({ds_odd, ds_even});

% print dataset
fprintf('Dataset input:\n');
cosmo_disp(ds_odd_even);

% Use cosmo_correlation_measure.
% This measure returns, by default, a split-half correlation measure
% based on the difference of mean correlations for matching and
% non-matching conditions (a la Haxby 2001).
measure=@cosmo_correlation_measure;

% define spherical neighborhood with radius of 3 voxels
radius=3; % voxels
nbrhood=cosmo_spherical_neighborhood(ds_odd_even,'radius',radius);

% Run the searchlight with a 3 voxel radius
corr_results=cosmo_searchlight(ds_odd_even,nbrhood,measure);

% print output
fprintf('Dataset output:\n');
cosmo_disp(corr_results);

% Plot the output
cosmo_plot_slices(corr_results);

% Define output location
output_fn=fullfile(output_path,'corr_searchlight.nii');

% Store results to disc
cosmo_map2fmri(corr_results, output_fn);

% Show citation information
cosmo_check_external('-cite');

author: CoSMoMVPA

repo: CoSMoMVPA

save_path: github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA


text:
function toms446_test04 ( )

%*****************************************************************************80
%
%% TOMS446_TEST04 tests EDCHEB, which evaluates the derivative of a Chebyshev series.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 September 2011
%
%  Author:
%
%    John Burkardt
%
  nf = 5;
  npl = 10;

  nx = 6;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TOMS446_TEST04\n' );
  fprintf ( 1, '  Test EDCHEB, which evaluates the \n' );
  fprintf ( 1, '  derivative of a Chebyshev series.\n' );

  x = cheby ( nf, npl, @functn );

  for j = 1 : nf

    x2(1:npl) = x(1:npl,j);

    fprintf ( 1, '\n' );
    if ( j == 1 )
      fprintf ( 1, '  d/dx Sin(x)\n' );
    elseif ( j == 2 )
      fprintf ( 1, '  d/dx Cos(x)\n' );
    elseif ( j == 3 )
      fprintf ( 1, '  d/dx Sin(2x)\n' );
    elseif ( j == 4 )
      fprintf ( 1, '  d/dx Cos(2x)\n' );
    elseif ( j == 5 )
      fprintf ( 1, '  d/dx x^5\n' );
    end

    fprintf ( 1, '\n' );

    for k = 1 : nx

      xval = 2.0 * ( k - 1 ) / ( nx - 1 ) - 1.0;

      fxj = functn_d ( xval );

      fval = edcheb ( xval, x2, npl );

      fprintf ( 1, '  %10.4f  %10.4f  %10.4f\n', xval, fxj(j), fval );

    end

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [varargout]=febioOutputView(pathName,febio_spec)

% function [hf]=febioOutputView(pathName,febio_spec)
% ------------------------------------------------------------------------
%
%
%
% ------------------------------------------------------------------------

%%
% optionStruct=[];

%%
fontSize=15;

%%
hf=cFigure; %Open figure

%%

V=febio_spec.Geometry.Nodes{1}.node.VAL;
E_cell=febio_spec.Geometry.Elements;

%%

nodeDataCellAll=febio_spec.Output.logfile.node_data;

nodalDisplacementAll=zeros(size(V));
for q=1:1:numel(nodeDataCellAll)
    dataTypeString=nodeDataCellAll{q}.ATTR.data;
    if strcmp(dataTypeString,'ux;uy;uz')
        [~,nodalDisplacementAll,~]=importFEBio_logfile(fullfile(pathName,nodeDataCellAll{q}.ATTR.file)); %Import data

        nodalDisplacementAll=nodalDisplacementAll(:,2:end,:);
        sizImport=size(nodalDisplacementAll);
        sizImport(3)=sizImport(3)+1;
        dataArray_n=zeros(sizImport);
        dataArray_n(:,:,2:end)=nodalDisplacementAll;
        nodalDisplacementAll=dataArray_n;
        U_end=nodalDisplacementAll(:,:,end);
        U_mag=sqrt(sum(U_end(:,3).^2,2));
        V_def=V+U_end;
    end
end
nodalDisplacementMagnitudeAll=sqrt(sum(nodalDisplacementAll.^2,2));

hf.UserData.febioOutputView.colorData=[];
hf.UserData.febioOutputView.pathName=pathName;
hf.UserData.febioOutputView.febio_spec=febio_spec;

%%
% Create basic view and store graphics handle to initiate animation

hf.UserData.febioOutputView.ht=gtitle(' - '); %Figure axis title

handleSet=gobjects(1,numel(E_cell));
for q=1:1:numel(E_cell)

    elementsNow=febio_spec.Geometry.Elements{q}.elem.VAL;
    elementTypeNow=febio_spec.Geometry.Elements{1}.ATTR.type;

    if any(strcmp(elementTypeNow,{'tri3','tri6','tri7','quad4','quad8'})) %Surface elements
        facesNow=elementsNow;
    else %Solid elements
        facesNow=element2patch(elementsNow);
    end

    handleSet(q)=gpatch(facesNow,V,U_mag,'k',1); %Add graphics object to animate
    handleSet(q).FaceColor='interp';
end

axisGeom(gca,fontSize);
colormap(gjet(250)); colorbar;
cLim=[min(nodalDisplacementMagnitudeAll(:)) max(nodalDisplacementMagnitudeAll(:))];
if abs(cLim(2)-cLim(1))<eps(1)
    cLim(1)=cLim(1)-1;
    cLim(2)=cLim(2)+1;
end
hf.UserData.febioOutputView.cLim=cLim;
caxis(cLim);
VV=[V;V_def];
axis([min(VV(:,1)) max(VV(:,1)) min(VV(:,2)) max(VV(:,2)) min(VV(:,3)) max(VV(:,3))]); %Set axis limits statically
camlight headlight;

hf.UserData.febioOutputView.handleSet=handleSet;

%%

outputDataCellAll=febio_spec.Output.logfile.node_data;
if isfield(febio_spec.Output.logfile,'element_data')
    outputDataCellAll=[outputDataCellAll febio_spec.Output.logfile.element_data];
end

popUpString=cell(1,1);
%Initialize with displacement magnitude
popUpString{1}='um';
hf.UserData.febioOutputView.data.um=nodalDisplacementMagnitudeAll;

for q=1:1:numel(outputDataCellAll)

    dataTypeString=outputDataCellAll{q}.ATTR.data;
    dataTypeSet=strsplit(dataTypeString,';');

    [timeVec,dataArray,~]=importFEBio_logfile(fullfile(pathName,outputDataCellAll{q}.ATTR.file)); %Import data
    dataArray=dataArray(:,2:end,:);
    sizImport=size(dataArray);
    sizImport(3)=sizImport(3)+1;
    dataArray_n=zeros(sizImport);
    dataArray_n(:,:,2:end)=dataArray;
    dataArray=dataArray_n;

    for qSet=1:1:numel(dataTypeSet)
        dataTypeStringNow=dataTypeSet{qSet};
        popUpString{end+1}=dataTypeStringNow;
        dataNow=dataArray(:,qSet,:);
        switch dataTypeStringNow
            case 'J' %Volume ratio
                dataNow(:,:,1)=1; %set initial to ones
        end
        hf.UserData.febioOutputView.data.(dataTypeStringNow)=dataNow;
    end

end

timeVec=[0; timeVec(:)]; %Time

%%

backGroundColor=hf.Color;
if strcmp(backGroundColor,'k')
    textColor='w';
elseif size(backGroundColor,2)==3
    grayLevels=linspace(0,1,100);
    [~,indMax]=max(abs(grayLevels-mean(double(backGroundColor))));
    textColor=grayLevels(indMax)*ones(1,3);
else
    textColor='k';
end

hPop = uicontrol(hf,'Style','popupmenu','String',popUpString,...
    'BackgroundColor',backGroundColor,'FontSize',fontSize,'FontWeight','normal','Units','Points','ForegroundColor',textColor,...
    'Callback',@(a,b)setColorData(a,b,{hf}));

hFunc=get(hf,'ResizeFcn');

if iscell(hFunc)
    warning('gtitle replaced the ResizeFcn function. Specify your ResizeFcn in the form @(h,e)figResize(h,e,c) to avoid this behavior');
    set(hf,'ResizeFcn',@(a,b)figResize(a,b,{hf,hPop}));
else
    if isempty(hFunc)
        set(hf,'ResizeFcn',@(a,b)figResize(a,b,{hf,hPop}));
    else
        set(hf,'ResizeFcn',@(a,b)(cellfun(@(x)feval(x,a,b),{hFunc,@(a,b)figResize(a,b,{hf,hPop})})));
    end
end

figResize([],[],{hf,hPop});

%%

clear animStruct;

% Set up animation features
animStruct.Time=timeVec; %The time vector
propertySetVert=repmat({'Vertices'},1,numel(handleSet));
propertySetCData=repmat({'CData'},1,numel(handleSet));

for qt=1:1:size(nodalDisplacementAll,3) %Loop over time increments
    U_now=nodalDisplacementAll(:,:,qt); %Current displacement
    V_def=V+U_now; %Current nodal coordinates
    d1=repmat({V_def},1,numel(handleSet));

    %Initialize animation structure with nodal coordinate and displacement animation
    animStruct.Handles{qt}=[handleSet]; %Handles of objects to animate
    animStruct.Props{qt}={propertySetVert{:}}; %Properties of objects to animate
    animStruct.Set{qt}={d1{:}}; %Property values for to set in order to animate

    %Add colordata animations for faces
    colorData=nodalDisplacementMagnitudeAll(:,:,qt);

    d2={};
    for qs=1:1:numel(handleSet)
        colorDataNow=colorData;
%         if size(colorData,1)==size(V,1)
%             f=handleSet(qs).Faces;
%             [colorDataNow]=vertexToFaceMeasure(f,colorData);
%         end
        f=handleSet(qs).Faces;
        if size(colorData,1)==size(f,1)
            [colorDataNow]=faceToVertexMeasure(f,V,colorData);
        end
        d2{qs}=colorDataNow;
    end
    animStruct.Handles{qt}(1:2*numel(handleSet))=[handleSet handleSet]; %Handles of objects to animate
    animStruct.Props{qt}(end+1:end+numel(propertySetCData))={propertySetCData{:}}; %Properties of objects to animate
    animStruct.Set{qt}(end+1:end+numel(propertySetCData))={d2{:}}; %Property values for to set in order to animate
end

anim8(hf,animStruct); %Initiate animation feature
drawnow;

%%

if nargout>0
    varargout{1}=hf;
end

end

%%

function figResize(~,~,inputCell)

hf=inputCell{1};
hPop=inputCell{2};
unitsNow=hf.Units;
hf.Units='Points';

figPosition=hf.Position;
textBoxWidth=round(figPosition(3)/6);
textBoxHeight=hPop.Extent(4).*ceil(hPop.Extent(3)./figPosition(3));
textPosition=[0 figPosition(4)-textBoxHeight textBoxWidth textBoxHeight];
hPop.Position = textPosition;

hf.Units=unitsNow;

end

%%

function setColorData(source,~,inputCell)
hf=inputCell{1};
indexValue = source.Value;
stringSet = source.String;

dataTypeStringNow = stringSet{indexValue};
hf.UserData.febioOutputView.ht.String=dataTypeStringNow;

hf.UserData.febioOutputView.colorData=hf.UserData.febioOutputView.data.(dataTypeStringNow);

updateFaceColor(hf);

caxis(hf.UserData.febioOutputView.cLim);
drawnow;

end

%%

function updateFaceColor(hf)

for qt=1:1:numel(hf.UserData.anim8.animStruct.Time)
    cLim=[];
    for qh=numel(hf.UserData.febioOutputView.handleSet)+1:1:2*numel(hf.UserData.febioOutputView.handleSet)
        c=hf.UserData.febioOutputView.colorData(:,:,qt);
        d2=repmat({c},1,numel(hf.UserData.febioOutputView.handleSet));
        hf.UserData.anim8.animStruct.Set{qt}{qh}=d2{:}; %Property values for to set in order to animate

        if isempty(cLim)
            cLim=[min(c(:)) max(c(:))];
        else
            cLim(1)=min(min(c(:)),cLim(1));
            cLim(2)=max(max(c(:)),cLim(2));
        end
    end
end

if abs(cLim(2)-cLim(1))<eps(1)
    cLim(1)=cLim(1)-1;
    cLim(2)=cLim(2)+1;
end
hf.UserData.febioOutputView.cLim=cLim;

%Briefly toggle slider to trigger anim8 redraw event
jSlider=hf.UserData.anim8.sliderHandles{1};
v=get(jSlider,'Value');
if v>1
    set(jSlider,'Value',v-1);
    set(jSlider,'Value',v);
else
    set(jSlider,'Value',v+1);
    set(jSlider,'Value',v);
end

end

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

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
%% Niblack Image Thresholding
% Sample to compare Niblack thresholding against other algorithms
% (global thresholding and adaptive thresholding) for an image with varying
% illumination.
%
% Sources:
%
% * <https://github.com/opencv/opencv_contrib/blob/3.2.0/modules/ximgproc/samples/niblack_thresholding.cpp>
% * <https://docs.opencv.org/3.2.0/d7/d4d/tutorial_py_thresholding.html>
%

function niblack_thresholding_demo()
    % Input 8-bit grayscale image + Parameters
    % - BS: block size (local neighborhood) [niblack, adaptive]
    % - K : constant multiplied by std dev next subtracted from mean [niblack]
    % - C : constant subtracted from mean [adaptive]
    if ~mexopencv.isOctave() && mexopencv.require('images')
        % image with dark pixels being foreground
        im = which('printedtext.png');
        K = -0.7;
        C = 7;
    elseif true
        % image with dark pixels being foreground
        im = fullfile(mexopencv.root(),'test','sudoku.jpg');
        K = -0.7;
        C = 7;
    elseif ~mexopencv.isOctave() && mexopencv.require('images')
        % image with white pixels being foreground
        im = which('rice.png');
        K = 0.7;
        C = -17;
    end
    assert(~isempty(im) && exist(im, 'file') == 2);
    img = cv.imread(im, 'Grayscale',true);
    BS = min(floor(size(img)/16) * 2 + 1);
    assert(~isempty(img), 'Failed to load image');

    % Preprocess image
    if true
        % no processing
        src = img;
    elseif false
        src = cv.medianBlur(img, 'KSize',3);
    elseif true
        % really effective for global thresholding [otsu]
        src = localNormalization(img, 11, 33);
    else
        % rice image, estimate and subtract non-uniform illumination background
        % (see NonuniformIlluminationExample.mlx example)
        if mexopencv.require('images')
            src = imtophat(img, strel('disk',15));
            src = imadjust(src);
        else
            el = cv.getStructuringElement('Shape','Ellipse', 'KSize',[15 15]*2-1);
            src = cv.morphologyEx(img, 'Tophat', 'Element',el);
            obj = cv.SimpleWB();
            src = obj.balanceWhite(src);
        end
    end

    % Threshold
    opts = {'Type','Binary', 'MaxValue',255};
    bw1 = cv.threshold(src, 'Otsu', opts{:});
    bw2 = cv.adaptiveThreshold(src, 'Method','Mean', ...
        'C',C, 'BlockSize',BS, opts{:});
    bw3 = cv.adaptiveThreshold(src, 'Method','Gaussian', ...
        'C',C, 'BlockSize',BS, opts{:});
    bw4 = cv.niBlackThreshold(src, K, 'Method','Niblack', ...
        'BlockSize',BS, opts{:});
    bw5 = cv.niBlackThreshold(src, -K, 'Method','Sauvola', ...
        'BlockSize',BS, opts{:});
    bw6 = cv.niBlackThreshold(src, -K, 'Method','Wolf', ...
        'BlockSize',BS, opts{:});
    bw7 = cv.niBlackThreshold(src, K, 'Method','Nick', ...
        'BlockSize',BS, opts{:});
    %bw8 = my_niblack(src, K, BS);

    % Results
    subplot(331), imshow(img), title('Source')
    subplot(332), imshow(src), title('Processed')
    subplot(333), imshow(bw1), title('Otsu')
    subplot(334), imshow(bw2), title('Adaptive Mean')
    subplot(335), imshow(bw3), title('Adaptive Gaussian')
    subplot(336), imshow(bw4), title('Niblack')
    subplot(337), imshow(bw5), title('Sauvola')
    subplot(338), imshow(bw6), title('Wolf')
    subplot(339), imshow(bw7), title('Nick')
end

%% Helper function

function out = localNormalization(img, s1, s2)
    %LOCALNORMALIZATION  local normalization to get uniform local mean and variance
    %
    %     out = localNormalization(img)
    %     out = localNormalization(img, s1, s2)
    %
    % The local normalization tends to uniformize the mean and variance of an
    % image around a local neighborhood. This is especially useful for correct
    % non-uniform illumination or shading artifacts.
    %
    % ## Input
    % * __img__ 8-bit input image
    %
    % ## Output
    % * __out__ output image of same size and type.
    %
    % ## Options
    % * __s1__ sigma to estimate the local mean. default 5
    % * __s2__ sigma to estimate the local variance. Often `s2` should be
    %   larger than `s1`. default 15
    %
    % ## References
    % > http://bigwww.epfl.ch/sage/soft/localnormalization/
    %

    % check arguments
    if nargin < 2, s1 = 5; end
    if nargin < 3, s2 = 15; end
    validateattributes(img, {'uint8'}, {});

    % convert to grayscale
    if size(img,3) == 3
        gray = cv.cvtColor(img, 'RGB2GRAY');
    else
        gray = img;
    end

    % convert to floating-point image
    gray = cv.convertTo(gray, 'RType','single', 'Alpha',1.0/255.0);

    % numerator = img - gauss_blur(img)
    blur = cv.GaussianBlur(gray, 'KSize',[0 0], 'SigmaX',s1, 'SigmaY',s1);
    num = gray - blur;

    % denominator = sqrt(gauss_blur(img^2))
    den = sqrt(cv.GaussianBlur(num.^2, 'KSize',[0 0], 'SigmaX',s2, 'SigmaY',s2));

    % output = numerator / denominator
    out = num ./ den;

    % normalize output into [0,1]
    out = cv.normalize(out, 'Alpha',0.0, 'Beta',1.0, 'NormType','MinMax');

    % convert to 8-bit
    out = cv.convertTo(out, 'RType','uint8', 'Alpha',255.0);
end

function bw = my_niblack(img, K, BS)
    %MY_NIBLACK  Manual implementation of Niblack thresholding

    img = im2double(img);
    mu = imboxfilt(img, [BS BS]);
    sd = sqrt(imboxfilt(img.^2, [BS BS]) - mu.^2);
    bw = img > (mu + K*sd);
end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
function assertTrue(a, message)
% assert that the input is equal to true
%
% assertTrue(a[,msg])
%
% Inputs:
%   a               vector scalar logical that must be true
%   msg             optional custom message
%
% Throws:
%   'MOxUnit:notLogicalScalar'      a is not a logical scalar
%   'MOxUnit:notTrue'               a is not true
%
% Examples:
%   assertTrue(true);
%   %||  % ok
%
%   assertTrue(false);
%
%   %|| error('input does not evaluate to true');
%
%   assertFalse([true,true]);
%   %|| error('input is not a logical scalar');
%
% Notes:
%   - If a custom message is provided, then any error message is prefixed
%     by this custom message
%   - This function attempts to show similar behaviour as in
%     Steve Eddins' MATLAB xUnit Test Framework (2009-2012)
%     URL: http://www.mathworks.com/matlabcentral/fileexchange/
%                           22846-matlab-xunit-test-framework
%
% NNO Jan 2014

    if ~isscalar(a) || ~islogical(a)
        whatswrong='input is not a logical scalar';
        error_id='assertTrue:invalidCondition';
    elseif ~a
        whatswrong='input does not evaluate to true';
        error_id='assertTrue:falseCondition';
    else
        return
    end

    if isempty(error_id)
        return;
    end

    if nargin<2
        message='';
    end

    full_message=moxunit_util_input2str(message,whatswrong,a);

    if moxunit_util_platform_is_octave()
        error(error_id,'%s',full_message);
    else
        throwAsCaller(MException(error_id,'%s',full_message));
    end

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text:
function [view,OK] = editROIFields(view,n)
% Edit the fields in a region of interest
%
%  [view,OK] = editROIFields(view,n)
%
% You can set the name and color of an ROI
% ARW 040104 : Added uisetcolor option, ability to use [R G B] color format
% RAS, DR, 2007: several new options, including size report and
% save options.
% ras, 01/24/07: records date created, last modified.
% ras, 10/08/07: for the 'save ROI' checkbox, the code now determines
% whether to default to checked or unchecked based on whether the ROI
% is already saved, as well as its name. E.g., if the file has already
% been saved, or it's named 'ROI1', it leaves it unchecked by default.
colorList = {'yellow','magenta','cyan','red','green','blue','white','kblack','user'};

colorChar = char(colorList)';
colorChar = colorChar(1,:);

if ~exist('n','var'), n = view.selectedROI; end
if n==0
    myErrorDlg('Sorry,  you need to load an ROI first.')
end

ROI = view.ROIs(n);
if (ischar(ROI.color))

    colorNum = findstr(ROI.color,colorChar);
    switch lower(ROI.color)
        case 'yellow',  colorRGB=[1 1 0];
        case 'magenta', colorRGB=[1 0 1];
        case 'cyan',    colorRGB=[0 1 1];
        case 'red',     colorRGB=[1 0 0];
        case 'green',   colorRGB=[0 1 0];
        case 'blue',    colorRGB=[0 0 1];
        case 'white',   colorRGB=[1 1 1];
        case 'k',       colorRGB=[0 0 0];
        otherwise
            colorRGB=[0 0 0];
    end
else
    colorNum=8; colorRGB=ROI.color;
end

if ~isfield(ROI, 'created'), ROI.created = datestr(now); end
if ~isfield(ROI, 'modified'), ROI.modified = datestr(now); end
if ~isfield(ROI, 'comments'), ROI.comments = ''; end

dlg(1).string = 'ROI name:';
dlg(1).fieldName = 'name';
dlg(1).style = 'edit';
dlg(1).value = ROI.name;

dlg(2).string = 'Color:';
dlg(2).fieldName = 'color';
dlg(2).list = colorList;
dlg(2).choice = colorNum;
dlg(2).style = 'popupmenu';
if ischar(ROI.color), dlg(2).value = colorList{colorNum};
else                  dlg(2).value = 'user';
end

dlg(end+1).string = 'Comments on ROI:';
dlg(end).fieldName = 'comments';
dlg(end).style = 'edit3';
dlg(end).value = ROI.comments;

dlg(end+1).string = 'Date Created:';
dlg(end).fieldName = 'created';
dlg(end).style = 'text';
dlg(end).value = ROI.created;

dlg(end+1).string = 'Last Modified:';
dlg(end).fieldName = 'modified';
dlg(end).style = 'text';
dlg(end).value = datestr(now);

% ras 01/07: let's also report the ROI size where it's not too hard
if ismember(view.viewType, {'Inplane' 'Volume' 'Gray'})
    dlg(end+1).string = 'ROI Size';
    dlg(end).fieldName = 'roiSize';
    dlg(end).style = 'text';
    nVoxels = size(ROI.coords, 2);
    roiVolume = nVoxels .* prod(viewGet(view, 'voxelSize'))';
    if isequal(view.viewType, 'Inplane')
        % get anatomical and functional sizes
		if nVoxels > 0
			funcVoxels=roiSubCoords(view, ROI.coords);
			nFuncVoxels = size(funcVoxels,2);
			str = strvcat([num2str(nVoxels) ' anatomical voxels'], ...
				[num2str(nFuncVoxels) ' functional voxels'], ...
				sprintf('%3.1fmm^3', roiVolume));
		else
			str = 'No voxels';
		end
        dlg(end).value = str;
    else
        % functionals are resampled to match anat, only one size
        dlg(end).value = sprintf('%i voxels, %3.1fmm^3', nVoxels, roiVolume);
    end
end

if isequal(view.viewType, 'Inplane') & nVoxels > 0
    % another nicety: report which slices the ROI may be found in
    dlg(end+1).string = 'Slices containing ROI';
    dlg(end).fieldName = 'roiSlices';
    dlg(end).style = 'text';
    dlg(end).value = num2str( unique(ROI.coords(3,:)) );
end

%% add checkbox to save the modified ROI:
% default to checked if the ROI has not been saved, unchecked if it has
roiIsSaved = check4File( fullfile(roiDir(view), ROI.name) );
tempRoi = strncmp(ROI.name, 'ROI', 3); % ROI1, ROI2, etc... don't want to save
saveFlag = ( ~roiIsSaved & ~tempRoi );

dlg(end+1).string = 'Save this ROI when done';
dlg(end).fieldName = 'save';
dlg(end).style = 'checkbox';
dlg(end).value = saveFlag;

if ismember(view.viewType, {'Volume' 'Gray'})
    dlg(end+1).string = 'If saving, save in local / shared directory?';
    dlg(end).fieldName = 'local';
    dlg(end).style = 'popup';
    dlg(end).list = {'local' 'shared'};
    dlg(end).value = 2;
end

resp = generalDialog(dlg,'Edit ROI Fields');

% If user selects 'OK', change the parameters.  Otherwise the
% user isn't happy with these settings so bail out.
if ~isempty(resp)
    ROI = mergeStructures(ROI, resp);
    if (strcmp(ROI.color,'user'))
        ROI.color = uisetcolor(colorRGB);
    else
        ROI.color = ROI.color(1);
    end

    % enforce proper ROI fields
    ROI = rmfield(ROI, 'save');
    ROI = roiCheck(ROI);

    if ismember(view.viewType, {'Volume' 'Gray'})   % get local flag from resp
        local = isequal(resp.local, 'local');
    else
        local = 1; % Inplane/Flat: always save locally
    end

    if resp.save==1
        saveROI(view, ROI, local);
    end

    for f = fieldnames(ROI)'
        view.ROIs(n).(f{1}) = ROI.(f{1});
    end

    OK = 1;
else
    OK = 0;
end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function [pos,vel,acc]=parabolicblend(t,tb,omega,thetai,thetaf)

toffset=t(1);
t=t-toffset;

tbefore=find(t<tb);
tparbegin=t(1:tbefore(end));

%%the parabolic starting blend
pos=thetai+(omega/(2*tb)).*tparbegin.^2;
vel=omega/tb.*tparbegin;
acc=omega/tb;
tparend=t(length(t)-tbefore(end)+1:end);
tlinear=t(tbefore(end)+1:end-length(tparend));
%%the linear zone
pos=[pos, pos(end)+omega/tb.*tlinear ];

%%the parabolic ending blend
k=omega/(2*tb);

pos=[pos, thetaf-k.*(t(end)-tparend).^2];
end

author: Sable

repo: mcbench-benchmarks


text:
function expmDimAdjust = getExpmDimAdjust(disc)
%GETEXPMDIMADJUST    Adjust dimension of discretization for LINOP/EXPM.

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

expmDimAdjust = max(getDiffOrder(disc.source), 0);
expmDimAdjust = max(expmDimAdjust, [], 1);

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function options = prunecplexoptions(options)

try
    if strfind(version,'2016')
        o1 = cplexoptimset;
    else
        o1 = cplexoptimset('cplex');
    end
    o2 = options.cplex;
    n = fieldnames(o1);
    for i = 1:length(n)
        if isequal(o1.(n{i}),o2.(n{i}))
            options.cplex = rmfield(options.cplex,n{i});
        end
    end
catch
end

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
%% 参数设置
%% 基带数据数据产生
%% 信道编码（卷积码、或交织器）
%% qpsk调制
%% 扩频
%% 插入导频
%% 串并转换
%% IFFT
%% 插入保护间隔、循环前缀
%% 并串转换
%% DA
%% 上变频
%% 信道（通过多经瑞利信道、或信号经过AWGN信道）
%% 下变频
%% AD
%% 串并转换
%% 去掉保护间隔、循环前缀
%% FFT
%% 信道估计与插值（均衡）
%% 信道校正
%% 并串转换
%% 解扩
%% QPSK解调
%% （解交织）
%% 信道译码（维特比译码）
%% 计算误码率

repo: OFDM


text:
function SR = getInitialSRImage(W, LRImages, photoParams)
% GETINITIALSRIMAGE Initial guess for super-resolved image
%   GETINITIALSRIMAGE computes a rough estimate for the super-resolved
%   image from given model parameters.
%
%   X = GETINITIALSRIMAGE(W, Y, PHOTOPARAMS) computes the "average image" X
%   as initial guess based on the system matrix W, the low-resolution data
%   Y and the photometric parameters PHOTOPARAMS.
%
%   See David P. Capel, Image Mosaicing and Super-resolution, PhD thesis,
%   2001 for details.

    if nargin > 2 && ~isempty(photoParams)
        numFrames = length(photoParams.mult);
        numLRPixel = length(LRImages) / numFrames;

        % Compose photometric parameters into additive and multiplicative term.
        bm = zeros(size(LRImages));
        ba = zeros(size(LRImages));
        for k = 1:numFrames
            bm( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(photoParams.mult(k), numLRPixel, 1);
            ba( ((k-1)*numLRPixel + 1):(k*numLRPixel) ) = repmat(photoParams.add(k), numLRPixel, 1);
        end
        bm_invmat = spdiags(1./bm(:), 0, length(bm), length(bm));

        % Compute "average image" from low-resolution observtions, system
        % matrix and phtometric parameters.
        SR =  (W' * bm_invmat * (LRImages - ba .* ones(size(LRImages)))) ./ (sum(W, 1)' + 1e-4);
    else
        % Compute "average image" without photometric parameters
        SR = (W' * LRImages) ./ (sum(W, 1)' + 1e-4);
    end

author: thomas-koehler

repo: SupER


text:
classdef core
% General utility functions
methods(Static)

end

end

author: indigits

repo: sparse-plex


text:
function draw_API = defaultCircle(h_group)
%
%       DRAW_API.setColor
%       DRAW_API.updateView
%       DRAW_API.getBoundingBox
%

  % initialize variables needing function scope
  bounding_box = [];
  %h_axes = iptancestor(h_group,'axes');

  % The line objects should have a width of one screen pixel.
  line_width = ceil(getPointsPerScreenPixel);
  h_circle  = rectangle(...
                        'Curvature', [1,1],...
                        'LineWidth', line_width,...
                        'faceColor', 'none',...
                        'Hittest', 'off',...
                        'Parent', h_group);
  h_patch   = patch('FaceColor', 'none', 'EdgeColor', 'none', ...
                    'HitTest', 'off', ...
                    'Parent', h_group);

  draw_API.setColor         = @setColor;
  draw_API.updateView       = @updateView;
  draw_API.getBoundingBox   = @getBoundingBox;

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  function pos = getBoundingBox
    pos = bounding_box;
  end
  %--------------------------------------------------------------------------

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  function updateView(cen, r)

    if ~ishandle(h_group)
        return;
    end

    new_pos = [cen(1) - r, cen(2) - r, r+r, r+r];
    if ( ~isequal(new_pos, get(h_circle, 'Position')) )
      set(h_circle, 'Position', new_pos);
      xx = [...
        new_pos(1),...
        new_pos(1),new_pos(1)+new_pos(3),new_pos(1)+new_pos(3),...
        new_pos(1)];
      yy = [...
        new_pos(2),...
        new_pos(2)+new_pos(4),new_pos(2)+new_pos(4),new_pos(2),...
        new_pos(2)];
      set(h_patch, 'XData', xx, 'YData', yy);
    end

    bounding_box = new_pos;

  end
  %--------------------------------------------------------------------------

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  function setColor(c)
    if ishandle(h_circle)
      set(h_circle, 'EdgeColor', c);
    end

  end
  %--------------------------------------------------------------------------

end

% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function setXYDataIfChanged(h, x, y)
% % Set XData and YData of HG object h to x and y if they are different.  h
% % must be a valid HG handle to an object having XData and YData properties.
% % No validation is performed.
%
%   if ~isequal(get(h, 'XData'), x) || ~isequal(get(h, 'YData'), y)
%     set(h, 'XData', x, 'YData', y);
%   end
% end
% %--------------------------------------------------------------------------


text:
classdef MOEAPSL < ALGORITHM
% <multi> <real/integer/binary> <large/none> <constrained/none> <sparse>
% Multi-objective evolutionary algorithm based on Pareto optimal subspace
% learning

%------------------------------- Reference --------------------------------
% Y. Tian, C. Lu, X. Zhang, K. C. Tan, and Y. Jin, Solving large-scale
% multi-objective optimization problems with sparse optimal solutions via
% unsupervised neural networks, IEEE Transactions on Cybernetics, 2021,
% 51(6): 3115-3128.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Population initialization
            P   = UniformPoint(Problem.N,Problem.D,'Latin');
            Dec = P.*repmat(Problem.upper-Problem.lower,Problem.N,1) + repmat(Problem.lower,Problem.N,1);
            Dec(:,Problem.encoding==4) = 1;
            Mask = UniformPoint(Problem.N,Problem.D,'Latin') > 0.5;
            Population = Problem.Evaluation(Dec.*Mask);
            [Population,Dec,Mask,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Dec,Mask,Problem.N,0,0);

            %% Optimization
            rho = 0.5;
            while Algorithm.NotTerminated(Population)
                Site = rho > rand(1,ceil(Problem.N/2));
                if any(Site)
                    [rbm,dae,allZero,allOne] = ModelTraining(Mask,Dec,any(Problem.encoding~=4));
                else
                    [rbm,dae,allZero,allOne] = deal([]);
                end
                MatingPool = TournamentSelection(2,ceil(Problem.N/2)*2,FrontNo,-CrowdDis);
                [OffDec,OffMask] = Operator(Problem,Dec(MatingPool,:),Mask(MatingPool,:),rbm,dae,Site,allZero,allOne);
                Offspring = Problem.Evaluation(OffDec.*OffMask);
                [Population,Dec,Mask,FrontNo,CrowdDis,sRatio] = EnvironmentalSelection([Population,Offspring],[Dec;OffDec],[Mask;OffMask],Problem.N,length(Population),2*sum(Site));
                rho = (rho+sRatio)/2;
            end
        end
    end
end

author: BIMK

repo: PlatEMO

save_path: github-repos/MATLAB/BIMK-PlatEMO


text:
function [l] = yd32l(yd3)
% Convert volume from cubic yards to liters.
% Chad Greene 2012
l = yd3*764.55485798;


text:
function plot_3d_2( data1, data2, theta )

    data1 = rotate(data1, theta);
    x1 = data1(:, 1);
    y1 = data1(:, 2);
    z1 = data1(:, 3);

    data2 = rotate(data2, theta);
    x2 = data2(:, 1);
    y2 = data2(:, 2);
    z2 = data2(:, 3);

    figure();
    scatter3(x1, y1, z1, 'b');
    hold on;
    scatter3(x2, y2, z2, 'r');
    hold off;

end

author: XgTu


text:
function [cimages, cnames] = APPclassifierOutput2confidenceImages(imsegs, conf_maps)
% Computes confidence maps from results of APPtestImage
%
% Copyright(C) Derek Hoiem, Carnegie Mellon University, 2005
% Permission granted to non-commercial enterprises for
% modification/redistribution under GNU GPL.
% Current Version: 1.0  09/30/2005

nvclasses = length(conf_maps(1).vnames);
nhclasses = length(conf_maps(1).hnames);
nclasses = nvclasses+nhclasses;
for v = 1:nvclasses
    cnames{v} = ['v' conf_maps(1).vnames{v}];
end
for h = 1:nhclasses
    cnames{nvclasses+h} = ['h' conf_maps(1).hnames{h}];
end

cimages = cell(length(imsegs), 1);

for f = 1:length(imsegs)

    for n = 1:nclasses
        cim{n} = single(ones(imsegs(f).imsize)/nclasses);
    end

%     for s = 1:imsegs(f).nseg
%
%         ind = find(imsegs(f).segimage==s);
%
%         for v = 1:nvclasses
%             cim{v}(ind) = single(conf_maps(f).vmap(s, v));
%         end
%         for h = 1:nhclasses
%             cim{nvclasses+h}(ind) = single(conf_maps(f).hmap(s, h));
%         end
%
%     end

    cimages{f} = single(zeros([imsegs(f).imsize nclasses]));

    vind = find(strcmp(cnames, 'v090'));

    for n = 1:nclasses
        if n <= nvclasses
            %cimages{f}(:, :, n) = cim{n};
            tmpmap = conf_maps(f).vmap(:, n);
            cimages{f}(:, :, n) = tmpmap(imsegs(f).segimage);
        else
            % multiply P(vclass|X) by P(vertical|X)
            tmpmap = conf_maps(f).hmap(:, n-nvclasses);
            %cimages{f}(:, :, n) = cim{n}.*cim{vind};
            cimages{f}(:, :, n) = tmpmap(imsegs(f).segimage).*cimages{f}(:, :, vind);
        end
    end
end

author: zouchuhang

repo: LayoutNet


text:
function test_ft_sourcedepth

% MEM 1gb
% WALLTIME 00:10:00
% DEPENDENCY ft_sourcedepth

if nargout
  % assume that this is called by RUNTESTS
  tests = functiontests(localfunctions);
else
  % assume that this is called from the command line
  func = localfunctions;
  for i=1:numel(func)
    fprintf('evaluating %s\n', func2str(func{i}));
    feval(func{i});
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function testSphere(testCase)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

headmodel = [];
headmodel.r = 120;
headmodel.o = [0 0 40];
headmodel.unit = 'mm';

% A negative depth indicates that the source is inside the source
% compartment, positive indicates outside.

assert(isalmostequal(ft_sourcedepth([  0   0  40], headmodel), -120));
assert(isalmostequal(ft_sourcedepth([  0   0  50], headmodel), -110));
assert(isalmostequal(ft_sourcedepth([  0   0  60], headmodel), -100));
assert(isalmostequal(ft_sourcedepth([  0   0 160], headmodel),    0));
assert(isalmostequal(ft_sourcedepth([  0   0 200], headmodel),   40));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function testMesh(testCase)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[pos, tri] = mesh_sphere(2560);

headmodel = [];
headmodel.bnd.pos = pos*120;
headmodel.bnd.pos(:,3) = headmodel.bnd.pos(:,3) + 40;
headmodel.bnd.tri = tri;
headmodel.unit = 'mm';

% the volume conduction model is not a perfect sphere, hence some tolerance is needed
assert(isalmostequal(ft_sourcedepth([  0   0  40], headmodel), -120, 'abstol', 1));
assert(isalmostequal(ft_sourcedepth([  0   0  50], headmodel), -110, 'abstol', 1));
assert(isalmostequal(ft_sourcedepth([  0   0  60], headmodel), -100, 'abstol', 1));
assert(isalmostequal(ft_sourcedepth([  0   0 160], headmodel),    0, 'abstol', 1));
assert(isalmostequal(ft_sourcedepth([  0   0 200], headmodel),   40, 'abstol', 1));

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [mu vr] = ricestat(v, s)
%RICESTAT Mean and variance of Rice/Rician probability distribution.
%   [mu vr] = ricestat(v, s) returns the mean and variance of the Rice
%   distribution with parameters v and s.
%
%   R ~ Rice(v, s) if R = sqrt(X^2 + Y^2), where X ~ N(v*cos(a), s^2) and
%   Y ~ N(v*sin(a), s^2) are independent normal distributions (any real a).
%   Note that v and s are *not* the mean and standard deviation of R!
%
%   Reference: http://en.wikipedia.org/wiki/Rice_distribution (!)
%
%   Example:
%
%     % Compare expected and sample stats:
%     v = 5; s = 4; N = 1000;
%     r = ricernd(v*ones(1, N), s);
%     mu = mean(r), vr = var(r)
%     [Mu Vr] = ricestat(v, s)
%     % Plot histogram and mark expected mean +/- 1 stdev:
%     c = linspace(0, ceil(max(r)), 20);
%     w = c(2); % histogram bin-width
%     h = histc(r, c); bar(c, h, 'histc'); hold on
%     pk = N*w*ricepdf(Mu, v, s);
%     plot([Mu-sqrt(Vr) Mu+sqrt(Vr)], [pk pk]/2, 'ro-')
%     plot(Mu, pk/2, 'rx')
%
%   See also RICEPDF, RICERND, RICEFIT

%   Missing (?) 'See also's RICECDF, RICEINV, RICELIKE

%   Inspired by normstat from the MATLAB statistics toolbox
%   Copyright 2008 Ged Ridgway (Ged at cantab dot net)

L = Lhalf(-0.5 * v^2 / s^2);
mu = s * sqrt(pi/2) * L;
vr = 2*s^2 + v^2 - (pi * s^2 / 2) * L^2;

function l = Lhalf(x)
% Laguerre polynomial L_{1/2}(x)
% see Moments section of http://en.wikipedia.org/wiki/Rice_distribution
l = exp(x/2) * ( (1-x) * besseli(0, -x/2) - x*besseli(1, -x/2) );


text:
if mcs == 1879
    display('1879: Birth of Albert Einstein')
elseif mcs == 1955
    display('1955: Albert Einstein passed away')
elseif mcs == 1933
    display('1933: Albert Einstein, driven by the Nazis, took asylum in U.S.A')
elseif mcs == 1947
    display('Indian Independence')
    display('- - - - - - - - - -')
    display('Dr. B R Ambedkar became law minister of free independent India')
elseif mcs == 1114
    display('Birth of great mathematician bhAskarAchArya.')
    display('He wrote "sidhAnta samhita" which has 2 parts')
    display('1: Two mathematical parts.')
    display('2: Two astronomical parts.')
end

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


text:
classdef SplittingAlgorithmFactory < handle

   methods (Access = public, Static)

       function obj = create(cParams)
           switch cParams.type
               case 'ForwardBackward'
                   obj = ForwardBackward(cParams);
               case 'AcceleratedForwardBackward'
                   obj = AcceleratedForwardBackward(cParams);
           end

       end

   end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function [b]=mrow(a)

% function [b]=mrow(a)
% ------------------------------------------------------------------------
% This function converts the input matrix (or vector) a to a row vector.
%
%
% Change log:
% 2023/03/10: Kevin Moerman Created
%
% ------------------------------------------------------------------------
%%

if ismatrix(a)
    if ~isvector(a) %Check if it is a vector already
        b=a(:)';
    else %Vector so either row already or a column
        if iscolumn(a)
            b=a'; %Transpose
        else
            b=a; %Keep
        end
    end
else
    error('Input is not of matrix type. The mrow function is only defined for matrix arrays, see also ismatrix');
end


text:
%% Plotting Individual Orientations
% Basics of the plot types for individual orientations data
%
%%
% This section gives an overview over the possibilities that MTEX offers to
% visualize orientation data. Let us first load a sample EBSD data set

mtexdata forsterite

%%
% and select all individual orientations of the Iron phase

ebsd('Fo').orientations

%% Scatter Pole Figure Plot
% A pole figure showing scattered points of these data figure can be
% produced by the command <orientation.plotPDF.html plotPDF>.

plotPDF(ebsd('Fo').orientations,Miller(1,0,0,ebsd('Fo').CS))

%% Scatter (Inverse) Pole Figure Plot
% Accordingly, scatter points in inverse pole figures are produced by the
% command  <orientation.plotIPDF.html plotIPDF>.

plotIPDF(ebsd('Fo').orientations,xvector)

%% Scatter Plot in ODF Sections
% The plotting of scatter points in sections of the orientation space is carried out by the
% command <orientation.plotSection.html plotSection>. In the above examples, the number
% of plotted orientations was chosen automatically such that the
% plots not to become too crowded with points. The number of randomly chosen orientations
% can be specified by the option *points*.

plotSection(ebsd('Fo').orientations,'points',1000,'sigma','sections',9)

%% Scatter Plot in Axis Angle or Rodrigues Space
% Another possibility is to plot the single orientations directly into the
% orientation space, i.e., either in axis/angle parameterization or in Rodrigues
% parameterization.

scatter(ebsd('Fo').orientations)

%%
% Here, the optional option 'center' specifies the center of the unique
% region in the orientation space.

%% Orientation plots for EBSD and grains
% Since EBSD and grain data involves single orientations, the above plotting
% commands are also applicable for those objects.

%%
% Let us consider some grains <EBSD.calcGrains.html reconstructed> from the
% EBSD data

grains = calcGrains(ebsd);

%%
% Then the scatter plot of the individual orientations of the Iron phase in
% the inverse pole figure is achieved by

plotIPDF(ebsd('Fo').orientations,xvector,'points',1000, 'MarkerSize',3);

%%
% In the same way, the mean orientations of grains can be visualized

hold all
plotIPDF(grains('Fo').meanOrientation,xvector,'points',500, 'MarkerSize',3);
hold off

%%
% One can also use different colors on the scatter points

h = [Miller(1,0,0,ebsd('Fo').CS),Miller(1,1,0,ebsd('Fo').CS)];
plotPDF(ebsd('Fo').orientations,ebsd('Fo').mad,h,'antipodal','MarkerSize',4)

%%
% or some arbitrary data vector

plotSection(grains('Fo').meanOrientation,log(grains('Fo').area),...
  'sigma','sections',9,'MarkerSize',10);

%%
% See also <PlotTypes_demo.html#5, Scatter plots> for more information
% about scatter plot and <SphericalProjection_demo.html,spherical
% projections>  for more information on spherical projections.

author: mtex-toolbox

repo: mtex

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


text:
function test_minkowski(P, closeAll)
if nargin<2
    closeAll=false;
end
if closeAll
    close all
end
tmplt=['ust_s1_samusikImported_minkowski_' String.encodeBank(P) '_29D_15nn_3D.mat'];
run_umap('s1_samusikImported_29D.csv', 'label_column', 'end', ...
    'label_file', 's1_29D.properties', ...
    'n_components', 3, ...
    'save_template_file', tmplt, ...
    'metric', 'minkowski', ...
    'dist_args', P);
run_umap('s2_samusikImported_29D.csv', ...
    'template_file', tmplt, 'label_column', 'end', ...
    'label_file', 's2_samusikImported_29D.properties', ...
    'match_scenarios', 4,  ...
    'see_training', true, ...
    'match_table_fig', false, ...
    'match_histogram_fig', false, ...
    'false_positive_negative_plot', true, 'match_supervisors', 3);

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% /**
%  * Copyright (C) 2016 CoDyCo
%  * @author: Daniele Pucci, Gabriele Nava
%  * Permission is granted to copy, distribute, and/or modify this program
%  * under the terms of the GNU General Public License, version 2 or any
%  * later version published by the Free Software Foundation.
%  *
%  * A copy of the license can be found at
%  * http://www.robotcub.org/icub/license/gpl.txt
%  *
%  * 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
%  */
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% NOTE: THIS SCRIPT IS RUN AUTOMATICALLY WHEN THE USER STARTS THE ASSOCIATED
% SIMULINK MODEL. NO NEED TO RUN THIS SCRIPT EVERY TIME.
clearvars -except sl_synch_handles simulinkStaticGUI
clc

% Add path to local source code
addpath('./src/')

%% GENERAL SIMULATION INFO
%
% If you are simulating the robot with Gazebo, remember that it is required
% to launch Gazebo as follows:
%
%     gazebo -slibgazebo_yarp_clock.so
%
% and properly set the environmental variable YARP_ROBOT_NAME in the .bashrc.

% Simulation time in seconds. For long simulations, put an high number
% (not inf) for allowing automatic code generation
Config.SIMULATION_TIME = 600000;

% Controller period [s]
Config.tStep           = 0.01;

%% PRELIMINARY CONFIGURATION
%
% DEMO_TYPE: defines the kind of demo that will be performed.
%
% 'YOGA': the robot will perform the YOGA++ demo (highly dynamic movements
%         while balancing on one foot and two feet)
%
% 'COORDINATOR': the robot can either balance on two feet or move from left
%                to right follwing a desired center-of-mass trajectory.
%
DEMO_TYPE                     = 'YOGA';

% Config.SCOPES: debugging scopes activation
Config.SCOPES_WRENCHES        = true;
Config.SCOPES_GAIN_SCHE_INFO  = true;
Config.SCOPES_MAIN            = true;
Config.SCOPES_QP              = true;

% DATA PROCESSING
%
% Save the Matlab workspace after stopping the simulation
Config.SAVE_WORKSPACE         = false;

% Verify that the integration time has been respected during the simulation
Config.CHECK_INTEGRATION_TIME = true;
Config.PLOT_INTEGRATION_TIME  = false;

% Run robot-specific configuration parameters
run(strcat('app/robots/',getenv('YARP_ROBOT_NAME'),'/configRobot.m'));
run(strcat('app/robots/',getenv('YARP_ROBOT_NAME'),'/configStateMachine.m'));
run(strcat('app/robots/',getenv('YARP_ROBOT_NAME'),'/gainsAndReferences.m'));

% Deactivate/activate the internal coordinator
if strcmpi(DEMO_TYPE, 'COORDINATOR')

    Config.COORDINATOR_DEMO = true;

elseif strcmpi(DEMO_TYPE, 'YOGA')

    Config.COORDINATOR_DEMO = false;
end

author: robotology

repo: whole-body-controllers


text:
function ExpFiles = io_expand_filenames(FileFilter, Files)
% Expands a list of paths :
%    1) If it is a file => keep it unchanged
%    2) If they are .ds/ directory with .meg4/.res4 files,
%       or ERPCenter directories with .hdr/.erp files,
%       => keep them as "files to open"
%    3) Else : add all the data files they contains (subdirectories included)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2010

% Returned variable
ExpFiles = {};
% Get file format
FileFormat = char(FileFilter.getFormatName());
% Loop on all the selected items
for i = 1:length(Files)
    % DIRECTORIES
    if isdir(Files{i})
        isDirFile = 0;
        % If CTF/ERP format
        if ismember(FileFormat, {'CTF', 'EEG-ERPCENTER', 'EEG-NEURALYNX', 'EEG-NEURONE'})
            switch (FileFormat)
                case 'CTF'
                    % Check if there are .meg4 or .res4 files in directory
                    dirFiles = [dir(bst_fullfile(Files{i}, '*.meg4'));
                                dir(bst_fullfile(Files{i}, '*.res4'))];
                case 'EEG-ERPCENTER'
                    % Check if there are .hdr file in directory
                    dirFiles = dir(bst_fullfile(Files{i}, '*.hdr'));
                case 'EEG-NEURALYNX'
                    % Check if there are .ncs or .nse files in directory
                    dirFiles = [dir(bst_fullfile(Files{i}, '*.ncs'));
                                dir(bst_fullfile(Files{i}, '*.nse'))];
                case 'EEG-NEURONE'
                    % Get binary files 1-9.bin
                    dirFiles = [dir(bst_fullfile(Files{i}, '1.bin')); dir(bst_fullfile(Files{i}, '2.bin')); dir(bst_fullfile(Files{i}, '3.bin')); dir(bst_fullfile(Files{i}, '4.bin')); dir(bst_fullfile(Files{i}, '5.bin'));
                                dir(bst_fullfile(Files{i}, '6.bin')); dir(bst_fullfile(Files{i}, '7.bin')); dir(bst_fullfile(Files{i}, '8.bin')); dir(bst_fullfile(Files{i}, '9.bin'))];
            end
            j = 1;
            while (~isDirFile && (j <= length(dirFiles)))
                if FileFilter.accept(java.io.File(bst_fullfile(Files{i}, dirFiles(j).name)))
                    isDirFile = 1;
                    ExpFiles = cat(2, ExpFiles, Files{i});
                else
                    j = j + 1;
                end
            end
        end

        % If directory is not a CTF/ERP dir to be opened
        if ~isDirFile
            % Get all files in this directory
            dirFiles = dir(bst_fullfile(Files{i}, '*'));
            % Build a new files list
            dirFullFiles = {};
            for j = 1:length(dirFiles)
                % Skip all the files that start with a '.'
                if (dirFiles(j).name(1) == '.')
                    continue;
                end
                % Skip all the 4D system files
                if strcmpi(FileFormat, '4D') && ismember(dirFiles(j).name, {'config', 'hs_file'})
                    continue;
                end
                dirFullFiles{end + 1} = bst_fullfile(Files{i}, dirFiles(j).name);
            end
            % And call function recursively
            ExpFiles = cat(2, ExpFiles, io_expand_filenames(FileFilter, dirFullFiles));
        end

    % SINGLE FILE
    else
        % Test if is accepted by FileFilter
        if FileFilter.accept(java.io.File(Files{i}))
            % If single file is CTF : get the parent
            if strcmpi(FileFormat, 'CTF') || strcmpi(FileFormat, 'EEG-NEURALYNX')
                ExpFiles{end+1} = bst_fileparts(Files{i});
            else
                ExpFiles{end+1} = Files{i};
            end
        end
    end
end

author: brainstorm-tools


text:
function [ n_data, x, fx ] = struve_h1_values ( n_data )

%*****************************************************************************80
%
%% STRUVE_H1_VALUES returns some values of the Struve H1 function.
%
%  Discussion:
%
%    The function is defined by:
%
%      H1(x) = 2*x/pi * Integral ( 0 <= t <= pi/2 )
%        sin ( x * cos ( t ) )^2 * sin ( t ) dt
%
%    In Mathematica, the function can be evaluated by:
%
%      StruveH[1,x]
%
%    The data was reported by McLeod.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 September 2004
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Milton Abramowitz and Irene Stegun,
%    Handbook of Mathematical Functions,
%    US Department of Commerce, 1964.
%
%    Allan McLeod,
%    Algorithm 757, MISCFUN: A software package to compute uncommon
%      special functions,
%    ACM Transactions on Mathematical Software,
%    Volume 22, Number 3, September 1996, pages 288-301.
%
%    Stephen Wolfram,
%    The Mathematica Book,
%    Fourth Edition,
%    Wolfram Media / Cambridge University Press, 1999.
%
%  Parameters:
%
%    Input/output, integer N_DATA.  The user sets N_DATA to 0 before the
%    first call.  On each call, the routine increments N_DATA by 1, and
%    returns the corresponding data; when there is no more data, the
%    output value of N_DATA will be 0 again.
%
%    Output, real X, the argument of the function.
%
%    Output, real FX, the value of the function.
%
  n_max = 20;

  fx_vec = [ ...
     0.80950369576367526071E-06, ...
     0.12952009724113229165E-04, ...
     0.82871615165407083021E-03, ...
     0.13207748375849572564E-01, ...
     0.19845733620194439894E+00, ...
     0.29853823231804706294E+00, ...
     0.64676372828356211712E+00, ...
     0.10697266613089193593E+01, ...
     0.38831308000420560970E+00, ...
     0.74854243745107710333E+00, ...
     0.84664854642567359993E+00, ...
     0.58385732464244384564E+00, ...
     0.80600584524215772824E+00, ...
     0.53880362132692947616E+00, ...
     0.72175037834698998506E+00, ...
     0.58007844794544189900E+00, ...
     0.60151910385440804463E+00, ...
     0.70611511147286827018E+00, ...
     0.61631110327201338454E+00, ...
     0.62778480765443656489E+00 ];

  x_vec = [ ...
        0.0019531250E+00, ...
       -0.0078125000E+00, ...
        0.0625000000E+00, ...
       -0.2500000000E+00, ...
        1.0000000000E+00, ...
        1.2500000000E+00, ...
        2.0000000000E+00, ...
       -4.0000000000E+00, ...
        7.5000000000E+00, ...
       11.0000000000E+00, ...
       11.5000000000E+00, ...
      -16.0000000000E+00, ...
       20.0000000000E+00, ...
       25.0000000000E+00, ...
      -30.0000000000E+00, ...
       50.0000000000E+00, ...
       75.0000000000E+00, ...
      -80.0000000000E+00, ...
      100.0000000000E+00, ...
     -125.0000000000E+00 ];

  if ( n_data < 0 )
    n_data = 0;
  end

  n_data = n_data + 1;

  if ( n_max < n_data )
    n_data = 0;
    x = 0.0;
    fx = 0.0;
  else
    x = x_vec(n_data);
    fx = fx_vec(n_data);
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%--- help for complementarity_memoizer ---
%
%  Memoize linear and nonlinear restrictions
%
%  ::
%
%    [sep_cf,cf]=complementarity_memoizer(obj)
%
%  Args:
%
%     obj (rise | dsge | svar | rfvar): model object
%
%  Returns:
%     :
%
%     - **sep_cf** [function handle]: function that takes as input a vector of
%       variable values and returns a vector of values that are expected to be
%       greater than or equal to 0.
%
%     - **cf** [function handle]: function that takes as input a vector of
%       variable values and returns a true if all the restrictions are satisfied
%       and returns false otherwise
%
%

author: jmaih


text:
function legendre_polynomial_plot01 ( )

%*****************************************************************************80
%
%% LEGENDRE_POLYNOMIAL_PLOT01 tests P_POLYNOMIAL_PLOT.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    13 March 2012
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'LEGENDRE_POLYNOMIAL_PLOT01:\n' );
  fprintf ( 1, '  P_POLYNOMIAL_PLOT creates a plot of one or more Legendre functions.\n' );

  index = [ 0, 1, 2, 3, 4, 5 ];
  filename = 'p_polynomial_plot.png';

  p_polynomial_plot ( index, filename );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Legendre polynomial plot stored in file "%s".\n', filename );

  return
end


text:
function [h_1d,h_2d] = create_h(sigma_h, size_h, opt, mode)

if sigma_h > opt.M || sigma_h > opt.N
    error('blur kernel must be smaller than image');
end

if mode == 1
    x = linspace(-size_h/2, size_h/2, size_h);
    h_1d = exp(-x.^2 / (2 * sigma_h^2)); % 1D Guassian filter kernel
    h_1d = h_1d / sum(h_1d); % normalize
    h_2d = kron(h_1d',h_1d);
elseif mode == 2
    h_2d = ones(size_h,size_h) / (size_h*size_h);
end


text:
function beta_vector = scattering_coefficient_random(number_of_images,...
    parameters)
%SCATTERING_COEFFICIENT_RANDOM  Generate scattering coefficient values for a set
%of images uniformly at random.
%   Inputs:
%       -|number_of_images|: number of images for which scattering coefficient
%       is simulated.
%       -|parameters|: structure containing miscellaneous parameters, such as
%       range of values for scattering coefficient and type of random number
%       generator. Guarantees uniformity with other functions that implement
%       generation of scattering coefficient values.
%
%   Outputs:
%       -|beta_vector|: 1-by-|number_of_images| vector containing the random
%       values of scattering coefficient for every image in the set.

% Determine the range of random values for scattering coefficient.
maximum_value = parameters.maximum_value;
minimum_value = parameters.minimum_value;

% Get type of random number generator, e.g. 'default'.
random_generator = parameters.random_generator;

% Get binary flag that indicates whether the random number generator should be
% configured or not.
configure_random_generator = parameters.configure_random_generator;

% Optionally configure random number generation for repeatability.
if configure_random_generator
    rng(random_generator);
end

% Generate random scattering coefficient for each image following a uniform
% distribution inside the specified range.
beta_vector = minimum_value + (maximum_value - minimum_value) *...
    rand(1, number_of_images);

end

author: sakaridis


text:
function ydata = tsne_d(D, labels, no_dims, perplexity)
%TSNE_D Performs symmetric t-SNE on the pairwise Euclidean distance matrix D
%
%   mappedX = tsne_d(D, labels, no_dims, perplexity)
%   mappedX = tsne_d(D, labels, initial_solution, perplexity)
%
% The function performs symmetric t-SNE on the NxN pairwise Euclidean
% distance matrix D to construct an embedding with no_dims dimensions
% (default = 2). An initial solution obtained from an other dimensionality
% reduction technique may be specified in initial_solution.
% The perplexity of the Gaussian kernel that is employed can be specified
% through perplexity (default = 30). The labels of the data are not used
% by t-SNE itself, however, they are used to color intermediate plots.
% Please provide an empty labels matrix [] if you don't want to plot
% results during the optimization.
% The data embedding is returned in mappedX.
%
%

% This file is part of the Matlab Toolbox for Dimensionality Reduction.
% The toolbox can be obtained from http://homepage.tudelft.nl/19j49
% You are free to use, change, or redistribute this code in any way you
% want for non-commercial purposes. However, it is appreciated if you
% maintain the name of the original author.
%
% (C) Laurens van der Maaten, Delft University of Technology

    if ~exist('labels', 'var')
        labels = [];
    end
    if ~exist('no_dims', 'var') || isempty(no_dims)
        no_dims = 2;
    end
    if ~exist('perplexity', 'var') || isempty(perplexity)
        perplexity = 30;
    end

    % First check whether we already have an initial solution
    if numel(no_dims) > 1
        initial_solution = true;
        ydata = no_dims;
        no_dims = size(ydata, 2);
    else
        initial_solution = false;
    end

    % Compute joint probabilities
    D = D / max(D(:));                                                      % normalize distances
    P = d2p(D .^ 2, perplexity, 1e-5);                                      % compute affinities using fixed perplexity

    % Run t-SNE
    if initial_solution
        ydata = tsne_p(P, labels, ydata);
    else
        ydata = tsne_p(P, labels, no_dims);
    end

repo: cluster


text:
function G = mldivide( a, F )
%\  DISKFUNV left divide.
%
%  a\F Divides each component of a DISKFUNV F by the scalar a.
%
%  One is only allowed to divide a DISKFUNV by a scalar.
%
% See also MRDIVIDE.

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

% Empty check:
if ( ( isempty(a) ) || ( isempty(F) ) )
    G = diskfunv();
    return
end

% Only allow a\F, where a is a scalar:
if ( ~isa(a, 'double') )
    error('DISKFUN:DISKFUNV:mldivide:nonScalar', ...
        'Division must be by a scalar.');
end

% Left divide:
G = F;
G.components{1} = mldivide( a, F.components{1} );
G.components{2} = mldivide( a, F.components{2} );

end


text:
classdef TestGeneralizedHoughGuil
    %TestGeneralizedHoughGuil

    methods (Static)
        function test_1
            hough = cv.GeneralizedHoughGuil();
            [img, tmpl] = sample_data();
            hough.setTemplate(tmpl);
            [pos,votes] = hough.detect(img);
            assert(iscell(pos) && iscell(votes));
            assert(isequal(numel(pos), numel(votes)));
            if ~isempty(pos)
                assert(all(cellfun(@numel,pos) == 4));
                assert(all(cellfun(@numel,votes) == 3));
            end
        end

        function test_2
            hough = cv.GeneralizedHoughGuil();
            [img, tmpl] = sample_data();
            [edges, dx, dy] = calcEdges(tmpl);
            hough.setTemplate(edges, dx, dy);
            [pos,votes] = hough.detect(img);
        end

        function test_3
            hough = cv.GeneralizedHoughGuil();
            [img, tmpl] = sample_data();
            hough.setTemplate(tmpl);
            [edges, dx, dy] = calcEdges(img);
            [pos,votes] = hough.detect(edges, dx, dy);
        end
    end

end

function [img, tmpl] = sample_data()
    img = zeros(200,200,'uint8');
    img(20:50,20:50) = 255;
    img(120:150,120:150) = 255;

    tmpl = zeros(50,50,'uint8');
    tmpl(10:40,10:40) = 255;
end

function [edges, dx, dy] = calcEdges(img)
    edges = cv.Canny(img, [50 100]);
    dx = cv.Sobel(img, 'DDepth','single', 'XOrder',1, 'YOrder',0);
    dy = cv.Sobel(img, 'DDepth','single', 'XOrder',0, 'YOrder',1);
end

author: kyamagu

repo: mexopencv


text:
function pass = test_promote_functional(~)

% Test operator + functional and operator*functional.

tol = 1e-10;

%%
N = chebop(@(u) diff(u,2) + sum(u));
N.lbc = 0;
N.rbc = 0;
u = N\1;
pass(1) = norm(N(u) - 1, inf) < tol;

%%
N = chebop(@(u) diff(u,2) + u.*sum(u));
N.lbc = 0;
N.rbc = 0;
u = N\1;
pass(2) = norm(N(u) - 1, inf) < tol;

%%
N = chebop(@(x,u,v) [diff(u) ; diff(v)]);
N.bc = @(x,u, v) [u(0) - 1; u(0).*v(.5)];
N.init = [1 ; 0];
pass(3) = size(matrix(linearize(N), 3), 1) == 8;
u = N\1;
pass(4) = norm(N(u) - 1, inf) < tol;

%%

N = chebop(@(x,u,v) [diff(u) ; diff(v) + v.*sum(u) + u(.3)]);
N.bc = @(x,u, v) [u(0)-1; u(0).*v(.5)];
pass(5) = size(matrix(linearize(N), 3), 1) == 8;
u = N\1;
pass(6) = norm(N(u) - 1, inf) < tol;

%% Periodic (with values):

N = chebop(@(u) diff(u,2) + sum(u));
N.bc = 'periodic';
rhs = chebfun(@(x) cos(pi*x));
u = N\rhs;
pass(7) = norm(N(u) - rhs, inf) < tol;
pass(8) = isequal(get(u.funs{1}, 'tech'), @trigtech);

%% Periodic (with coeffs):

N = chebop(@(u) diff(u,2) + sum(u));
N.bc = 'periodic';
rhs = chebfun(@(x) cos(pi*x));
pref = cheboppref();
pref.discretization = 'coeffs';
u = solvebvp(N, rhs, pref);
pass(9) = norm(N(u) - rhs, inf) < tol;
pass(10) = isequal(get(u.funs{1}, 'tech'), @trigtech);

end

author: chebfun


text:
%% DS - CDMA (SNR-Performance)
clear all;close all;clc;
nu=input('Number of Users = ');
u=[];s=[];
ml=input('Number of bits for each user = ');
hl=2^nextpow2(nu);
%
for k = 1:nu

u_binary(k,:)=randi([0 1],1,ml);

end
for k = 1:nu

u_BPSK(k,:)=u_binary(k,:)*2-1;

end
for n=1:nu
    s(n,:)=cdmat(u_BPSK(n,:),hl,n);
end
cd1=sum(s);
%% Oversampling
cd =rectpulse(cd1,4);
loo=0;
for SNR=0:2:8

    loo=loo+1;

    t=awgn(cd,SNR,'measured');

    %% Integrate and dump (downsampling)
    or=intdump(t,4);

    sr=[];
    for p=1:nu
        sr(p,:)=cdmar(or,hl,p,ml);
    end

    binary_rx=(sr+1)/2;
[n(loo),r(loo)]=symerr(u_BPSK,sr);
end

figure;%plot combined signals
%Tx
subplot(211);stem(cd1(1:20),'filled');
title('Combined signals (only 20 symbols');
xlabel('Index of Combined symbols');
ylabel('Magnitude');
grid;
%Rx
subplot(212);stem(or(1:20),'filled');
title('Combined noisy signals (only 20 symbols');
xlabel('Index of Combined symbols');
ylabel('Magnitude');

grid;

SNR=0:2:8;
figure; % plot the BER vs. SNR
semilogy(SNR,r,'r-x'),grid;

figure;% plot data for a randomly selected user such as user no. 1 before the BPSK mapping Tx and Rx
% Tx
subplot(211);stem(u_binary(1,1:10),'filled');grid
xlabel('Bits index');
title('Transmitted Bits (showing only 10 bits)');
% Rx
subplot(212);stem((sr(1,1:10)+1)/2,'filled');grid
xlabel('Bits index');
title('Received Bits (showing only 10 bits)');

figure;% plot data for a randomly selected user such as user no. 1 after the BPSK mapping Tx and Rx
% Tx
subplot(211);stem(u_BPSK(1,1:10),'filled');grid
xlabel('Symbol index');
title('Transmitted BPSK Symbols (showing only 10 Symbol)');
% Rx
subplot(212);stem(sr(1,1:10),'filled');grid
xlabel('Symbol index');
title('Received BPSK Symbols (showing only 10 Symbol)');

author: Sable


text:
function model = yalmip2sdpt3(interfacedata)
[blk,A,C,b,oldKs]=sedumi2sdpt3(interfacedata.F_struc(:,1),-interfacedata.F_struc(:,2:end),-interfacedata.c,interfacedata.K,interfacedata.options.sdpt3.smallblkdim);
interfacedata.options.sdpt3.printyes=double(interfacedata.options.verbose);
interfacedata.options.sdpt3.expon=interfacedata.options.sdpt3.expon(1);

model.blk = blk;
model.A = A;
model.C = C;
model.b = b;
model.ops = interfacedata.options.sdpt3;

author: yalmip


text:
function displayClass(obj,vName,varargin)

if check_option(varargin,'skipHeader'), return; end

disp(' ');

vName = get_option(varargin,'variableName',vName);
className = class(obj);
altName = get_option(varargin,'className',className);
scopes = get_option(varargin,'moreInfo');

str = [vName ' = ' doclink([className '.' className],altName)];
%str = [vName ' = <strong>' altName '</strong>'];

if ~isempty(scopes), str = [str,' (',scopes,')']; end

disp(str);

end


text:
%COLLISIONMODEL Class to conduct point-primitive collision checking
%
% Group objects from the Shape heirachy and/or other CollisionModel
% objects for collision checking functionality. Once made,
% CollisionModel objects cannot be modified. Primitives are ordered in
% decreasing volume to help optimise the collision checking process.
%
% Copyright (C) Bryan Moutrie, 2013-2014
% Licensed under the GNU Lesser General Public License
% see full file for full statement
%
% Syntax:
%  (1) cmdl = CollisionModel(prim1, prim2, ..., primN)
%  (2) cmdl = CollisionModel(note, prim1, prim2, ..., primN)
%
%  (2) is as per (1) but also includes a text note about the object
%
% Outputs:
%  cmdl : CollisionModel object
%
% Inputs:
%  prim : Primitive shape(s). May either be scalar, array, or cell of
%          objects which are from the Shape class heirachy, or a scalar
%          CollisionModel object.
%  note : Short text description of object for user reference
%
% See documentation for information on properties and methods
% (type doc CollisionModel into the command window)
%
% See also Box.Box collisions Cone Curvilinear Cylinder.Cylinder
%  Ellipsoid.Ellipsoid Shape Sphere.Sphere

% 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 Lesser 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 CollisionModel

    properties (SetAccess = private)
        primitives % Primitive shapes of the CollisionModel
        checkFuns % Function handles to check each primitive
        % Short text description of object for user reference
        note = '<Add a description with note property>'
    end

    methods
        function cmdl = CollisionModel(varargin)
            if ischar(varargin{1})
                cmdl.note = varargin{1};
                shapes = varargin(2:end);
            else
                shapes = varargin;
            end

            i = 1;
            while i <= length(shapes)
                if isa(shapes{i},'CollisionModel')
                    cell = shapes{i}.primitives;
                elseif ~isscalar(shapes{i})
                    cell = num2cell(shapes{i});
                elseif iscell(shapes{i})
                    cell = shapes{i};
                else
                    cell = [];
                end
                if ~isempty(cell)
                    shapes = [shapes(1:i-1) cell(:)' shapes(i+1:end)];
                end
                i = i + 1;
            end

            for i = length(shapes): -1: 1
                negVol(i) = -shapes{i}.volume;
                funcs{i} = shapes{i}.check;
            end

            [~, order] = sort(negVol);
            cmdl.checkFuns = funcs(order);
            cmdl.primitives = shapes(order);
        end

        function h = plot(cmdl, varargin)
            %PLOT Plot the CollisionModel
            %
            % As per the Shape method, but options affect all primitives
            %
            % See also Shape.plot

            n = length(cmdl.primitives);
            hold on
            if nargout == 1, h = []; end
            for i = 1: n
                hn = cmdl.primitives{i}.plot(varargin{:});
                if nargout == 1, h = [h, hn]; end
            end
            hold off
        end

        function c = collision(cmdl, pts)
            %COLLISION Determine if a collision is occuring
            %
            % As per the check method, but c is a scalar value, and
            % will return as soon as a collision is determined
            %
            % See also CollisionModel.check

            n = length(cmdl.primitives);
            c = false;
            for i = 1: n
                if any(cmdl.checkFuns{i}(pts(:,1),pts(:,2),pts(:,3)));
                    c = true;
                    return;
                end
            end
        end

        function inside = check(cmdl, pts)
            %CHECK Check if point(s) are inside the CollisionModel
            %
            % As per the Shape method, but c is mxp, where p is the
            % number of primitives
            %
            % See also CollisionModel.collisions Shape.check

            n = length(cmdl.primitives);
            inside = zeros(size(pts,1),n);
            for i = 1: n
                inside(:,i) = ...
                    cmdl.checkFuns{i}(pts(:,1), pts(:,2), pts(:,3));
            end
        end
    end

end

author: Allopart

repo: rbpf-gmapping


text:
function [result,modified_q] = fit_q_to_range(qmin,qmax,q)
modified_q = q;
while modified_q<qmin
    modified_q = modified_q+2*pi;
end
while modified_q>qmax
    modified_q = modified_q-2*pi;
end
if modified_q<qmin
    result = false;
else
    result = true;
end
end

author: xuhuairuogu

repo: V-REP-Simulation-Projects

path: github-repos/MATLAB/xuhuairuogu-V-REP-Simulation-Projects/V-REP-Simulation-Projects-841b944af4ea3a8fb250578d36434515f577f411/admittance control(adapted from an example in the book--A Systematic Approach to Learning Robot Programming with ROS)/iiwa14_kinematics/fit_q_to_range.m


text:
% Steering A Linear Array Example
%
% This example demonstrates how to use k-Wave to steer a tone burst from a
% linear array transducer in 2D. It builds on the Simulating Transducer
% Field Patterns Example.
%
% author: Bradley Treeby
% date: 10th December 2009
% last update: 24th August 2014
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

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

clear all;

% =========================================================================
% SIMULATION
% =========================================================================

% create the computational grid
Nx = 128;           % number of grid points in the x (row) direction
Ny = Nx;            % number of grid points in the y (column) direction
dx = 50e-3/Nx;    	% grid point spacing in the x direction [m]
dy = dx;            % grid point spacing in the y direction [m]
kgrid = makeGrid(Nx, dx, Ny, dy);

% define the properties of the propagation medium
medium.sound_speed = 1500;  % [m/s]
medium.alpha_power = 1.5;   % [dB/(MHz^y cm)]
medium.alpha_coeff = 0.75;  % [dB/(MHz^y cm)]

% create the time array
[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);
kgrid.t_array = 0:dt:500*dt;

% define source mask for a linear transducer with an odd number of elements
num_elements = 21;      % [grid points]
x_offset = 25;          % [grid points]
source.p_mask = zeros(Nx, Ny);
start_index = Ny/2 - round(num_elements/2) + 1;
source.p_mask(x_offset, start_index:start_index + num_elements - 1) = 1;

% define the properties of the tone burst used to drive the transducer
sampling_freq = 1/dt;   % [Hz]
steering_angle = 30;    % [deg]
element_spacing = dx;   % [m]
tone_burst_freq = 1e6;  % [Hz]
tone_burst_cycles = 8;

% create an element index relative to the centre element of the transducer
element_index = -(num_elements - 1)/2:(num_elements - 1)/2;

% use geometric beam forming to calculate the tone burst offsets for each
% transducer element based on the element index
tone_burst_offset = 40 + element_spacing*element_index*sin(steering_angle*pi/180)/(medium.sound_speed*dt);

% create the tone burst signals
source.p = toneBurst(sampling_freq, tone_burst_freq, tone_burst_cycles, 'SignalOffset', tone_burst_offset);

% assign the input options
input_args = {'DisplayMask', source.p_mask};

% run the simulation
kspaceFirstOrder2D(kgrid, medium, source, [], input_args{:});

% =========================================================================
% VISUALISATION
% =========================================================================

% plot the input time series
figure;
num_source_time_points = length(source.p(1,:));
[t_sc, scale, prefix] = scaleSI(kgrid.t_array(num_source_time_points));
stackedPlot(kgrid.t_array(1:num_source_time_points)*scale, source.p);
xlabel(['Time [' prefix 's]']);
ylabel('Input Signals');

repo: Aero-matlab


text:
classdef prtClassBinomial < prtClass
 %prtClassBinomial  Maximum a Posteriori classifier for binary data using
 %  IID binomial distributions for each feature (column) under each
 %  hypothesis (class)
 %
 %  Properties:
 %
 %       priorSuccesses = 1e-3;  %I think I did this right.
 %       priorTrials = 10000e-3;
 %

    properties (SetAccess=private)
        name = 'Binomial'
        nameAbbreviation = 'Binom'
        isNativeMary = true;
    end

    properties
        priorSuccesses = 1e-3;
        priorTrials = 10000e-3;
        pSuccessByClass = [];
    end

    methods
        % Constructor
        function self = prtClassBinomial(varargin)

            self.classTrain = 'prtDataInterfaceCategoricalTargets';
            self.classRun = 'prtDataSetBase';
            self.classRunRetained = false;

            self = prtUtilAssignStringValuePairs(self,varargin{:});
        end
    end

    methods (Access = protected, Hidden = true)

        function self = trainAction(self,ds)

            self.pSuccessByClass = [];
            for iClass = 1:ds.nClasses;
                classDs = ds.retainClassesByInd(iClass);
                pVec = (sum(classDs.X,1)+self.priorSuccesses)./(classDs.nObservations + self.priorTrials);
                pVec = full(pVec);
                self.pSuccessByClass(iClass,:) = pVec;
            end
        end

        function ds = runAction(self,ds)

            nClasses = size(self.pSuccessByClass,1);
            logLikelihoods = zeros(ds.nObservations, nClasses);
            for iY = 1:nClasses
                pVec = self.pSuccessByClass(iY,:);
                xOut = bsxfun(@times,ds.X,pVec) + bsxfun(@times,~ds.X,1-pVec);
                logLikelihoods(:,iY) = sum(log(xOut),2);
            end
            logLikelihoods = exp(bsxfun(@minus, logLikelihoods, prtUtilSumExp(logLikelihoods.').'));
            ds.X = logLikelihoods;
        end
    end
    methods
        function [sorted,pDist] = getSortedFeatures(self)
            % [sorted,pDist] = getSortedFeatures(self)
            %   Return the list of the features in sorted order.  pDist is
            %   the corresponding distance between the MLEs of the mean
            %   p(true)

            nClasses = size(self.pSuccessByClass,1);
            if nClasses ~= 2
                error('Only for binary problems');
            end
            pDist = self.pSuccessByClass(2,:)-self.pSuccessByClass(1,:);
            absDist = abs(pDist);
            [~,sorted] = sort(absDist,'descend');
            pDist = pDist(sorted);

        end
    end

end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
function errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux, fluxesB)
% followFluxes
%	Prints fluxes and reactions for each of the reactions that results in
%   fluxes in the specified interval.
%
%   model       a model structure
%   fluxesA     flux vector for the test case
%   lowerFlux	only reactions with fluxes above this cutoff
%               value are displayed
%   upperFlux   only reactions with fluxes below this cutoff
%               value are displayed (opt, default Inf)
%   fluxesB     flux vector for the reference case(opt)
%
%   Usage: errorFlag=followFluxes(model, fluxesA, lowerFlux, upperFlux,
%           fluxesB)

%Checks that the upper flux is larger than the lower flux
if nargin>3
    if upperFlux<=lowerFlux
        errorFlag=1;
        return;
    end
end

%Gets the fluxes for the reactions
if nargin<4
    fluxIndexes=find(fluxesA>=lowerFlux);
else
    fluxIndexes=find(fluxesA>=lowerFlux & fluxesA<=upperFlux);
end

%Finds the involved reactions
formulas = constructEquations(model,model.rxns(fluxIndexes));

if nargin>3
    fprintf('These reactions have flux values between %s and %s\n\n',num2str(lowerFlux),num2str(upperFlux));
else
    fprintf('These reactions have flux values above %s\n\n',num2str(lowerFlux));
end
for i=1:length(formulas)
    if nargin>4
        fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i))) ' Reference flux: ' num2str(fluxesB(fluxIndexes(i)))];
    else
        fluxText=['Flux: ' num2str(fluxesA(fluxIndexes(i)))];
    end
    fprintf('%s: %s\n\t%s\n\t%s\n', char(model.rxns(fluxIndexes(i))), char(formulas(i)),...
        char(model.rxnNames(fluxIndexes(i))),fluxText);
end
end

author: SysBioChalmers

repo: RAVEN