text:
function RadiobutmHenry
warning('off','MATLAB:dispatcher:InexactMatch')
Hhandle=findobj('Tag','Henry');
H=get(Hhandle,'Value');
mHhandle=findobj('Tag','mHenry');
mH=get(mHhandle,'Value');
if mH==1
   H=0;
   set(mHhandle, 'Value', 1);  set(mHhandle, 'SelectionHighlight', 'On');
   set(Hhandle,'Value', 0);    set(Hhandle, 'SelectionHighlight', 'Off');
  else
  set(mHhandle, 'Value', 0);   set(mHhandle, 'SelectionHighlight', 'Off');
   set(Hhandle,'Value', 1);    set(Hhandle, 'SelectionHighlight', 'On');
   H=1;
end

author: Sable

repo: mcbench-benchmarks


text:
function [C,numberOfOverlapPixels] = normxcorr2_general(varargin)
%NORMXCORR2_GENERAL Normalized two-dimensional cross-correlation.
%   [C,numberOfOverlapPixels] = NORMXCORR2_GENERAL(TEMPLATE,A) computes the
%   normalized cross-correlation of matrices TEMPLATE and A. The resulting
%   matrix C contains correlation coefficients and its values may range
%   from -1.0 to 1.0.
%
%   [C,numberOfOverlapPixels] =
%   NORMXCORR2_GENERAL(TEMPLATE,A,requiredNumberOfOverlapPixels) sets to 0
%   all locations in C computed from positions where A and T overlap less
%   than requiredNumberOfOverlapPixels.
%   Larger values of requiredNumberOfOverlapPixels zero-out pixels on a
%   larger border around C.
%   Thus, larger values remove less stable computations but also limit the
%   capture range.
%   If the template is smaller than the image and it is desired that the
%   computation only be carried out when the template is fully overlapping
%   the image, requiredNumberOfOverlapPixels should be set to
%   numel(template).
%   The default is set to 0, meaning no modifications to C.
%
%   Limitations of normxcorr2:
%   The documentation of normxcorr2 states that, "The matrix A must be
%   larger than the matrix TEMPLATE for the normalization to be
%   meaningful." It is implemented following the details of the paper "Fast
%   Normalized Cross-Correlation", by J. P. Lewis, Industrial Light &
%   Magic. This approach assumes the template is small relative to the
%   image and proceeds to calculate the normalization across the entire
%   template. This leads to correct computations wherever the template is
%   wholly overlapping with the image, but the computation is incorrect in
%   the borders of the output (the border size is proportional to the
%   template size).  This problem is therefore worse for larger templates
%   to the point that, when the template is the same size as the image, the
%   only correct value is at the center pixel (where the images are fully
%   overlapping). Thus, if normxcorr2 is used for such things as
%   registering images of the same size, the result will be incorrect.
%
%   The new normxcorr2_general:
%   normxcorr2_general is more general than normxcorr2 in that it gives
%   correct results everywhere regardless of the relative size of A and
%   TEMPLATE. It accomplishes this by computing the normalized correlation
%   only in the overlap regions between the two matrices. Thus, the result
%   is correct for all locations of correlation.  The result is the same as
%   if the NCC were carried out in the spatial domain (which would take a
%   long time to compute for large matrices).
%
%   Class Support
%   -------------
%   The input matrices can be numeric. The output matrix C is double.
%
%   Example
%   -------
%   This example correlates an input with itself using normxcorr2 (the
%   built-in Matlab version) and normxcorr2_general (the general version).
%   Because the template is not small compared with the input image (they
%   are the same size in this case), the output of normxcorr2.m is
%   incorrect for most pixels.  On the other hand, the general version is
%   correct at all locations, which can be easily verified analytically or
%   visually.
%
%   Note that the image processing toolbox (IPT) is needed to run this
%   example since normxcorr2 is part of that toolbox.  However,
%   normxcorr2_general does not require the IPT.
%
%   input = repmat([1:6 5:-1:1],11,1);
%   normxcorr2_output = normxcorr2(input,input);
%   normxcorr2_general_output = normxcorr2_general(input,input);
%   figure;
%   subplot(2,2,1), imagesc(input); title('Input pattern');
%   subplot(2,2,3), imagesc(normxcorr2_output); title('Output of Matlab built-in normxcorr2');
%   subplot(2,2,4), imagesc(normxcorr2_general_output); title('Output of normxcorr2\_general');
%
%   See also NORMXCORR2.
%
%   References: Dirk Padfield. "Masked FFT registration". In Proc. Computer
%   Vision and Pattern Recognition, 2010.
%
%   Author: Dirk Padfield, GE Global Research, padfield@research.ge.com
%

%   Input-output specs
%   ------------------
%   T:    2-D, real, full matrix
%         logical, uint8, uint16, or double
%         no NaNs, no Infs
%         prod(size(T)) >= 2
%
%   A:    2-D, real, full matrix
%         logical, uint8, uint16, or double
%         no NaNs, no Infs
%         prod(size(A)) >= 2
%
%   C:    double

[T, A, requiredNumberOfOverlapPixels] = ParseInputs(varargin{:});

sizeA = size(A);
sizeT = size(T);

% Find the number of pixels used for the calculation as the two images are
% correlated.  The size of this image will be the same as the correlation
% image.
numberOfOverlapPixels = local_sum(ones(sizeA),sizeT(1),sizeT(2));

local_sum_A = local_sum(A,sizeT(1),sizeT(2));
local_sum_A2 = local_sum(A.*A,sizeT(1),sizeT(2));

% Note: diff_local_sums should be nonnegative, but it may have negative
% values due to round off errors. Below, we use max to ensure the radicand
% is nonnegative.
diff_local_sums_A = ( local_sum_A2 - (local_sum_A.^2)./ numberOfOverlapPixels );
clear local_sum_A2;
denom_A = max(diff_local_sums_A,0);
clear diff_local_sums_A;

% Flip T in both dimensions so that its correlation can be more easily
% handled.
rotatedT = rot90(T,2);
local_sum_T = local_sum(rotatedT,sizeA(1),sizeA(2));
local_sum_T2 = local_sum(rotatedT.*rotatedT,sizeA(1),sizeA(2));
clear rotatedT;

diff_local_sums_T = ( local_sum_T2 - (local_sum_T.^2)./ numberOfOverlapPixels );
clear local_sum_T2;
denom_T = max(diff_local_sums_T,0);
clear diff_local_sums_T;

denom = sqrt(denom_T .* denom_A);
clear denom_T denom_A;

xcorr_TA = xcorr2_fast(T,A);
clear A T;
numerator = xcorr_TA - local_sum_A .* local_sum_T ./ numberOfOverlapPixels;
clear xcorr_TA local_sum_A local_sum_T;

% denom is the sqrt of the product of positive numbers so it must be
% positive or zero.  Therefore, the only danger in dividing the numerator
% by the denominator is when dividing by zero. We know denom_T~=0 from
% input parsing; so denom is only zero where denom_A is zero, and in these
% locations, C is also zero.
C = zeros(size(numerator));
tol = 1000*eps( max(abs(denom(:))) );
i_nonzero = find(denom > tol);
C(i_nonzero) = numerator(i_nonzero) ./ denom(i_nonzero);
clear numerator denom;

% Remove the border values since they result from calculations using very
% few pixels and are thus statistically unstable.
% By default, requiredNumberOfOverlapPixels = 0, so C is not modified.
if( requiredNumberOfOverlapPixels > max(numberOfOverlapPixels(:)) )
    error(['ERROR: requiredNumberOfOverlapPixels ' num2str(requiredNumberOfOverlapPixels) ...
    ' must not be greater than the maximum number of overlap pixels ' ...
    num2str(max(numberOfOverlapPixels(:))) '.']);
end
C(numberOfOverlapPixels < requiredNumberOfOverlapPixels) = 0;

%-------------------------------
% Function  local_sum
%
function local_sum_A = local_sum(A,m,n)

% This algorithm depends on precomputing running sums.

% If m,n are equal to the size of A, a faster method can be used for
% calculating the local sum.  Otherwise, the slower but more general method
% can be used.  The faster method is more than twice as fast and is also
% less memory intensive.
if( m == size(A,1) && n == size(A,2) )
    s = cumsum(A,1);
    c = [s; repmat(s(end,:),m-1,1) - s(1:end-1,:)];
    s = cumsum(c,2);
    clear c;
    local_sum_A = [s, repmat(s(:,end),1,n-1) - s(:,1:end-1)];
else
    % Break the padding into parts to save on memory.
    B = zeros(size(A,1)+2*m,size(A,2));
    B(m+1:m+size(A,1),:) = A;
    s = cumsum(B,1);
    c = s(1+m:end-1,:)-s(1:end-m-1,:);
    d = zeros(size(c,1),size(c,2)+2*n);
    d(:,n+1:n+size(c,2)) = c;
    s = cumsum(d,2);
    local_sum_A = s(:,1+n:end-1)-s(:,1:end-n-1);
end

%-------------------------------
% Function  xcorr2_fast
%
function cross_corr = xcorr2_fast(T,A)

T_size = size(T);
A_size = size(A);
outsize = A_size + T_size - 1;

% Figure out when to use spatial domain vs. freq domain
conv_time = time_conv2(T_size,A_size); % 1 conv2
fft_time = 3*time_fft2(outsize); % 2 fft2 + 1 ifft2

if (conv_time < fft_time)
    cross_corr = conv2(rot90(T,2),A);
else
    cross_corr = freqxcorr(T,A,outsize);
end

%-------------------------------
% Function  freqxcorr
%
function xcorr_ab = freqxcorr(a,b,outsize)

% Find the next largest size that is a multiple of a combination of 2, 3,
% and/or 5.  This makes the FFT calculation much faster.
optimalSize(1) = FindClosestValidDimension(outsize(1));
optimalSize(2) = FindClosestValidDimension(outsize(2));

% Calculate correlation in frequency domain
Fa = fft2(rot90(a,2),optimalSize(1),optimalSize(2));
Fb = fft2(b,optimalSize(1),optimalSize(2));
xcorr_ab = real(ifft2(Fa .* Fb));

xcorr_ab = xcorr_ab(1:outsize(1),1:outsize(2));

%-------------------------------
% Function  time_conv2
%
function time = time_conv2(obssize,refsize)

% time a spatial domain convolution for 10-by-10 x 20-by-20 matrices

% a = ones(10);
% b = ones(20);
% mintime = 0.1;

% t1 = cputime;
% t2 = t1;
% k = 0;
% while (t2-t1)<mintime
%     c = conv2(a,b);
%     k = k + 1;
%     t2 = cputime;
% end
% t_total = (t2-t1)/k;

% % convolution time = K*prod(size(a))*prod(size(b))
% % t_total = K*10*10*20*20 = 40000*K
% K = t_total/40000;

% K was empirically calculated by the commented-out code above.
K = 2.7e-8;

% convolution time = K*prod(obssize)*prod(refsize)
time =  K*prod(obssize)*prod(refsize);

%-------------------------------
% Function  time_fft2
%
function time = time_fft2(outsize)

% time a frequency domain convolution by timing two one-dimensional ffts

R = outsize(1);
S = outsize(2);

% Tr = time_fft(R);
% K_fft = Tr/(R*log(R));

% K_fft was empirically calculated by the 2 commented-out lines above.
K_fft = 3.3e-7;
Tr = K_fft*R*log(R);

if S==R
    Ts = Tr;
else
%    Ts = time_fft(S);  % uncomment to estimate explicitly
   Ts = K_fft*S*log(S);
end

time = S*Tr + R*Ts;

%-----------------------------------------------------------------------------
function [T, A, requiredNumberOfOverlapPixels] = ParseInputs(varargin)

if( nargin < 2 || nargin > 3 )
    error('ERROR: The number of arguments must be either 2 or 3.  Please see the documentation for details.');
end

T = varargin{1};
A = varargin{2};

if( nargin == 3 )
    requiredNumberOfOverlapPixels =  varargin{3};
else
    requiredNumberOfOverlapPixels = 0;
end

% The following requires the image processing toolbox, so it is commented
% out here for generality.
%iptcheckinput(T,{'logical','numeric'},{'real','nonsparse','2d','finite'},mfilename,'T',1)
%iptcheckinput(A,{'logical','numeric'},{'real','nonsparse','2d','finite'},mfilename,'A',2)

checkSizesTandA(T,A)

% See geck 342320. If either A or T has a minimum value which is negative, we
% need to shift the array so all values are positive to ensure numerically
% robust results for the normalized cross-correlation.
A = shiftData(A);
T = shiftData(T);

checkIfFlat(T);

%-----------------------------------------------------------------------------
function B = shiftData(A)

B = double(A);

is_unsigned = isa(A,'uint8') || isa(A,'uint16') || isa(A,'uint32');
if ~is_unsigned

    min_B = min(B(:));

    if min_B < 0
        B = B - min_B;
    end

end

%-----------------------------------------------------------------------------
function checkSizesTandA(T,A)

if numel(T) < 2
    eid = sprintf('Images:%s:invalidTemplate',mfilename);
    msg = 'TEMPLATE must contain at least 2 elements.';
    error(eid,'%s',msg);
end

%-----------------------------------------------------------------------------
function checkIfFlat(T)

if std(T(:)) == 0
    eid = sprintf('Images:%s:sameElementsInTemplate',mfilename);
    msg = 'The values of TEMPLATE cannot all be the same.';
    error(eid,'%s',msg);
end

%-----------------------------------------------------------------------------
function [newNumber] = FindClosestValidDimension(n)

% Find the closest valid dimension above the desired dimension.  This
% will be a combination of 2s, 3s, and 5s.

% Incrementally add 1 to the size until
% we reach a size that can be properly factored.
newNumber = n;
result = 0;
newNumber = newNumber - 1;
while( result ~= 1 )
    newNumber = newNumber + 1;
    result = FactorizeNumber(newNumber);
end

%-----------------------------------------------------------------------------
function [n] = FactorizeNumber(n)

for ifac = [2 3 5]
    while( rem(n,ifac) == 0 )
        n = n/ifac;
    end
end

author: kavli-ntnu


text:
function tcourses_svm = classify_ConvertForSVM(tcourses, trials)

nConds = length(tcourses.labels);
[nVoxels nTimePoints] = size(tcourses.data.conditions(1).trials{1});
nEntries = nTimePoints*nVoxels;
nTrials = length(trials);
tcourses_svm.trials = trials;
tcourses_svm.labels = tcourses.labels;
tcourses_svm.label_vector = (1:(nConds*nTrials))';
tcourses_svm.instance_matrix = zeros(nConds,nEntries);

condIndex = 0;
for cond = 1:nConds
    for trial = trials;
        condIndex = condIndex + 1;
        tcourses_svm.label_vector(condIndex) = cond;
        tcourses_svm.instance_matrix(condIndex,:) = ...
            reshape(tcourses.data.conditions(cond).trials{trial}',[1 nEntries]);
    end
end

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function varargout=pow2cep(varargin)
%
% For calling details please see v_pow2cep.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_pow2cep.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: pow2cep.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_pow2cep(varargin{:});
else
    v_pow2cep(varargin{:});
end

author: ImperialCollegeLondon

repo: sap-voicebox


text:
function [c, ceq] = pathConstraint(z)
% [c, ceq] = pathConstraint(z)
%
% Computes the path constraint so that the chain integrator dynamics match
% the pendulum dynamics.
%
% INPUTS:
%   z = [x;v1;v2];
%
% OUTPUTS:
%   dz = dz/dt
%
% NOTES:
%   ddx = dv1   % definition
%   v1 = v2     % path constraint
%   dv2 = u2    % dynamics
%

% x = z(1,:); %Unused
v1 = z(2,:);
v2 = z(3,:);

c = [];
ceq = v1-v2;

end

author: MatthewPeterKelly

repo: OptimTraj


text:
function L = gt(p1,p2)
%PREAL/GT Overloaded GT (>) operator for class preal.

global useUnitsFlag

if ~(useUnitsFlag) % If physunits is disabled...
    L=gt(double(p1),double(p2)); % ... treat as double.
    return
end

p1=preal(p1);
p2=preal(p2);
tol=0.001;
if isscalar(p1)
    p1=preal(p1.value*ones(size(p2)),p1.units);
elseif isscalar(p2)
    p2=preal(p2.value*ones(size(p1)),p2.units);
elseif ndims(p1)==ndims(p2)&size(p1)==size(p2)
    % do nothing
else
    error('Array dimensions must agree')
end

L=false(size(p1));
for k=1:numel(L)
    if any(abs(p1(k).units-p2(k).units)>tol)
        error('Attempt to compare dimensionally inconsistent preals')
    end
    L(k)=gt(p1(k).value,p2(k).value);
end


text:
function [delta,err] = diffTracker( I0, I1, sig, ss )
% Fast, robust estimation of translation/scale change between two images.
%
% Approximates the translational offset between two images by assuming the
% images lie on linear manifold. Specifically, assumes that if I0 and I1
% are a pair of images related by a translation [dx dy], then (I0+I1)/2 is
% the image exactly halfway between I0 and I1 (ie I0 translated by [dx/2
% dy/2]). The above only holds for small translations and spatially smooth
% images. As such the input images typically need to be spatially smoothed
% first, the amount of necessary smoothing will increase as the size of
% translation increases (experiment for best results). The code is quite
% fast, the bottleneck is the spatial smoothing.
%
% The actual computation is performed as follows. First we generate an
% artificial translation of I0 by 1 pixel in x and y, and store the results
% in Tx and Ty. Also, if ss>1, we generate an artificial scaling Ts of I0
% by upsampling by a factor of ss. The linearity assumption tells us that:
%  I1 = I0 + (I0-Tx) * dx + (I0-Ty) * dy +  (I0-Ts) * ds
% Only dx, dy and possibly ds are unknown in the resulting overcomplete set
% of linear equations, least squares is then used. The error of the
% estimate can be used as a measure of the quality of the linear fit.
%
% This function was inspired by the beautiful work ok Yang et al.:
%   H. Yang, M. Pollefeys, G. Welch, J. Frahm, and A. Ilie. Differential
%   camera tracking through linearizing the local appearance manifold.
%   CVPR, 2007.
%
% USAGE
%  [delta,err] = diffTracker( I0, I1, [sig], [ss] )
%
% INPUTS
%  I0       - reference grayscale double image
%  I1       - translated version of I0
%  sig      - [0] amount of Gaussian spatial smoothing to apply
%  ss       - [0] scale step for artificial scaling (if >1)
%
% OUTPUTS
%  delta    - estimated dx/dy/ds
%  err      - squared error of estimate
%
% EXAMPLE - translation only
%  I = double(imread('cameraman.tif'))/255; dx=3; dy=5;
%  I0=I(1+dy:end,1+dx:end); figure(1); im(I0);
%  I1=I(1:end-dy,1:end-dx); figure(2); im(I1);
%  tic, [delta,err] = diffTracker( I0, I1, 10 ), toc
%
% EXAMPLE - translation and scale
%  I0 = double(imread('coins.png'))/255; dx=9; dy=-2; ds=1.10;
%  H1 = [eye(2)*ds -[dy; dx]; 0 0 1];
%  I1 = imtransform2(I0,H1);
%  tic, [ds,err] = diffTracker( I0, I1, 25, 1.05 ), toc
%  H2 = [eye(2)*ds(3) -[ds(2); ds(1)]; 0 0 1];
%  I2 = imtransform2(I0,H2);
%  figure(1); im(I0); figure(2); im(I1); figure(3); im(I2);
%
% See also
%
% Piotr's Image&Video Toolbox      Version 2.61
% Copyright 2010 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Lesser GPL [see external/lgpl.txt]

% get inputs
if(nargin<3 || isempty(sig)), sig=0; end
if(nargin<4 || isempty(ss)), ss=0; end

% smooth images, keep only valid region
if( sig>0 ), f=filterGauss(2*ceil(sig*2.25)+1,[],sig^2);
  I0 = conv2(conv2(I0,f','valid'),f,'valid');
  I1 = conv2(conv2(I1,f','valid'),f,'valid');
end

% I0 translated by 1 pixel both in x and y, crop I0/I1 so dims match
if(ss>1), Ts=arrayToDims(imResample(I0,ss),size(I0)); end
Ty = I0(2:end,1:end-1); Tx = I0(1:end-1,2:end);
I0 = I0(1:end-1,1:end-1); I1 = I1(1:end-1,1:end-1);

% I1 = I0 + (I0-Tx)*dx + (I0-Ty)*dy + (I0-Ts)*ds, recover delta accordingly
dI1=I1(:)-I0(:); dIy=I0(:)-Ty(:); dIx=I0(:)-Tx(:);
if(ss>1), Ts=Ts(1:end-1,1:end-1); dIs=I0(:)-Ts(:); else dIs=[]; end
delta = -[dIx dIy dIs] \ dI1;

% compute squared error (if over certain threshold may wish to discard)
if(nargout>1), err=sum((-[dIx dIy dIs]*delta - dI1).^2) / length(dI1); end

% put scale delta into units independent of ss
if(ss>1), delta(3)=ss^delta(3); end

end

author: pdollar

repo: toolbox

save_path: github-repos/MATLAB/pdollar-toolbox


text:
function x = r8mat_lt_solve ( n, a, b )

%*****************************************************************************80
%
%% R8MAT_LT_SOLVE solves a transposed lower triangular linear system.
%
%  Discussion:
%
%    Given the lower triangular matrix A, the linear system to be solved is:
%
%      A' * x = b
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 October 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of rows and columns of the matrix A.
%
%    Input, real A(N,N), the N by N lower triangular matrix.
%
%    Input, real B(N), the right hand side of the linear system.
%
%    Output, real X(N), the solution of the linear system.
%
  x(1:n) = 0.0;
%
%  Solve L'*x = b.
%
  for i = n : -1 : 1
    x(i) = ( b(i) - x(i+1:n) * a(i+1:n,i) ) / a(i,i);
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% evaluate simulated data - ICA and NMF
function separ(sep0, offset0, path_data, path_res, prename, niter, savethis, hint, sep_how)
% sep_how: string i - ica, n - nmf -> method for separation
if ~exist('hint', 'var')
    hint = 0;
end

if ~exist('sep_how', 'var')
    sep_how = 'in';
end

fprintf('Separation of components... \n')
for rr = 1: length(offset0)
    fprintf('\n%g: ',rr)
    for ll=1 : length(sep0)
        fprintf('.')
        p.namedir = [prename num2str(100*sep0(ll)) 'offset_' num2str(offset0(rr))];
        cd ([path_data p.namedir])
        for mm=1:niter

            namefile = [p.namedir '-iter_' num2str(mm)];
            load ([namefile '.mat'])
            %         ims(psf);
            %         SaveImageFULL('psf', 'pf');

            if sum(sep_how == 'i')>0 %ICA
                [icasig{mm}, A{mm}, W{mm}] = fastica (dveccr, 'numOfIC', 2, 'g', 'tanh');
                icapixICA{mm} = reshape(A{mm},32, 32, 2);
            end
            if sum(sep_how == 'n')>0 %NMF
                ncomp = 2; %number of components to be separated
                if hint
                    dvec_ind = squeeze(reshape(double(array2im(dpixc_ind)), p.nx*p.ny, 1, 2)); % vectors of resized images
%                     [out, bg(mm), bg_im]=backgroundoffset(dpixc);
                    [out, bg(mm), bg_im]=backgroundoffset(dpixc, 'no', 5, 20, 8); %empirical values...
                    dvec_bg = bg(mm)*ones(1, p.nx*p.ny);
%                     dvec_bg = p.offset*ones(1, p.nx*p.ny); %changed for offset 10...

                    blinkmatrand = rand(p.Nt, ncomp);
                    winit = [blinkmatrand,ones(p.Nt,1)];             %random weights will be assigned to firts two and bg fixed

                    hinit = [dvec_ind'; dvec_bg];       %original 'true' points + background
%                     hinit = [rand(ncomp, p.nx*p.ny); dvec_bg];
                    ncomp = ncomp+1; %background added
                    [w{mm},h{mm}, wtrace{mm},htrace{mm}]=nmf_test(double(dveccr'),ncomp+1,1,winit,hinit, [3], [3]);

                else
                    [w{mm},h{mm}]=nmf(double(dveccr'),ncomp,1);
                end
                icapixNMF{mm} = reshape(h{mm}',32,32,ncomp);
            end
            %             imstiled(icapixICA{mm});
            %             SaveImageFULL([p.namedir 'ICA_' num2str(mm)], 'p');
            %             imstiled(icapixNMF{mm});
            %             SaveImageFULL([p.namedir 'NMF_' num2str(mm)], 'p');
            close all

        end

        p.path_data = path_data;
        p.path = path_res;

        if savethis == 1
            fprintf('saving data \n');
            if ~(strcmp('p.path', 'p.path_data')) %not identical
                mkdir ([p.path p.namedir]);
                cd ([p.path p.namedir]);
            end
            save ([p.namedir '_separ'])
            writedata([],[],p,[p.namedir '_param'])
        end
    end
end

fprintf('\n')

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function besselk_test ( )

%*****************************************************************************80
%
%% BESSELK_TEST examines the besselk correlation.
%
%  Discussion:
%
%    This code is based substantially on a document by Toby Driscoll.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    25 February 2012
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Toby Driscoll,
%    Mercer's theorem and the Karhunen-Loeve expansion,
%    Oxford University Mathematical Institute,
%    http://www2.maths.ox.ac.uk/chebfun/examples/stats/pdf/MercerKarhunenLoeve.pdf
%
  rmpath ( '/usr/local/matlab/toolbox/datafeed/datafeed' )
  addpath ( '../chebfun' )

  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BESSELK_TEST:\n' );
  fprintf ( 1, '  Demonstrate Mercer''s theorem and the KL expansion\n' );
  fprintf ( 1, '  for the besselk kernel.\n' );
%
%  Set the interval.
%
  a = 0.0;
  b = 10.0;
  fprintf ( 1, '  Using interval [%g,%g]\n', a, b );
  s_num = 21;
  s_vec = linspace ( a, b, s_num );
%
%  FRED is a function from the CHEBFUN library.
%
%  It constructs a "chebop" representing the Fredholm integral operator
%  with kernel K for functions in domain [A,B].
%
  F = fred ( @besselk_correlation, domain ( [ a, b ] ) );
%
%  EIGS has been extended to be able to compute the eigenvalues Lambda
%  and eigenfunctions Psi of the Fredholm integral operator represented by F.
%
%  The "LM" switch requests that we return the eigenvalues of largest magnitude.
%
%  Each Psi is a CHEBFUN, that is, it takes a real number argument.
%
  eigen_num = 20;
  [ Psi, Lambda ] = eigs ( F, eigen_num, 'lm' );

  eigen_found = length ( Lambda );
  fprintf ( 1, '  Requested %d eigenmodes, computed %d\n', eigen_num, eigen_found );
  eigen_num = min ( eigen_num, eigen_found );
%
%  Print the eigenvalues.
%
  lambda_vec = diag ( Lambda );
  fprintf ( 1, '\n' );
  fprintf ( 1, '   I       Lambda(I)\n' );
  fprintf ( 1, '\n' );
  for i = 1 : eigen_num
    fprintf ( 1, '  %2d  %10g\n', i, lambda_vec(i) );
  end
%
%  Plot the eigenvalues.
%
  figure ( 1 )
  clf
  plot ( lambda_vec, 'Linewidth', 2 );
  hold on
  plot ( lambda_vec, 'b.', 'Markersize', 20 );
  title ( 'besselk: Mercer eigenvalues' );
  xlabel ( '<--- N --->')
  grid on
  print -dpng 'besselk_figure1.png'
%
%  Plot selected eigenfunctions.
%
  figure ( 2 )
  subplot ( 4, 1, 1 )
  plot ( Psi(:,1), 'Linewidth', 2 );
  title ( 'besselk: Mercer eigenfunction PSI(1)' )
  grid on
  subplot ( 4, 1, 2 )
  plot ( Psi(:,2), 'Linewidth', 2 );
  title ( 'besselk: Mercer eigenfunction PSI(2)' )
  grid on
  subplot ( 4, 1, 3 )
  plot ( Psi(:,3), 'Linewidth', 2 );
  title ( 'besselk: Mercer eigenfunction PSI(3)' )
  grid on
  subplot ( 4, 1, 4 )
  plot ( Psi(:,4), 'Linewidth', 2 );
  title ( 'besselk: Mercer eigenfunction PSI(4)' )
  grid on
  print -dpng 'besselk_figure2.png'
%
%  Orthonormality check.
%
  ptp = Psi' * Psi;
  error_frobenius = r8mat_is_identity ( eigen_num, ptp );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Frobenius norm of I - Psi'' * Psi = %g\n', error_frobenius );
%
%  K(S,S) should be exactly 1.
%  Because we are using a truncated representation of K, our estimate of K(S,S)
%  will be smaller than 1.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Truncated estimate of K(s,s) = 1 for S in the interval.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '        S        K(s,s) estimate\n' );
  fprintf ( 1, '\n' );
  for i = 1 : 21
    s = s_vec(i);
    ptlp = Psi(s,:) * Lambda * Psi(s,:)';
    fprintf ( 1, '  %10g  %14g\n', s, ptlp );
  end
%
%  Look at eigenvalue decay.
%
  x = diff ( log ( ( 1:eigen_num ) ) );
  y = diff ( log ( lambda_vec ) )';
  c = y ./ x;
  figure ( 3 );
  clf
  plot ( c, 'Linewidth', 2 );
  grid on
  hold on
  plot ( c, 'b.', 'Markersize', 20 );
  xlabel ( '<-- N -->' )
  title ( 'besselk: Eigenvalue decay rate' );
  print -dpng 'besselk_figure3.png'
%
%  Look at eigenvalue sum.
%
%  The trace of K(s,s) over [a,b] should be the integral of 1 over [a,b],
%  that is, b - a.
%
%  We compare the trace to the partial sums of the lambda's to see how much
%  of the variance of the process we have captured.
%
  trace_K = b - a;
  lambda_cum = cumsum ( lambda_vec ) / trace_K;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Index    Cumulative Eigenvalue sum\n' );
  fprintf ( 1, '\n' );
  for i = 1 : eigen_num
    fprintf ( 1, '  %5d  %10g\n', i, lambda_cum(i) );
  end
%
%  We decide to use no more than 10 eigenfunctions.
%
  eigen_use = min ( 10, eigen_num );
%
%  Find 400 realizations of the process by selecting, for each realization,
%  10 random parameters Z in the truncated KL expansion.
%
  Z = randn ( eigen_use, 400 );
  X = Psi(:,1:eigen_use) * ( sqrt ( Lambda(1:eigen_use,1:eigen_use) ) * Z );
%
%  Plot 40 of the realizations;
%  Plot their mean, computed from all 400.
%
  figure ( 4 )
  clf
  plot ( X(:,1:40) )
  mu = sum ( X, 2 ) / 400;
  hold on;
  plot ( mu, 'k', 'linewidth', 3 );
  title ( 'besselk: 40 Random Realizations X(t,omega), and their Mean.' )
  print -dpng 'besselk_figure4.png'
%
%  Estimate the covariance from the data.
%
  figure ( 5 )
  clf
  [ S, T ] = meshgrid ( s_vec, s_vec );
  C = cov ( X(s_vec,:)' );
  mesh ( S, T, C );
  hold on;
  D = besselk_correlation ( S, T );
  plot3 ( S, T, D, 'k.', 'markersize', 10 )
  title ( 'besselk: Covariance K(S,T) (dots), and Estimate from Realizations (mesh)' )
  print -dpng 'besselk_figure5.png'
%
%  Using just 10 functions in the expansion,
%  reduce the correlation length,
%  and examine the sum of the lambda's.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Use a fixed number of eigenfunctions = %d\n', eigen_use );
  fprintf ( 1, '  but vary the correlation length RHOBAR.\n' );
  fprintf ( 1, '  (We used RHOBAR = 1 above.)\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  The sum of the eigenvalues, divided by (B-A),\n' );
  fprintf ( 1, '  discloses the relative amount of the total variation\n' );
  fprintf ( 1, '  that is captured by the truncated expansion.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      RHOBAR      VARSUM\n' );
  fprintf ( 1, '\n' );
  rhobar = 4.0;
  for i = 1 : 10
    F = fred ( @besselk_correlation, domain ( [ a, b ] ) );
    lambda_vec = eigs ( F, eigen_use, 'lm' );
    varsum = sum ( lambda_vec(1:eigen_use) ) / ( b - a );
    fprintf ( 1, '  %10g  %10g\n', rhobar, varsum );
    rhobar = rhobar / 2.0;
  end
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BESSELK_TEST:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  rmpath ( '../chebfun' )

  return
end


text:
function evaluate_ref_models()
% Evaluate MatConvNet reference models to validate them

addpath(fullfile(fileparts(mfilename('fullpath')), '..','examples', 'imagenet')) ;

models = {...
  'resnet-50-dag', 2015, ...
  'resnet-101-dag', 2015, ...
  'resnet-152-dag', 2015, ...
  'matconvnet-alex', 2012, ...
  'matconvnet-vgg-s', 2013, ...
  'matconvnet-vgg-m', 2013, ...
  'matconvnet-vgg-f', 2013, ...
  'matconvnet-vgg-verydeep-16', 2014, ...
  'caffe-ref', 2012, ...
  'caffe-alex', 2012, ...
  'vgg-s', 2013, ...
  'vgg-m', 2013, ...
  'vgg-f', 2013, ...
  'vgg-m-128', 2013, ...
  'vgg-m-1024', 2013, ...
  'vgg-m-2048', 2013, ...
  'vgg-verydeep-19', 2014, ...
  'vgg-verydeep-16', 2014, ...
  'googlenet-dag', 2014} ;

for i = 1:2:numel(models)
  opts.dataDir = fullfile('data', 'imagenet12-s256') ;
  opts.expDir = fullfile('data','models-eval', models{i}) ;
  opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
  opts.modelPath = fullfile('data', 'models', ...
    sprintf('imagenet-%s.mat', models{i})) ;
  opts.lite = false ;
  opts.numFetchThreads = 12 ;
  opts.train.batchSize = 128 ;
  opts.train.numEpochs = 1 ;
  opts.train.gpus = [] ;
  opts.train.prefetch = true ;
  opts.train.expDir = opts.expDir ;

  resultPath = fullfile(opts.expDir, 'results.mat') ;
  if ~exist(resultPath)
    results = cnn_imagenet_evaluate(opts) ;
    save(fullfile(opts.expDir, 'results.mat'), 'results') ;
  end
end

fprintf('|%30s|%10s|%10s|%10s|%10s|\n', 'model', 'introduced', ...
        'top-1 err.', 'top-5 err.', 'images/s') ;
fprintf(strrep(sprintf('|%30s|%10s|%10s|%10s|%10s|\n', '', '', '', '', ''),' ','-')) ;

years = horzcat(models{2:2:end}) ;
[~,perm] = sort(years, 'descend') ;

for i = perm
  i = 2*(i - 1) + 1 ;
  opts.expDir = fullfile('data', 'models-eval', models{i}) ;
  resultPath = fullfile(opts.expDir, 'results.mat') ;
  load(resultPath, 'results') ;

  if isfield(results.val, 'error')
    top5 = results.val.error(2,end) ;
    top1 = results.val.error(1,end) ;
    speed = results.val.speed(end) ;
  else
    top5 = results.val.top5err(1,end) ;
    top1 = results.val.top1err(1,end) ;
    speed = results.val.num / results.val.time ;
  end

  fprintf('|%30s|%10d|%10s|%10s|%10s|\n', ...
    models{i}, ...
    models{i+1}, ...
    sprintf('%5.1f',top1*100), ...
    sprintf('%5.1f',top5*100), ...
    sprintf('%5.1f',speed)) ;
end

% (cd data/models ; md5sum *.mat | xargs  printf '| %-33s| %-40s|\n')

author: guosheng

repo: refinenet

save_path: github-repos/MATLAB/guosheng-refinenet


text:
function [feat] = batch_feature(filelist, imgset, feature, c)
%
% Copyright Aditya Khosla http://mit.edu/khosla
%
% Please cite this paper if you use this code in your publication:
%   A. Khosla, J. Xiao, A. Torralba, A. Oliva
%   Memorability of Image Regions
%   Advances in Neural Information Processing Systems (NIPS) 2012
%

if(~exist('c', 'var'))
  c = conf();
end

p = c.feature_config.(feature);
if(isfield(p, 'dictionary_size') && isfield(p, 'dictionary_file'))
	feature_file = sprintf(p.([imgset '_file']), c.cache, p.dictionary_size);
	batch_folder = [c.cache '/' imgset '_' feature '_' num2str(p.dictionary_size) '/'];
else
  feature_file = sprintf(p.([imgset '_file']), c.cache);
	batch_folder = [c.cache '/' imgset '_' feature '_' num2str(p.feature_size) '/'];
end

if(exist(feature_file, 'file'))
  load(feature_file);
  return;
end

num_batches = ceil(length(filelist)/c.batch_size);
batch_idx = arrayfun(@(x) (x-1)*c.batch_size+1:min(x*c.batch_size, length(filelist)), 1:num_batches, 'UniformOutput', false);
batch_order = randperm(num_batches);
batch_files = cell(num_batches, 1);

vprintf(c.verbosity, 0, 'Processing filelist (%s, %s): batch %d of %d\r', imgset, feature, 0, num_batches);
for b=1:num_batches
    this_batch = batch_idx{batch_order(b)};
    batch_file = [batch_folder num2str(batch_order(b)) '.mat'];
    batch_files{batch_order(b)} = batch_file;
    vprintf(c.verbosity, 0, 'Processing filelist (%s, %s): batch %d of %d\r', imgset, feature, b, num_batches);
    if(~exist(batch_file, 'file'))
        parsaveFeat(batch_file, [], []);
        poolfeat = filelist_feature('', filelist(this_batch), feature, c);
        parsaveFeat(batch_file, poolfeat, this_batch);
    end
end
vprintf(c.verbosity, 0, '\n');

if(nargout>0)
    feat = cell(num_batches, 1);
    for i=1:num_batches
        tmp = load(batch_files{i});
        feat{i} = tmp.poolfeat;
    end
    feat = cell2mat(feat);
else
    feat = {};
end

if exist('OCTAVE_VERSION','builtin')
    save(feature_file, 'feat', 'batch_files', '-v7');
else
    % -v7.3 is used for storing large files
    save(feature_file, 'feat', 'batch_files', '-v7.3');
end

author: adikhosla

repo: feature-extraction


text:
% Studies the recovery probability of rank aware order recursive
% matching pursuit with sparsity level and number of channels in joint recovery.

close all;
clear all;
clc;
rng('default');
% Create the directory for storing images
[status_code,message,message_id] = mkdir('bin');
% Signal space
N = 256;
% Number of measurements
M = 32;
% Number of signals
Ss = [1, 2, 4, 8, 16, 32];
% Sparsity levels
Ks = 2:30;
num_trials = 200;
num_ks = length(Ks);
num_ss = length(Ss);
success_with_k = zeros(num_ss, num_ks);

snr_threshold = 100;

for ns=1:num_ss
    % Current sparsity level
    S = Ss(ns);
    for nk=1:num_ks
        K = Ks(nk);
        num_successes = 0;
        for nt=1:num_trials
            % Sensing matrix
            Phi = spx.dict.simple.gaussian_dict(M, N);
            % Sparse signal generator
            gen  = spx.data.synthetic.SparseSignalGenerator(N, K, S);
            % Gaussian distributed non-zero samples
            X = gen.gaussian;
            % Measurement vectors
            Y = Phi * X;
            % Create the solver for rank aware order recursive matching pursuit
            solver = spx.pursuit.joint.RankAwareORMP(Phi, K);
            result = solver.solve(Y);
            % Solution vectors
            X_Rec = result.Z;
            % Comparison
            cs = spx.commons.SparseSignalsComparison(X, X_Rec, K);
            % Reconstruction SNR
            snr = cs.cum_signal_to_noise_ratio;
            success = snr > snr_threshold;
            num_successes = num_successes + success;
            fprintf('S: %d, K=%d, trial=%d, residual: %e, SNR: %f dB\n'...
                , S, K, nt, cs.cum_difference_norm, snr);
        end
        success_with_k(ns, nk) = num_successes / num_trials;
    end
end

save ('bin/figure_1_ra_ormp_success_with_K_S.mat');

author: indigits

repo: sparse-plex


text:
% Labels 64ths of imagae and saves to file
numImages = length(dir('C:\Users\brend_000\Documents\MATLAB\Machine Learning\Ghost Target\Images\cambride')) - 2;
for imageNum = 1:5
    imgLabel = cell(8,8);
    image = imread(['C:\Users\brend_000\Documents\MATLAB\Machine Learning\Ghost Target\Images\cambridge\img',num2str(imageNum),'.jpg']);
    image = nxel(8,image);
    for i = 1:8
        for j = 1:8
            imshow(image{i,j})
            imgLabel{i,j} = input('Label?','s');
        end
    end
    save(['Images\cambridge_labels\img',num2str(imageNum),'.mat'],'imgLabel')
end

author: zhangqianqianQQ

repo: MachineVisionAlgorithm


text:
function [ y, ierror ] = y_check_eg_civil ( y )

%*****************************************************************************80
%
%% Y_CHECK_EG_CIVIL checks an Egyptian Civil year.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input/output, integer Y, the year, which must not be 0.
%
%    Output, integer IERROR, is 0 if Y is legal, and 1 otherwise.
%
  if ( 0 < y )
    ierror = 0;
  else
    ierror = 1;
  end

  return
end


text:
function [vertices, faces, facevertexcdata, renderer] = u3d_pre_patch(ax)
%U3D_PRE_PATCH    Preprocess surface output to u3d.
%
% usage
%   [vertices, faces, facevertexcdata] = U3D_PRE_PATCH
%   [vertices, faces, facevertexcdata] = U3D_PRE_PATCH(h)
%
% optional input
%   ax = axes object handle
%
% output
%   vertices = row vectors of point positions, as row cell array
%              for multiple surfaces
%            = {1 x #surfaces}
%            = {[#vertices x 3], ... }
%   faces = for each surface triangle face, indices of its 3 vertices,
%           these indices refer to the columns of matrix vertices,
%           as row cell array for multiple surfaces
%         = {1 x #surfaces}
%         = {[#faces x 3], ... }
%   facevertexcdata = RGB color information at each vertex,
%                     as row cell array for multiple surfaces
%                   = {1 x #surfaces}
%                   = {[#vertices x 3], ... }
%
% See also fig2idtf, u3d_pre_line, u3d_pre_surface,
%          u3d_pre_quivergroup, u3d_pre_contourgroup.
%
% File:      u3d_pre_patch.m
% Based on:  u3d_pre by Sven Koerner, koerner(underline)sven(add)gmx.de
% Author:    Ioannis Filippidis, jfilippidis@gmail.com
% Date:      2012.07.16 -
% Language:  MATLAB R2012a
% Purpose:   preprocess patch children of axes for u3d export
%
% License to use and modify this code is granted freely to all interested,
% as long as the original author is referenced and attributed as such.
% The original author maintains the right to be solely associated with this work.

%todo
%   if FaceColor == 'none' draw only the edges (i.e., wireframe view)

%% input
if nargin < 1
    sh = findobj('flat', 'type', 'patch');
else
    objs = get(ax, 'Children');
    sh = findobj(objs, 'flat', 'type', 'patch');
end

if isempty(sh)
    disp('No patch objects found.');
    vertices            = [];
    faces               = [];
    facevertexcdata     = [];
    renderer = [];
    return
end

%% process each patch
N = size(sh, 1); % number of patches
vertices = cell(1, N);
faces = cell(1, N);
facevertexcdata = cell(1, N);
renderer = cell(1, N);
for i=1:N
    disp(['     Preprocessing patch No.', num2str(i) ] );
    h = sh(i, 1);

    [v, f, fvx, r] = single_patch_preprocessor(h);
    disp('Face Vertex Size of patch:')
    size(fvx)
    vertices{1, i} = v;
    faces{1, i} = f;
    facevertexcdata{1, i} = fvx;
    renderer{1, i} = r;
end

function [vertices, faces, facevertexcdata, renderer] = single_patch_preprocessor(h)
%% shading -> renderer in adobe reader
edgecolor = get(h, 'EdgeColor');
if strcmp(edgecolor, 'none')
    renderer = 'Solid';
else
    renderer = 'SolidWireframe';
end

%% get defined data-points
faces = get(h, 'Faces');
vertices = get(h, 'Vertices');
facevertexcdata = get(h, 'FaceVertexCData');

% triangulation needed ?
if size(faces, 2) > 3
    faces = delaunay_triangulate_patch_face(faces, vertices);
end

%% remove nan vertices and faces
% remove faces using at least one vertex with some nan coordinate
nan_vertices = any(isnan(vertices), 2);
nan_faces = nan_vertices(faces);
nan_faces = any(nan_faces, 2);
nan_faces = ~nan_faces;
faces = faces(nan_faces, :);

% vertices with nan are not used anymore
% just make them contain numbers
% DO NOT REMOVE them! This would destroy face indexing
vertices(isnan(vertices) ) = 0;
vertices = vertices.';

%% fix face color if needed (after faces have been removed)
facecolor = get(h, 'FaceColor');
if isempty(facevertexcdata) && ~ischar(facecolor)
    ddisp('Patch: Fixing face color')
    nfaces = size(faces, 1);
    facevertexcdata = repmat(facecolor, nfaces, 1);
end

%% CData
[~, m] = size(facevertexcdata);

% true color ?
if m == 3
    disp('FaceVertexCData is already True Color.')
    return
end

%% continue only if indexed colors need be replaced with RGB from colormap
% not indexed colors ?
if m ~= 1
    error('u3dpatch:FaceVertexCData', 'size(FaceVertexCData, 2) \notin {1, 3}')
end

ax = get(h, 'Parent');

% single row ? - fix to avoid errors later when exporting
if size(facevertexcdata, 1)
    disp('Patch: Single row FaceVerteXCData, replicating for all faces.')
    nfaces = size(faces, 1);
    facevertexcdata = repmat(facevertexcdata, nfaces, 1);
end

facevertexcdata = scaled_ind2rgb(facevertexcdata, ax);

function [realcolor] = scaled_ind2rgb(cdata, ax)
cdata = double(cdata);

cmap = colormap(ax);
nColors = size(cmap, 1);
[cmin, cmax] = caxis(ax);

idx = (cdata -cmin) / (cmax -cmin) *nColors;
idx = ceil(idx);
idx(idx < 1) = 1;
idx(idx > nColors) = nColors;

%% handle nans in idx
nanmask = isnan(idx);
idx(nanmask) = 1; %temporarily replace w/ a valid colormap index

%% realcolor and output
realcolor = cmap(idx, :);

function [f] = delaunay_triangulate_patch_face(faces, vertices)
warning('patch:faces', 'Patch faces are not triangulated.')
disp('      Using Delanay triangulation.')

% for each face
n = size(faces, 1);
f = cell(n, 1);
for i=1:n
    curface = faces(i, :);

    % clear NaN due to face with smaller number of vertices
    curface = curface(~isnan(curface) );

    cur_pntnum = size(curface, 2);

    % triangle after NaN removal ?
    if cur_pntnum == 3
        f(i, 1) = curface;
        continue
    end

    % project on polygon's plane and Delaunay triangulate
    xabs = vertices(curface, :).';
    xref = xabs(:, 1);
    xrel = bsxfun(@minus, xabs, xref);
    base = xrel(:, 2:3); % 1 is the zero vector
    orth_base = orth(base);
    A = orth_base.';
    xproj = A *xrel;
    curtrifaces = delaunay(xproj.');

    f{i, 1} = curface(curtrifaces);
end
f = cell2mat(f);


text:
function [response] = plotly(varargin)
% plotly - create a graph in your plotly account
%   [response] = plotly(x1,y1,x2,y2,..., kwargs)
%   [response] = plotly({data1, data2, ...}, kwargs)
%       x1,y1 - arrays
%       data1 - a data struct with styling information
%       kwargs - an optional argument struct
%
% See also plotlylayout, plotlystyle, signin, signup
%
% For full documentation and examples, see https://plot.ly/api
origin = 'plot';
if isstruct(varargin{end})
    structargs = varargin{end};
    f = lower(fieldnames(structargs));
    if ~any(strcmp('filename',f))
        structargs.filename = NaN;
    end
    if ~any(strcmp('fileopt',f))
        structargs.fileopt = NaN;
    end
    args = varargin(1:(end-1));
else
    structargs = struct('filename', NaN,'fileopt',NaN);
    args = varargin(1:end);
end

response = makecall(args, origin, structargs);

end

author: goGPS-Project


text:
%gs_top_to_bottom   test top_to_bottom Gauss-Seidel iteration
%   IFISS scriptfile: HCE; 28 January 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage

% Top-to-bottom Gauss-Seidel iterative solution of system Asupg x = fsupg
% starting with zero initial guess, for problem defined on n x n grid.

% For Figure 4.4 of Chapter 4:
%    generate benchmark problem with cd_testproblem (using prescribed
%    outflow for Example 3.1.1), plot residual using command
%       semilogy(stats(:,1),stats(:,2)/stats(1,2));

Q = triu(Asupg,-1);
xgs = zeros(length(fsupg),1);

nf = norm(fsupg);
r = fsupg - Asupg*xgs;
nr = norm(r);
its = 0;
stats = [its,nr];
fprintf('\n%5i %15.3e\n', its, nr);

tol = 1.d-6;

[L,U] = lu(Q);
while nr/nf > tol,
   xgs = xgs + U\(L\r);
   r = fsupg - Asupg*xgs;
   nr = norm(r);
   its = its + 1;
   stats = [stats;[its,nr]];
   fprintf('%5i %15.3e\n', its, nr);
end


text:
function varargout = parseParameters(Defaults,callerVarargin,varargin)
%   Parses parameter name-value pairs quickly. Does not handle options.
%
%   Within yourFunction(...), specify defaults in a struct: Defaults.x = 1;
%   Defaults.y = 1; Then call [x,y] = parseParameters(Defaults,varargin);
%   The user can then call yourFunction(...,'Y',2,'x',3); to change x and
%   y. See Examples section for more. This function combines brevity in
%   usage, high performance, and the convenience and clarity of parameter
%   name-value pairs. MATLAB's inputParser class is relatively slow.
%   Simpler methods are verbose and/or only handle positional arguments.
%   Many FEX parameter parsing solutions use assignin, which is convenient,
%   but also slow and unsafe.
%
%   Arguments
%   ---------
%   Defaults : struct
%       The default values for your parameters, specified as
%       Defaults.(paramName) = defaultValue. Order of declaration matters
%       when getting parsed output.
%   callerVarargin : cell array
%       Contains parameter name-value pairs. In normal usage, just pass
%       your function's varargin here.
%   isCaseSensitive : bool, optional
%       Default false. This optional positional argument allows you to
%       specify case sensitivity. Useful if you have parameter names like
%       's' and 'S'. MATLAB parameters are usually not case sensitive.
%   expandStruct : bool, optional
%       Default true. This optional positional argument by default expands
%       the output struct, enabling syntax such as [x,y,z] =
%       parseParameters(...). If you would rather use the output struct
%       itself (i.e. Results = parseParameters(...) ), set expandStruct to
%       true.
%
%   Returns
%   -------
%   varargout : cell
%       The values of the parameters, returned in the same order as the
%       Defaults struct fields were initialized. If expandStruct is false,
%       returns a struct formatted like the Defaults struct.
%
%   See Also
%   --------
%   inputParser
%
%   Notes
%   -----
%   In my tests this function is 9-20x faster than inputParser. To keep
%   your programs responsive, use inputParser for functions called less
%   than 1000 times and parseParameters for functions called less than
%   10,000 times. I recommend positional argument parsing with nargin
%   instead of name-value pairs for functions called less than 100,000
%   times. Any more and consider not using optional arguments.
%
%   Positional argument parsing methods include using exist, cell arrays,
%   and nargin. parseParameters is nearly on par with the exist method,
%   2-3x slower than the cell method, and 7-10x slower than the nargin
%   method.
%
%   I sacrificed features for performance. Users may be interested in other
%   solutions with more features. I tested the performance of several FEX
%   parameter name-value pair parsing functions. The fastest was
%   loadOptions by N. Brahms. The syntax is verbose, but it is only a tad
%   (1.2-1.5x) slower than parseParameters and allows for type checking.
%   Other fairly fast FEX solutions are getargs, parseargs, and
%   parse_pv_pairs.
%
%   Here's an extra tip. To make MATLAB's inputParser more concise, use::
%
%       >> results = struct2cell(p.Results);
%       >> [param1, param2, param3] = results{:};
%
%   Note: This documentation adheres to NumPy-style (see link below). It is
%   compatible with Sphinx using the matlabdomain and napoleon extensions.
%   https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
%
%   Examples
%   --------
%   .. highlight:: matlab
%
%   Basic usage within a function::
%
%       function foo(varargin)
%           Defaults.a = 'a';
%           Defaults.b = 'b';
%           [a,b] = parseParameters(Defaults,varargin);
%           disp(['a: ' a ', b: ' b '.']);
%       end
%       >> foo('a','A')
%       a: A, b: b.
%
%   Order of Defaults initialization matters. Case insensitive by default::
%
%       >> Defaults.x = 3.14159;
%       >> Defaults.msg = 'hello';
%       >> [x,msg] = parseParameters(Defaults,{'MsG','bye','x',1.61803})
%       x = 1.61803
%       msg = 'bye'
%
%   Using case sensitivity and returning a structure::
%
%       function foo(varargin)
%           Defaults.FOOL = 1;
%           Defaults.food = 'apple';
%           Fooey = parseParameters(Defaults,varargin,true,false);
%           disp(Fooey);
%       end
%       >> foo('food','orange','fool',0)
%       FOOL: 1
%       food: 'orange'
%
%   Notice that Fooey.FOOL was not changed. The options support using empty
%   arrays for defaults.
%
%   Copyright 2015 Jeffrey Chiou and everyone else. Feel free to copy,
%   distribute, and modify.

defaultParamNames = fieldnames(Defaults);
numInputs = length(callerVarargin);

%% Check for optional inputs and assign defaults.
% Using the nargin method for speed, sacrificing some flexibility
isCaseSensitive = false;
expandStruct = true;
if nargin > 2
    if ~isempty(varargin{1}), isCaseSensitive = varargin{1}; end;
end
if nargin > 3
    if ~isempty(varargin{2}), expandStruct = varargin{2}; end;
end

%% Check for an even number of arguments
if mod(numInputs,2)==1
    throw( MException('PARSEPARAMETERS:missingValue',...
        'A parameter seems to be missing a value.') );
end

%% Assign values. Repeated code for speed.
% Repeated code is bad for maintanability and readibility, but this
% function is optimized for speed. It runs faster if the conditionals are
% outside the loop.

if isCaseSensitive
    %% Case sensitive block.
    for i = 1:2:numInputs
        % Make sure parameter names are strings
        try
            % Counterintuitively, using find() here makes overall
            % performance faster. ~isempty() is faster than any(), and
            % access into defaultParamNames with a number is faster than
            % with a logical array.
            match = find( strcmp(callerVarargin{i},defaultParamNames), 1 );
        catch ME
            causeException = MException('PARSEPARAMETERS:nameNotString',...
                'Parameter names must be strings.');
            ME = addCause(ME,causeException);
            rethrow(ME);
        end

        % Overwrite defaults
        if ~isempty(match)
            Defaults.(defaultParamNames{match}) = callerVarargin{i+1};
        end
    end
else
    %% Case insensitive block. Nearly identical repeat of above.
    % Differences are find(...) instead of find(...,1), strcmpi() instead
    % of strcmp(), length()==1 instead of ~isempty(), and an error check.
    for i = 1:2:numInputs
        try
            match = find( strcmpi(callerVarargin{i},defaultParamNames) );
        catch ME
            causeException = MException('PARSEPARAMETERS:nameNotString',...
                'Parameter names must be strings.');
            ME = addCause(ME,causeException);
            rethrow(ME);
        end

        % Check for double default parameter names (ex. Defaults.x and
        % Defaults.X). This is not a problem with the case sensitive
        % version. In the case sensitive version, ~isempty() is just barely
        % faster than length()==1.
        if length(match)==1
            Defaults.(defaultParamNames{match}) = callerVarargin{i+1};
        else
            throw( MException('PARSEPARAMETERS:badDefaultNames',...
                ['Two default parameter names are identical, besides '...
                'case. Set case sensitivity to true in parseParameters']));
        end
    end
end % of isCaseSensitive if-else

%% Choose output format
% Speed of both options are about the same.
if expandStruct
    varargout = struct2cell(Defaults);
else
    varargout = {Defaults};
end

end % of function

author: sglvladi

repo: TrackingX

save_path: github-repos/MATLAB/sglvladi-TrackingX


text:
N = 3;
P = 0.824;
% P = [0.875	0.9583	0.9999	0.9999	0.9999	0.916667	0.9167	0.916667	0.9999	0.625	0.416667	0.833333	0.625];
duration = 1.5;
C = 60/duration;

ITR = (log2(N)+P.*log2(P)+(1-P).*log2((1-P)./(N-1)))*C;

mean(ITR)

author: PatternRecognition

repo: OpenBMI


text:
function [interpolated_values] = gsp_pwl_warp_fn(x,y,x0)

cut=1e-4;

if max(x0)>max(x)+cut
    error('GSP_PWL_WARP_FN: This function does not allow you to interpolate ousite the point x and y')
end

if min(x0)<min(x)-cut
    error('GSP_PWL_WARP_FN: This function does not allow you to interpolate ousite the point x and y')
end

sx0 = size(x0);
x0 = x0(:);

% Make sure data is sorted and monotonic
[x,x_ind]=sort(x,'ascend');
y=y(x_ind);
if ( isequal(sort(y,'ascend'),y)==0 && isequal(sort(y,'descend'),y)==0 )
    error('Data points are not monotonic');
end

% Piecewise-linear interpolation
num_pts=length(x);
num_pts_to_interpolate=length(x0);
interpolated_values=zeros(num_pts_to_interpolate,1);

for i=1:num_pts_to_interpolate
    [~,closest_ind]=min(abs(x-x0(i)));
    if (x(closest_ind)-x0(i))<(-cut) || ( abs(x(closest_ind)-x0(i))<cut && closest_ind < num_pts)
    %if sign(x(closest_ind)-x0(i))<0 || ( sign(x(closest_ind)-x0(i))==0 && closest_ind < num_pts)
        lower_ind=closest_ind;
    else
        lower_ind=closest_ind-1;
    end
    interpolated_values(i)=y(lower_ind)*(x(lower_ind+1)-x0(i))/(x(lower_ind+1)-x(lower_ind)) + y(lower_ind+1)*(x0(i)-x(lower_ind))/(x(lower_ind+1)-x(lower_ind));
end

interpolated_values = reshape(interpolated_values,sx0);

end

% Old Code:
% function [output] = gsp_pwl_warp_fn(approx_spectrum,x0)
% N=length(approx_spectrum);
% output=zeros(size(x0));
% for i=1:length(x0);
%     left_index=sum(approx_spectrum<=x0(i));
%     left_val=approx_spectrum(max(left_index,1));
%     right_val=approx_spectrum(min(left_index+1,N));
%     output(i)=left_index+(x0(i)-left_val)/(right_val-left_val);
% end
%
% end

repo: gspbox


text:
% pigs model from Lauritzen and Nilsson, 2001

seed = 0;
rand('state', seed);
randn('state', seed);

% we number nodes down and to the right
h = [1 5 9 13];
t = [2 6 10];
d = [3 7 11];
u = [4 8 12 14];

N = 14;
dag = zeros(N);

% causal arcs
for i=1:3
  dag(h(i), [t(i) h(i+1)]) = 1;
  dag(d(i), [u(i) h(i+1)]) = 1;
end
dag(h(4), u(4)) = 1;

% information arcs
fig = 2;
switch fig
 case 0,
  % no info arcs
 case 1,
   % no-forgetting policy (figure 1)
   for i=1:3
     dag(t(i), d(i:3)) = 1;
   end
 case 2,
  % reactive policy (figure 2)
  for i=1:3
    dag(t(i), d(i)) = 1;
  end
 case 7,
  % omniscient policy (figure 7: di has access to hidden state h(i-1))
  dag(t(1), d(1)) = 1;
  for i=2:3
    %dag([h(i-1) t(i-1) d(i-1)], d(i)) = 1;
    dag([h(i-1) d(i-1)], d(i)) = 1; % t(i-1) is redundant given h(i-1)
  end
end

ns = 2*ones(1,N);
ns(u) = 1;

% parameter tying
params = ones(1,N);
uparam = 1;
final_uparam = 2;
tparam = 3;
h1_param = 4;
hparam = 5;
dparams = 6:8;

params(u(1:3)) = uparam;
params(u(4)) = final_uparam;
params(t) = tparam;
params(h(1)) = h1_param;
params(h(2:end)) = hparam;
params(d) = dparams;

limid = mk_limid(dag, ns, 'chance', [h t], 'decision', d, 'utility', u, 'equiv_class', params);

% h = 1 means healthy, h = 2 means diseased
% d = 1 means don't treat, d = 2 means treat
% t = 1 means test shows healthy, t = 2 means test shows diseased

if 0
  % use random params
  limid.CPD{final_uparam} = tabular_utility_node(limid, u(4));
  limid.CPD{uparam} = tabular_utility_node(limid, u(1));
  limid.CPD{tparam} = tabular_CPD(limid, t(1));
  limid.CPD{h1_param} = tabular_CPD(limid, h(1));
  limid.CPD{hparam} = tabular_CPD(limid, h(2));
else
  limid.CPD{final_uparam} = tabular_utility_node(limid, u(4), [1000 300]);
  limid.CPD{uparam} = tabular_utility_node(limid, u(1), [0 -100]); % costs have negative utility!

  % h  P(t=1) P(t=2)
  % 1  0.9   0.1
  % 2  0.2   0.8
  limid.CPD{tparam} = tabular_CPD(limid, t(1), [0.9 0.2 0.1 0.8]);

  % P(h1)
  limid.CPD{h1_param} = tabular_CPD(limid, h(1), [0.9 0.1]);

  % hi di P(hj=1) P(hj=2),  j = i+1, i=1:3
  % 1  1  0.8     0.2
  % 2  1  0.1     0.9
  % 1  2  0.9     0.1
  % 2  2  0.5     0.5
  limid.CPD{hparam} = tabular_CPD(limid, h(2), [0.8 0.1 0.9 0.5 0.2 0.9 0.1 0.5]);
end

% Decision nodes get assigned uniform policies by default
for i=1:3
  limid.CPD{dparams(i)} = tabular_decision_node(limid, d(i));
end

fname = '/home/cs/murphyk/matlab/Misc/loopybel.txt';

engines = {};
engines{end+1} = global_joint_inf_engine(limid);
engines{end+1} = jtree_limid_inf_engine(limid);
%engines{end+1} = belprop_inf_engine(limid, 'max_iter', 1*N, 'filename', fname, 'tol', 1e-3);

exact = [1 2];
%approx = 3;
approx = [];

max_iter = 1;
order = d(end:-1:1);
%order = d(1:end);

NE = length(engines);
MEU = zeros(1, NE);
niter = zeros(1, NE);
strategy = cell(1, NE);
for e=1:NE
  [strategy{e}, MEU(e), niter(e)] = solve_limid(engines{e}, 'max_iter', max_iter, 'order',  order);
end
MEU

% check results match those in the paper (p. 22)
direct_policy = eye(2); % treat iff test is positive
never_policy = [1 0; 1 0]; % never treat
tol = 1e-0; % results in paper are reported to 0dp
for e=exact(:)'
  switch fig
   case 2, % reactive policy
    assert(approxeq(MEU(e), 727, tol));
    assert(approxeq(strategy{e}{d(1)}(:), never_policy(:)))
    assert(approxeq(strategy{e}{d(2)}(:), direct_policy(:)))
    assert(approxeq(strategy{e}{d(3)}(:), direct_policy(:)))
   case 1, assert(approxeq(MEU(e), 729, tol));
   case 7, assert(approxeq(MEU(e), 732, tol));
  end
end

for e=approx(:)'
  for i=1:3
    approxeq(strategy{exact(1)}{d(i)}, strategy{e}{d(i)})
    dispcpt(strategy{e}{d(i)})
  end
end

author: bayesnet

repo: bnt

save_path: github-repos/MATLAB/bayesnet-bnt


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   PARAMETERS Returns a data structure containing the parameters of the
%   ADEPT eCobra 600.
%
% The authors of this script are:
%   Arturo Gil Aparicio
%   Adrian Peidro Vidal
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE 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.
%
% ARTE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function robot = parameters()

robot.name= 'ADEPT_eCobra_600';

%Path where everything is stored for this robot
robot.path = 'robots/adept/eCobra_600';

robot.DH.theta= '[q(1) q(2) 0 q(4)]';
robot.DH.d='[0.342 0 q(3)+0.165 0]';
robot.DH.a='[0.325 0.275 0 0]';
robot.DH.alpha= '[0 pi 0 0]';

robot.J=[];

robot.inversekinematic_fn = 'inversekinematic_ecobra_600(robot, T)';
robot.directkinematic_fn = 'directkinematic(robot, q)';

%number of degrees of freedom
robot.DOF = 4;

%rotational: 0, translational: 1
robot.kind=['R' 'R' 'P' 'R'];

%minimum and maximum rotation angle in rad
robot.maxangle =[deg2rad(-170) deg2rad(170); %Axis 1, minimum, maximum
                deg2rad(-190) deg2rad(45); %Axis 2, minimum, maximum
                deg2rad(-29) deg2rad(256); %Axis 3
                deg2rad(-190) deg2rad(190); %Axis 4: Unlimited (400? default)
                ]; %Axis 6: Really Unlimited to (800? default)

%maximum absolute speed of each joint rad/s or m/s
robot.velmax = [deg2rad(250); %Axis 1, rad/s
                deg2rad(250); %Axis 2, rad/s
                deg2rad(250); %Axis 3, rad/s
                deg2rad(375); %Axis 4, rad/s
                ];%Axis 6, rad/s

robot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time

% end effectors maximum velocity
robot.linear_velmax = 7.6; %m/s

%base reference system
robot.T0 = eye(4);

%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION
%position, velocity and acceleration
robot=init_sim_variables(robot);
robot.path = pwd;

% GRAPHICS
robot.graphical.has_graphics=1;
robot.graphical.color = [255 102 51]./255;
%for transparency
robot.graphical.draw_transparent=0;%0.5;
%draw DH systems
robot.graphical.draw_axes=0;
%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for
%bigger robots
robot.graphical.axes_scale=1;
%adjust for a default view of the robot
robot.axis=[-0.8 0.8 -0.8 0.8 0 1];
%read graphics files
robot = read_graphics(robot);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DYNAMIC PARAMETERS
%   WARNING! These parameters do not correspond to the actual VIPER 850
%   robot. They have been introduced to demonstrate the necessity of
%   simulating the robot and should be used only for educational purposes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
robot.has_dynamics=1;

%consider friction in the computations
robot.dynamics.friction=0;

%link masses (kg)
robot.dynamics.masses=[10.0840645443765 7.99763638499999 7.82396742420414 6.79135586560867 2.69519416947469 0.582726761463460 0.0250548498725116];

%COM of each link with respect to own reference system
robot.dynamics.r_com=[  37.34e-3	 -7.59e-3	 291.45e-3;     %(rx, ry, rz) link 1
                       8.82e-3	 158.89e-3	     -116.12e-3; %(rx, ry, rz) link 2
                       45.72e-3      -60.41e-3       6.77e-3;     %(rx, ry, rz) link 3
                        0.65e-3       5.18e-3      304.45e-3;     %(rx, ry, rz) link 4
                        0        -16.20e-3        -0.43e-3;  %(rx, ry, rz) link 5
                        0        0.10e-3     102.45e-3]; %(rx, ry, rz) link 6

%Inertia matrices of each link with respect to its D-H reference system.
% Ixx	Iyy	Izz	Ixy	Iyz	Ixz, for each row
robot.dynamics.Inertia=[725041607.30e-9     742053235.46e-9   58888719.46e-9    -4612005.75e-9    -20201400.03e-9  100257432.34e-9;
                        473299566.08e-9    122717629.66e-9	   374750563.05e-9	   12544273.08e-9	  -140558617.88e-9	  -8394816.58e-9;
                        73135068.37e-9	    43626156.19e-9	   96299686.97e-9	   -34759300.78e-9	  -1593782.48e-9	 1209250.25e-9;
                        262441613.90e-9     261164434.73e-9    5256188.91e-9	  15725.91e-9	  4591746.99e-9	 471721.51e-9;
                        869212.45e-9        370702.33e-9       939398.99e-9	  4.39e-9	  -4.96e-9	 3.05e-9;
                        280731.23e-9	     284457.82e-9	   6143.16e-9	  0	   217.96e-9	 0];

%robot.motors=load_motors([5 5 5 4 4 4]);
%Speed reductor at each joint
%robot.motors.G=[300 300 300 300 300 300];

repo: ARTE


text:
%% rot2VecAngle
% Below is a demonstration of the features of the |rot2VecAngle| function

%%
clear; close all; clc;

%% Syntax
% |[theta,w]=rot2VecAngle(R);|

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

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function varargout = ohmslaw(varargin)
% OHMSLAW M-file for ohmslaw.fig
%      OHMSLAW, by itself, creates a new OHMSLAW or raises the existing
%      singleton*.
%
%      H = OHMSLAW returns the handle to a new OHMSLAW or the handle to
%      the existing singleton*.
%
%      OHMSLAW('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in OHMSLAW.M with the given input arguments.
%
%      OHMSLAW('Property','Value',...) creates a new OHMSLAW or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ohmslaw_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ohmslaw_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Copyright 2002-2003 The MathWorks, Inc.

% Edit the above text to modify the response to help ohmslaw

% Last Modified by GUIDE v2.5 28-Jun-2007 14:35:29

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ohmslaw_OpeningFcn, ...
                   'gui_OutputFcn',  @ohmslaw_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before ohmslaw is made visible.
function ohmslaw_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to ohmslaw (see VARARGIN)

% Choose default command line output for ohmslaw
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes ohmslaw wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = ohmslaw_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double

% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double

% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

img=imread('pic.jpg');
imshow(img)

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

curr=get(handles.edit1,'string');
volt=get(handles.edit2,'string');
res=get(handles.edit3,'string');

if curr=='0'
    volt=str2num(volt);
    res=str2num(res);
    current=volt/res;
    current=num2str(current);
    current=strcat(current,'  Amp');
    set(handles.text1,'string',current)
elseif volt=='0'
    curr=str2num(curr);
    res=str2num(res);
    voltage=curr*res;
    voltage=num2str(voltage);
    voltage=strcat(voltage,'  Volts');
    set(handles.text1,'string',voltage)
elseif res=='0'
    curr=str2num(curr);
    volt=str2num(volt);
    resistance=volt/curr;
    resistance=num2str(resistance);
    resistance=strcat(resistance,'  Ohms');
    set(handles.text1,'string',resistance)
end

author: Sable

repo: mcbench-benchmarks


text:
function val = get_params(pot, name)
% GET_PARAMS Accessor function for a field (dpot)
% val = get_params(pot, name)
%
% e.g., get_params(pot, 'table') or 'domain'

switch name
 case 'table', val = pot.T;
 case 'domain', val = pot.domain;
 otherwise,
  error(['invalid field name ' name]);
end


text:
function [GPUDeviceNames, GPUDeviceIdx, GPUDeviceCC] = hlp_getGPUDeviceNames(minComputeCapability)
% Return the names of all GPU devices on this machine
% This requires the Parallel Computing Toolbox
% Devices with Compute Capability less than minComputeCapability are
% ignored
% The Index of each device is returned in GPUDeviceIdx
%
% Author: Tim Mullen, SCCN/INC/UCSD 2014

if nargin<1
    minComputeCapability = 1.3; end
ws = warning('off','all');
dcount = gpuDeviceCount;
GPUDeviceNames = [];
GPUDeviceIdx   = [];
GPUDeviceCC    = [];

% save selected device
gs = gpuDevice();
for k=1:dcount
    % select the device
    if gs.Index==k
        g=gs;
    else
        g=gpuDevice(k);
    end
    % skip devices with compute capability less than minComputeCapability
    GPUDeviceCC(k) = str2double(g.ComputeCapability);
    if GPUDeviceCC(k) < minComputeCapability
        continue; end
    % get name and index of the device
    GPUDeviceNames{end+1} = g.Name;
    GPUDeviceIdx(end+1)   = g.Index;
end
% restore gpu device
gpuDevice(gs.Index);
warning(ws);

repo: REST


text:
function varargout = particleinB_E_gui(varargin)
% PARTICLEINB_E_GUI M-file for particleinB_E_gui.fig
%      PARTICLEINB_E_GUI, by itself, creates a new PARTICLEINB_E_GUI or raises the existing
%      singleton*.
%
%      H = PARTICLEINB_E_GUI returns the handle to a new PARTICLEINB_E_GUI or the handle to
%      the existing singleton*.
%
%      PARTICLEINB_E_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in PARTICLEINB_E_GUI.M with the given input arguments.
%
%      PARTICLEINB_E_GUI('Property','Value',...) creates a new PARTICLEINB_E_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before particleinB_E_gui_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to particleinB_E_gui_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help particleinB_E_gui

% Last Modified by GUIDE v2.5 17-Jun-2011 05:04:25

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @particleinB_E_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @particleinB_E_gui_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before particleinB_E_gui is made visible.
function particleinB_E_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to particleinB_E_gui (see VARARGIN)

% Choose default command line output for particleinB_E_gui
handles.output = hObject;

%close all;
%clear all;
clc;

set(handles.vx,'Value',0);
set(handles.vy,'Value',0);
set(handles.vz,'Value',0);

set(handles.x,'Value',-10);
set(handles.y,'Value',0);
set(handles.z,'Value',0);

set(handles.Bx,'Value',0);
set(handles.By,'Value',-6);
set(handles.Bz,'Value',0);
set(handles.Ex,'Value',0)
set(handles.Ey,'Value',0)
set(handles.Ez,'Value',2)

set(handles.q,'Value',1);
set(handles.m,'Value',5);

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes particleinB_E_gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = particleinB_E_gui_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject    handle to start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.stop,'String','Stop!!');
guidata(hObject, handles);

v0 = [get(handles.vx,'Value'), get(handles.vy,'Value'), get(handles.vz,'Value') ]';   %initial velocity
B = [get(handles.Bx,'Value'), get(handles.By,'Value'), get(handles.Bz,'Value') ]';                                                %magnitude of B
E = [get(handles.Ex,'Value'), get(handles.Ey,'Value'), get(handles.Ez,'Value') ]';                                                %magnitude of B
m = get(handles.m,'Value');                                                        % mass
q = get(handles.q,'Value');                                                         % charge on particle
r0 = [get(handles.x,'Value'), get(handles.y,'Value'), get(handles.z,'Value') ]';    % initial position of particle
tspan = [0 70];

%to show B's direction
[x_q,y_q] = meshgrid(-15:12:15,-15:12:15);
z_q=10*ones(size(x_q));

u_q=B(1)*ones(size(x_q));
v_q=B(2)*ones(size(x_q));
w_q=B(3)*ones(size(x_q));
quiver3(x_q,y_q,z_q,u_q,v_q,w_q);
hold all;

% TO show electric field lines
z_q=-10*ones(size(x_q));

u_q=E(1)*ones(size(x_q));
v_q=E(2)*ones(size(x_q));
w_q=E(3)*ones(size(x_q));
quiver3(x_q,y_q,z_q,u_q,v_q,w_q);

legend('B','E');

% To draw axis and all
a_a = -15:0.1:15;
z_a = zeros(size(a_a));
plot3(a_a,z_a,z_a,'k','LineWidth',2);
plot3(z_a,a_a,z_a,'k','LineWidth',2);
plot3(z_a,z_a,a_a,'k','LineWidth',2);

% To set axis limits
%xlim([-15 15]);
%ylim([-15 15]);
%zlim([-15 15])

xlabel ('x axis');
ylabel ('y axis');
zlabel ('z axis');
title ('Particle in a magnetic field');

rotate3d(handles.axes,'on');

plot3(r0(1),r0(2),r0(3),'*m','MarkerSize',9,'LineWidth',2);

y0 = [r0; v0];
f = @(t,y) [y(4:6); (q/m)*cross(y(4:6),B)+E];
[t,y] = ode23t(f,tspan,y0);

%To show animation
for n=1:length(y)
    plot3(y(n,1),y(n,2),y(n,3),'--.r');
    pause(0.00001);

    z_z = get(handles.stop,'String');
    if z_z == 'Stoped'
        break;
    end

end

guidata(hObject, handles);

% --- Executes on slider movement.
function B_Callback(hObject, eventdata, handles)
% hObject    handle to B (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function B_CreateFcn(hObject, eventdata, handles)
% hObject    handle to B (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function m_Callback(hObject, eventdata, handles)
% hObject    handle to m (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.m,'Value');
set(handles.m_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function m_CreateFcn(hObject, eventdata, handles)
% hObject    handle to m (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function q_Callback(hObject, eventdata, handles)
% hObject    handle to q (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.q,'Value');
set(handles.q_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function q_CreateFcn(hObject, eventdata, handles)
% hObject    handle to q (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on button press in clear.
function clear_Callback(hObject, eventdata, handles)
% hObject    handle to clear (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cla(handles.axes);

% --- Executes on button press in stop.
function stop_Callback(hObject, eventdata, handles)
% hObject    handle to stop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.stop,'String','Stoped');
guidata(hObject, handles);

% --- Executes on slider movement.
function x_Callback(hObject, eventdata, handles)
% hObject    handle to x (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.x,'Value');
set(handles.x_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function x_CreateFcn(hObject, eventdata, handles)
% hObject    handle to x (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function y_Callback(hObject, eventdata, handles)
% hObject    handle to y (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.y,'Value');
set(handles.y_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function y_CreateFcn(hObject, eventdata, handles)
% hObject    handle to y (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function z_Callback(hObject, eventdata, handles)
% hObject    handle to z (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.z,'Value');
set(handles.z_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function z_CreateFcn(hObject, eventdata, handles)
% hObject    handle to z (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function vx_Callback(hObject, eventdata, handles)
% hObject    handle to vx (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.vx,'Value');
set(handles.vx_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function vx_CreateFcn(hObject, eventdata, handles)
% hObject    handle to vx (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function vy_Callback(hObject, eventdata, handles)
% hObject    handle to vy (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.vy,'Value');
set(handles.vy_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function vy_CreateFcn(hObject, eventdata, handles)
% hObject    handle to vy (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function vz_Callback(hObject, eventdata, handles)
% hObject    handle to vz (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.vz,'Value');
set(handles.vz_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function vz_CreateFcn(hObject, eventdata, handles)
% hObject    handle to vz (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function E_Callback(hObject, eventdata, handles)
% hObject    handle to E (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

% --- Executes during object creation, after setting all properties.
function E_CreateFcn(hObject, eventdata, handles)
% hObject    handle to E (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Ex_Callback(hObject, eventdata, handles)
% hObject    handle to Ex (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Ex,'Value');
set(handles.Ex_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Ex_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Ex (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Ey_Callback(hObject, eventdata, handles)
% hObject    handle to Ey (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Ey,'Value');
set(handles.Ey_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Ey_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Ey (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Ez_Callback(hObject, eventdata, handles)
% hObject    handle to Ez (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Ez,'Value');
set(handles.Ez_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Ez_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Ez (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Bx_Callback(hObject, eventdata, handles)
% hObject    handle to Bx (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Bx,'Value');
set(handles.Bx_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Bx_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Bx (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function By_Callback(hObject, eventdata, handles)
% hObject    handle to By (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.By,'Value');
set(handles.By_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function By_CreateFcn(hObject, eventdata, handles)
% hObject    handle to By (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% --- Executes on slider movement.
function Bz_Callback(hObject, eventdata, handles)
% hObject    handle to Bz (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
a = get (handles.Bz,'Value');
set(handles.Bz_text,'String',num2str(a));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Bz_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Bz (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end