text:
function varargout = montage2( IS, prm )
% Used to display collections of images and videos.
%
% Improved version of montage, with more control over display.
% NOTE: Can convert between MxNxT and MxNx3xT image stack via:
%   I = repmat( I, [1,1,1,3] ); I = permute(I, [1,2,4,3] );
%
% USAGE
%  varargout = montage2( IS, [prm] )
%
% INPUTS
%  IS           - MxNxTxR or MxNxCxTxR, where C==1 or C==3, and R may be 1
%                 or cell vector of MxNxT or MxNxCxT matrices
%  prm
%   .showLines  - [1] whether to show lines separating the various frames
%   .extraInfo  - [0] if 1 then a colorbar is shown as well as impixelinfo
%   .cLim       - [] cLim = [clow chigh] optional scaling of data
%   .mm         - [] #images/col per montage
%   .nn         - [] #images/row per montage
%   .labels     - [] cell array of labels (strings) (T if R==1 else R)
%   .perRow     - [0] only if R>1 and not cell, alternative displays method
%   .hasChn     - [0] if true assumes IS is MxNxCxTxR else MxNxTxR
%   .padAmt     - [0] only if perRow, amount to pad when in row mode
%   .padEl      - [] pad element, defaults to min value in IS
%
% OUTPUTS
%  h           - image handle
%  m           - #images/col
%  nn          - #images/row
%
% EXAMPLE - [3D] show a montage of images
%  load( 'images.mat' ); clf; montage2( images );
%
% EXAMPLE - [3D] show a montage of images with labels
%  load( 'images.mat' );
%  for i=1:50; labels{i}=['I-' int2str2(i,2)]; end
%  prm = struct('extraInfo',1,'perRow',0,'labels',{labels});
%  clf; montage2( images(:,:,1:50), prm );
%
% EXAMPLE - [3D] show a montage of images with color boundaries
%  load( 'images.mat' );
%  I3 = repmat(permute(images,[1 2 4 3]),[1,1,3,1]); % add color chnls
%  prm = struct('padAmt',4,'padEl',[50 180 50],'hasChn',1,'showLines',0);
%  clf; montage2( I3(:,:,:,1:48), prm )
%
% EXAMPLE - [4D] show a montage of several groups of images
%  for i=1:25; labels{i}=['V-' int2str2(i,2)]; end
%  prm = struct('labels',{labels});
%  load( 'images.mat' ); clf; montage2( videos(:,:,:,1:25), prm );
%
% EXAMPLE - [4D] show using 'row' format
%  load( 'images.mat' );
%  prm = struct('perRow',1, 'padAmt',6, 'padEl',255 );
%  figure(1); clf; montage2( videos(:,:,:,1:10), prm );
%
% See also MONTAGE, PLAYMOVIE, FILMSTRIP
%
% Piotr's Computer Vision Matlab Toolbox      Version 2.0
% Copyright 2014 Piotr Dollar.  [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]

if( nargin<2 ); prm=struct(); end
varargout = cell(1,nargout);

%%% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[],...
  'labels',[], 'perRow',false, 'padAmt',0, 'padEl',[], 'hasChn',false };
prm = getPrmDflt( prm, dfs );
extraInfo=prm.extraInfo; labels=prm.labels;  perRow=prm.perRow;
hasChn=prm.hasChn;

%%% If IS is not a cell convert to MxNxCxTxR array
if( iscell(IS) && numel(IS)==1 ); IS=IS{1}; end;
if( ~iscell(IS) && ~ismatrix(IS) )
  siz=size(IS);
  if( ~hasChn );
    IS=reshape(IS,[siz(1:2),1,siz(3:end)]);
    prm.hasChn = true;
  end;
  if(ndims(IS)>5); error('montage2: input too large'); end;
end

if( ~iscell(IS) && size(IS,5)==1 ) %%% special case call subMontage once
  [varargout{:}] = subMontage(IS,prm);
  title(inputname(1));

elseif( perRow ) %%% display each montage in row format
  if(iscell(IS)); error('montage2: IS cannot be a cell if perRow'); end;
  siz = size(IS);
  IS=reshape(permute(IS,[1 2 4 3 5]),siz(1),[],siz(3),siz(5));
  if( nargout ); varargout{1}=IS; end
  prm.perRow = false;  prm.hasChn=true;
  [varargout{2:end}] = subMontage( IS, prm );
  title(inputname(1));

else %%% display each montage using subMontage

  % convert to cell array
  if( iscell(IS) )
    nMontages = numel(IS);
  else
    nMontages = size(IS,5);
    IS = squeeze(mat2cell2( IS, [1 1 1 1 nMontages] ));
  end

  % draw each montage
  clf;
  nn = ceil( sqrt(nMontages) ); mm = ceil(nMontages/nn);
  for i=1:nMontages
    subplot(mm,nn,i);
    prmSub=prm;  prmSub.extraInfo=0;  prmSub.labels=[];
    if( ~isempty(IS{i}) )
      subMontage( IS{i}, prmSub );
    else
      set(gca,'XTick',[]); set(gca,'YTick',[]);
    end
    if(~isempty(labels)); title(labels{i}); end
  end
  if( extraInfo ); impixelinfo; end;
end

function varargout = subMontage( IS, prm )
% this function is a generalized version of Matlab's montage.m

% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[], ...
  'labels',[], 'perRow',false, 'hasChn',false, 'padAmt',0, 'padEl',[] };
prm = getPrmDflt( prm, dfs );
showLines=prm.showLines;   extraInfo=prm.extraInfo;  cLim=prm.cLim;
mm=prm.mm; nn=prm.nn;  labels=prm.labels;  hasChn=prm.hasChn;
padAmt=prm.padAmt;  padEl=prm.padEl;
if( prm.perRow ); mm=1; end;

% get/test image format info and parameters
if( hasChn )
  if( ndims(IS)>4 || ~any(size(IS,3)==[1 3]) )
    error('montage2: unsupported dimension of IS'); end
else
  if( ndims(IS)>3 );
    error('montage2: unsupported dimension of IS'); end
  IS = permute(IS, [1 2 4 3] );
end
siz = size(IS);  nCh=size(IS,3);  nIm = size(IS,4);  sizPad=siz+padAmt;
if( ~isempty(labels) && nIm~=length(labels) )
  error('montage2: incorrect number of labels');
end

% set up the padEl correctly (must have same type / nCh as IS)
if(isempty(padEl))
  if(isempty(cLim)); padEl=min(IS(:)); else padEl=cLim(1); end; end
if(length(padEl)==1); padEl=repmat(padEl,[1 nCh]); end;
if(length(padEl)~=nCh); error( 'invalid padEl' ); end;
padEl = feval( class(IS), padEl );
padEl = reshape( padEl, 1, 1, [] );
padAmt = floor(padAmt/2 + .5)*2;

% get layout of images (mm=#images/row, nn=#images/col)
if( isempty(mm) || isempty(nn))
  if( isempty(mm) && isempty(nn))
    nn = min( ceil(sqrt(sizPad(1)*nIm/sizPad(2))), nIm );
    mm = ceil( nIm/nn );
  elseif( isempty(mm) )
    nn = min( nn, nIm );
    mm = ceil(nIm/nn);
  else
    mm = min( mm, nIm );
    nn = ceil(nIm/mm);
  end
  % often can shrink dimension further
  while((mm-1)*nn>=nIm); mm=mm-1; end;
  while((nn-1)*mm>=nIm); nn=nn-1; end;
end

% Calculate I (M*mm x N*nn size image)
I = repmat(padEl, [mm*sizPad(1), nn*sizPad(2), 1]);
rows = 1:siz(1); cols = 1:siz(2);
for k=1:nIm
  rowsK = rows + floor((k-1)/nn)*sizPad(1)+padAmt/2;
  colsK = cols + mod(k-1,nn)*sizPad(2)+padAmt/2;
  I(rowsK,colsK,:) = IS(:,:,:,k);
end

% display I
if( ~isempty(cLim)); h=imagesc(I,cLim);  else  h=imagesc(I);  end
colormap(gray);  axis('image');
if( extraInfo )
  colorbar; impixelinfo;
else
  set(gca,'Visible','off')
end

% draw lines separating frames
if( showLines )
  montageWd = nn * sizPad(2) + .5;
  montageHt = mm * sizPad(1) + .5;
  for i=1:mm-1
    ht = i*sizPad(1) +.5; line([.5,montageWd],[ht,ht]);
  end
  for i=1:nn-1
    wd = i*sizPad(2) +.5; line([wd,wd],[.5,montageHt]);
  end
end

% plot text labels
textalign = { 'VerticalAlignment','bottom','HorizontalAlignment','left'};
if( ~isempty(labels) )
  count=1;
  for i=1:mm;
    for j=1:nn
      if( count<=nIm )
        rStr = i*sizPad(1)-padAmt/2;
        cStr =(j-1+.1)*sizPad(2)+padAmt/2;
        text(cStr,rStr,labels{count},'color','r',textalign{:});
        count = count+1;
      end
    end
  end
end

% cross out unused frames
[nns,mms] = ind2sub( [nn,mm], nIm+1 );
for i=mms-1:mm-1
  for j=nns-1:nn-1,
    rStr = i*sizPad(1)+.5+padAmt/2; rs = [rStr,rStr+siz(1)];
    cStr = j*sizPad(2)+.5+padAmt/2; cs = [cStr,cStr+siz(2)];
    line( cs, rs );  line( fliplr(cs), rs );
  end
end

% optional output
if( nargout>0 ); varargout={h,mm,nn}; end

author: pdollar

repo: toolbox

save_path: github-repos/MATLAB/pdollar-toolbox


text:
function ray = createRay(varargin)
%CREATERAY Create a ray (half-line), from various inputs
%
%   RAY = createRay(POINT, ANGLE)
%   POINT is a N*2 array giving starting point of the ray, and ANGLE is the
%   orientation of the ray.
%
%   RAY = createRay(X0, Y0, ANGLE)
%   Specify ray origin with 2 input arguments.
%
%   RAY = createRay(P1, P2)
%   Create a ray starting from point P1 and going in the direction of point
%   P2.
%
%   Ray is represented in a parametric form: [x0 y0 dx dy]
%   x = x0 + t*dx
%   y = y0 + t*dy;
%   for all t>0
%
%   Example
%   origin  = [3 4];
%   theta   = pi/6;
%   ray = createRay(origin, theta);
%   figure(1); clf; hold on;
%   axis([0 10 0 10]);
%   drawRay(ray);
%
%   See also:
%   rays2d, createLine, points2d
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2007-10-18
% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.

if length(varargin)==2
    p0 = varargin{1};
    arg = varargin{2};
    if size(arg, 2)==1
        % second input is the ray angle
        ray = [p0 cos(arg) sin(arg)];
    else
        % second input is another point
        ray = [p0 arg-p0];
    end

elseif length(varargin)==3
    x = varargin{1};
    y = varargin{2};
    theta = varargin{3};
    ray = [x y cos(theta) sin(theta)];

else
    error('Wrong number of arguments in ''createRay'' ');
end

author: rpng

repo: lips

save_path: github-repos/MATLAB/rpng-lips


text:
#!/usr/bin/env octave
%% Machine Learning Online Class
%  Exercise 5 | Regularized Linear Regression and Bias-Variance
%
%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the
%  exercise. You will need to complete the following functions:
%
%     linearRegCostFunction.m
%     learningCurve.m
%     validationCurve.m
%
%  For this exercise, you will not need to change any code in this file,
%  or any other files other than those mentioned above.
%

%% Initialization
clear ; close all; clc

%% =========== Part 1: Loading and Visualizing Data =============
%  We start the exercise by first loading and visualizing the dataset.
%  The following code will load the dataset into your environment and plot
%  the data.
%

% Load Training Data
fprintf('Loading and Visualizing Data ...\n')

% Load from ex5data1:
% You will have X, y, Xval, yval, Xtest, ytest in your environment
load ('ex5data1.mat');

% m = Number of examples
m = size(X, 1);

% Plot training data
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 2: Regularized Linear Regression Cost =============
%  You should now implement the cost function for regularized linear
%  regression.
%

theta = [1 ; 1];
J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);

fprintf(['Cost at theta = [1 ; 1]: %f '...
         '\n(this value should be about 303.993192)\n'], J);

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 3: Regularized Linear Regression Gradient =============
%  You should now implement the gradient for regularized linear
%  regression.
%

theta = [1 ; 1];
[J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);

fprintf(['Gradient at theta = [1 ; 1]:  [%f; %f] '...
         '\n(this value should be about [-15.303016; 598.250744])\n'], ...
         grad(1), grad(2));

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 4: Train Linear Regression =============
%  Once you have implemented the cost and gradient correctly, the
%  trainLinearReg function will use your cost function to train
%  regularized linear regression.
%
%  Write Up Note: The data is non-linear, so this will not give a great
%                 fit.
%

%  Train linear regression with lambda = 0
lambda = 0;
[theta] = trainLinearReg([ones(m, 1) X], y, lambda);

%  Plot fit over the data
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');
hold on;
plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)
hold off;

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 5: Learning Curve for Linear Regression =============
%  Next, you should implement the learningCurve function.
%
%  Write Up Note: Since the model is underfitting the data, we expect to
%                 see a graph with "high bias" -- slide 8 in ML-advice.pdf
%

lambda = 0;
[error_train, error_val] = ...
    learningCurve([ones(m, 1) X], y, ...
                  [ones(size(Xval, 1), 1) Xval], yval, ...
                  lambda);

plot(1:m, error_train, 1:m, error_val);
title('Learning curve for linear regression')
legend('Train', 'Cross Validation')
xlabel('Number of training examples')
ylabel('Error')
axis([0 13 0 150])

fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
for i = 1:m
    fprintf('  \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
end

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 6: Feature Mapping for Polynomial Regression =============
%  One solution to this is to use polynomial regression. You should now
%  complete polyFeatures to map each example into its powers
%

p = 8;

% Map X onto Polynomial Features and Normalize
X_poly = polyFeatures(X, p);
[X_poly, mu, sigma] = featureNormalize(X_poly);  % Normalize
X_poly = [ones(m, 1), X_poly];                   % Add Ones

% Map X_poly_test and normalize (using mu and sigma)
X_poly_test = polyFeatures(Xtest, p);
X_poly_test = bsxfun(@minus, X_poly_test, mu);
X_poly_test = bsxfun(@rdivide, X_poly_test, sigma);
X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test];         % Add Ones

% Map X_poly_val and normalize (using mu and sigma)
X_poly_val = polyFeatures(Xval, p);
X_poly_val = bsxfun(@minus, X_poly_val, mu);
X_poly_val = bsxfun(@rdivide, X_poly_val, sigma);
X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val];           % Add Ones

fprintf('Normalized Training Example 1:\n');
fprintf('  %f  \n', X_poly(1, :));

fprintf('\nProgram paused. Press enter to continue.\n');
pause;

%% =========== Part 7: Learning Curve for Polynomial Regression =============
%  Now, you will get to experiment with polynomial regression with multiple
%  values of lambda. The code below runs polynomial regression with
%  lambda = 0. You should try running the code with different values of
%  lambda to see how the fit and learning curve change.
%

lambda = 0;
[theta] = trainLinearReg(X_poly, y, lambda);

% Plot training data and fit
figure(1);
plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
plotFit(min(X), max(X), mu, sigma, theta, p);
xlabel('Change in water level (x)');
ylabel('Water flowing out of the dam (y)');
title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));

figure(2);
[error_train, error_val] = ...
    learningCurve(X_poly, y, X_poly_val, yval, lambda);
% Should we use logarithmix scale there?
plot(1:m, error_train, 1:m, error_val);

title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
xlabel('Number of training examples')
ylabel('Error')
axis([0 13 0 100])
legend('Train', 'Cross Validation')

fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
for i = 1:m
    fprintf('  \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
end

fprintf('Program paused. Press enter to continue.\n');
pause;

%% =========== Part 8: Validation for Selecting Lambda =============
%  You will now implement validationCurve to test various values of
%  lambda on a validation set. You will then use this to select the
%  "best" lambda value.
%

[lambda_vec, error_train, error_val] = ...
    validationCurve(X_poly, y, X_poly_val, yval);

close all;
plot(lambda_vec, error_train, lambda_vec, error_val);
legend('Train', 'Cross Validation');
xlabel('lambda');
ylabel('Error');

fprintf('lambda\t\tTrain Error\tValidation Error\n');
for i = 1:length(lambda_vec)
	fprintf(' %f\t%f\t%f\n', ...
            lambda_vec(i), error_train(i), error_val(i));
end

fprintf('Program paused. Press enter to continue.\n');
pause;

author: SaveTheRbtz

repo: ml-class


text:
function X= readeAviFile(name)
xyloObj = mmreader(name);

nFrames = xyloObj.NumberOfFrames;
vidHeight = xyloObj.Height;
vidWidth = xyloObj.Width;

% Preallocate movie structure.
X= zeros(vidHeight,vidWidth,nFrames);

% Read one frame at a time.
for k = 1 : nFrames
    X(:,:,k)= rgb2gray( read(xyloObj, k));
end

% Size a figure based on the video's width and height.

author: thomaskuestner


text:
function centroids = kMeansInitCentroids(X, K)
%KMEANSINITCENTROIDS This function initializes K centroids that are to be
%used in K-Means on the dataset X
%   centroids = KMEANSINITCENTROIDS(X, K) returns K initial centroids to be
%   used with the K-Means on the dataset X
%

% You should return this values correctly
centroids = zeros(K, size(X, 2));

% ====================== YOUR CODE HERE ======================
% Instructions: You should set centroids to randomly chosen examples from
%               the dataset X
%
% Initialize the centroids to be random examples
% Randomly reorder the indices of examples
randidx = randperm(size(X, 1));
% Take the first K examples as centroids
centroids = X(randidx(1:K), :);

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

end

author: anirudhjayaraman

repo: Machine-Learning


text:
function [Flag,outputCommand]=dialog_setOutput_To_CommandLine()
% Dialog box used by the user to change the logical state of the output of
% robot's touch-pneumatic flange

% Copyright: Mohammad SAFEEA, 2018-July-20

global daHandleof_dialog_set_output_to_command_line;
global dialog_set_output_to_command_line_button_hit;
global dialog_set_output_to_command_line_flag;
global dialog_set_output_to_command_line_outputStateWrite;
global dialog_set_output_to_command_line_outputChekcboxHandles;

dialog_set_output_to_command_line_button_hit=0;
dialog_set_output_to_command_line_flag=false;
dialog_set_output_to_command_line_outputStateWrite={};
dialog_set_output_to_command_line_outputChekcboxHandles=[];

%% Interface container
dialog_width=400;
dialog_height=300;
dialog_x0=10;
dialog_y0=100;
daCaption='Set outputs val';
jointAnglesDialogHandle=figure('Name',daCaption,'rend','painters','pos',[dialog_x0 dialog_y0 dialog_width dialog_height]);
daHandleof_dialog_set_output_to_command_line=jointAnglesDialogHandle;
pause(0.5);
%% Button dimension
enter_buttons_separator=40;
button_width=100;
button_height=50;
%% Add ok button
fcn=@callback_dialog_set_output_to_command_line_okBtn;
btn_ok_h= uicontrol(jointAnglesDialogHandle,'Style', 'pushbutton', 'String', 'OK',...
                'Units','pixels',...
                'Callback', fcn);
x0=round((dialog_width-enter_buttons_separator-button_width*2)/2);
xtemp=x0;
y0=enter_buttons_separator;
ytemp=y0;
btn_ok_h.HorizontalAlignment='center';
btn_ok_h.Position=[x0 y0 button_width button_height];
%% Add cancel button
fcn=@callback_dialog_set_output_to_command_line_cancelBtn;
btn_cancel_h= uicontrol(jointAnglesDialogHandle,'Style', 'pushbutton', 'String', 'Cancel',...
                'Units','pixels',...
                'Callback', fcn);
x0=xtemp+enter_buttons_separator+button_width;
y0=ytemp;
btn_cancel_h.HorizontalAlignment='center';
btn_cancel_h.Position=[x0 y0 button_width button_height];
%% Dimensions of lables and sliders,
labelsNum=4;
enter_controls_horizontal_margin=10;
x0=enter_controls_horizontal_margin;
y0=ytemp+button_height;

labels_width=170;
enter_labels_vertical_margin=20;
labels_height=(dialog_height-enter_labels_vertical_margin*(labelsNum+1)-y0)/labelsNum;

x0=(dialog_width-labels_width/2)/2;
%% Add lables and sliders,
h=daHandleof_dialog_set_output_to_command_line;
labels_text_array={'OuputPin_11','OuputPin_12','OuputPin_1','OuputPin_2'};

for i=1:4
    labels_text=labels_text_array{i};
    lbl_handle= uicontrol('Style','checkbox','String',labels_text, ...
                       'Value',0, 'Units','pixels');
    x_labels_0=x0;
    y_labels_0=y0+(enter_labels_vertical_margin)*i+(labels_height)*(i-1);
    lbl_handle.HorizontalAlignment='center';
    lbl_handle.Position=[x_labels_0 y_labels_0 labels_width labels_height];
    dialog_set_output_to_command_line_outputChekcboxHandles{i}=lbl_handle;
end

while(dialog_set_output_to_command_line_button_hit==0)
    figure(daHandleof_dialog_set_output_to_command_line)
    pause(0.1);
end
outputCommand=dialog_set_output_to_command_line_outputStateWrite;
Flag=dialog_set_output_to_command_line_flag;

clear daHandleof_dialog_set_output_to_command_line;
clear dialog_set_output_to_command_line_button_hit;
clear dialog_set_output_to_command_line_flag;
clear dialog_set_output_to_command_line_outputStateWrite;
end

function callback_dialog_set_output_to_command_line_okBtn(PushButton, EventData)
    global daHandleof_dialog_set_output_to_command_line;
    global dialog_set_output_to_command_line_button_hit;
    global dialog_set_output_to_command_line_flag;
    global dialog_set_output_to_command_line_outputStateWrite;
    global dialog_set_output_to_command_line_outputChekcboxHandles;

    y=[];
    labels_text_array={'OuputPin_11','OuputPin_12','OuputPin_1','OuputPin_2'};
    for i=1:4
        h=dialog_set_output_to_command_line_outputChekcboxHandles{i};
        v=get(h,'Value');
        if v==1
            val='ON';
        else
            val='OFF';
        end
        y{i}=[labels_text_array{i},'_',val];
    end
    close(daHandleof_dialog_set_output_to_command_line);
    dialog_set_output_to_command_line_flag=true;
    dialog_set_output_to_command_line_outputStateWrite=y;
    dialog_set_output_to_command_line_button_hit=1;
end

function callback_dialog_set_output_to_command_line_cancelBtn(PushButton, EventData)
    global daHandleof_dialog_set_output_to_command_line;
    global dialog_set_output_to_command_line_button_hit;
    global dialog_set_output_to_command_line_flag;
    global dialog_set_output_to_command_line_outputStateWrite;

    close(daHandleof_dialog_set_output_to_command_line);
    dialog_set_output_to_command_line_flag=false;
    dialog_set_output_to_command_line_outputStateWrite=[];
    dialog_set_output_to_command_line_button_hit=1;
end

repo: KST-Kuka-Sunrise-Toolbox


text:
function [Jul1,Jul2]=GPS2TT(Jul1,Jul2)
%GPS2TT  Convert from the timescale used by the Global Positioning System
%           (GPS)  given as a two-part Julian date to terrestrial time
%           (TT), represented as a two-part Julian date.
%
%INPUTS:    Jul1, Jul2  Two parts of a Julian date given in GPS time. The
%                       units of the date are days. The full date is the
%                       sum of both terms. The date is broken into two
%                       parts to provide more bits of precision. It does
%                       not matter how the date is split.
%
%OUTPUTS:   Jul1, Jul2  The time as a Julian date in TT.
%
%This function just calls GPS2TAI and TAI2TT.
%
%Many temporal coordinate systems standards are compared in [1].
%
%REFERENCES:
%[1] D. F. Crouse, "An Overview of Major Terrestrial, Celestial, and
%    Temporal Coordinate Systems for Target Tracking," Formal Report, Naval
%    Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016, 173
%    pages.
%
%October 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

[Jul1,Jul2]=GPS2TAI(Jul1,Jul2);
[Jul1,Jul2]=TAI2TT(Jul1,Jul2);
end

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

author: USNavalResearchLaboratory

repo: TrackerComponentLibrary


text:
clc; close all;
% x = gallery('uniformdata',[10,1],0);
% y = gallery('uniformdata',[10,1],1);
% DT = delaunayTriangulation(x,y);
%
% k = convexHull(DT)
% figure
% plot(DT.Points(:,1),DT.Points(:,2), '.','markersize',10);
% hold on
% plot(DT.Points(k,1),DT.Points(k,2),'r')
% hold off

figure;
x = dTreePtsL(1, :)';
y = dTreePtsL(2, :)';
% plot(x,y,'.')
DT = delaunayTriangulation([x y] );
triplot(DT);
axis equal;
% xlim([-0.2 1.2])
% ylim([-0.2 1.2])

% k = boundary(x,y);
% hold on;
% plot(x(k),y(k));

author: DrGabor

repo: LiDAR

save_path: github-repos/MATLAB/DrGabor-LiDAR


text:
function trans = lineSymmetry(line)
%LINESYMMETRY create line symmetry as 2D affine transform
%
%   TRANS = lineSymmetry(LINE);
%   where line is given as [x0 y0 dx dy], return the affine tansform
%   corresponding to the desired line symmetry
%
%
%   See also:
%   lines2d, transforms2d, transformPoint, translation, homothecy
%
%   ---------
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 19/01/2005.
%

% deprecation warning
warning('geom2d:deprecated', ...
    '''lineSymmetry'' is deprecated, use ''createLineReflection'' instead');

% call current implementation
trans = createLineReflection(line);


text:
function level=isodata(I)
%   ISODATA Compute global image threshold using iterative isodata method.
%   LEVEL = ISODATA(I) computes a global threshold (LEVEL) that can be
%   used to convert an intensity image to a binary image with IM2BW. LEVEL
%   is a normalized intensity value that lies in the range [0, 1].
%   This iterative technique for choosing a threshold was developed by Ridler and Calvard .
%   The histogram is initially segmented into two parts using a starting threshold value such as 0 = 2B-1,
%   half the maximum dynamic range.
%   The sample mean (mf,0) of the gray values associated with the foreground pixels and the sample mean (mb,0)
%   of the gray values associated with the background pixels are computed. A new threshold value 1 is now computed
%   as the average of these two sample means. The process is repeated, based upon the new threshold,
%   until the threshold value does not change any more.

%
%   Class Support
%   -------------
%   The input image I can be of class uint8, uint16, or double and it
%   must be nonsparse.  LEVEL is a double scalar.
%
%   Example
%   -------
%       I = imread('blood1.tif');
%       level = graythresh(I);
%       BW = im2bw(I,level);
%       imshow(BW)
%
%   See also IM2BW.
%
% Reference :T.W. Ridler, S. Calvard, Picture thresholding using an iterative selection method,
%            IEEE Trans. System, Man and Cybernetics, SMC-8 (1978) 630-632.

% Convert all N-D arrays into a single column.  Convert to uint8 for
% fastest histogram computation.
I = im2uint8(I(:));

% STEP 1: Compute mean intensity of image from histogram, set T=mean(I)
[counts,N]=imhist(I);
i=1;
mu=cumsum(counts);
T(i)=(sum(N.*counts))/mu(end);
T(i)=round(T(i));

% STEP 2: compute Mean above T (MAT) and Mean below T (MBT) using T from
% step 1
mu2=cumsum(counts(1:T(i)));
MBT=sum(N(1:T(i)).*counts(1:T(i)))/mu2(end);

mu3=cumsum(counts(T(i):end));
MAT=sum(N(T(i):end).*counts(T(i):end))/mu3(end);
i=i+1;
% new T = (MAT+MBT)/2
T(i)=round((MAT+MBT)/2);

% STEP 3 to n: repeat step 2 if T(i)~=T(i-1)
while abs(T(i)-T(i-1))>=1
    mu2=cumsum(counts(1:T(i)));
    MBT=sum(N(1:T(i)).*counts(1:T(i)))/mu2(end);

    mu3=cumsum(counts(T(i):end));
    MAT=sum(N(T(i):end).*counts(T(i):end))/mu3(end);

    i=i+1;
    T(i)=round((MAT+MBT)/2);
    Threshold=T(i);
end

 % Normalize the threshold to the range [i, 1].
level = (Threshold - 1) / (N(end) - 1);

author: Sable

repo: mcbench-benchmarks


text:
function xyz = cube2ball(XYZ)
%
% transforms cubochoric coordinates of quaternions into homochoric ones
% maps from cube (edge pi^(2/3) onto ball (radius (3*pi/4)^(1/3))
%
% Input
%  XYZ - cubochoric coordinates (X,Y,Z) of N points of the cube
%
% Output
%  xyz - homochoric coordinates (x,y,z) of N points of the ball

% the actual mapping is only defined on one pyramid Pz (z>=abs(x),z>=abs(y))
% map other points by:
%  1. transform coordinates, so that we get a point of Pz
%  2. map the point
%  3. apply the inverse transformation

% define permutaions (and inverse ones) for each region (pyramid)
p = regionId(XYZ);
permRegion  = [2 3 1;3 2 1;1 3 2;3 1 2;1 2 3;2 1 3];
ipermRegion = [3 1 2;3 2 1;1 3 2;2 3 1;1 2 3;2 1 3];

%  permXYZ contains for each point its permutation
% ipermXYZ contains for each point its inverse permutation

permXYZ  =  permRegion(p,:);
ipermXYZ = ipermRegion(p,:);

% apply the permutation on each grid point
XYZ = XYZ(sub2ind(size(XYZ), (1:size(XYZ,1)).' * [1 1 1] ,permXYZ));

% map each point
cosyx = sqrt(2) * cos(pi/12 * XYZ(:,2)./XYZ(:,1));
sinyx = sqrt(2) * sin(pi/12 * XYZ(:,2)./XYZ(:,1));

A = 2 * cosyx - 3;
B = 2 - cosyx;
C = (6/pi)^(1/3);
D = sqrt(A .* (XYZ(:,1).^2 - XYZ(:,3).^2) + XYZ(:,3).^2);
E = C * XYZ(:,1)./abs(XYZ(:,3)) .* D ./ B;

xyz = XYZ;
xyz(:,1) = E .* (cosyx - 1);
xyz(:,2) = E .* sinyx;
xyz(:,3) = C * (XYZ(:,3) + XYZ(:,1).^2 ./ XYZ(:,3) .* A ./ B);

% overwrite points with division by zero
O = (XYZ(:,1)==0);
xyz(O,:) = (6/pi)^(1/3) * XYZ(O,:);

xyz = xyz(sub2ind(size(xyz), (1:size(xyz,1)).' * [1 1 1] ,ipermXYZ));

end

author: mtex-toolbox

repo: mtex

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


text:
function h=plotbox(box,varargin)
% PLOTBOX Plots box(es) to the current figure.
%
% Synopsis:
%  h=plotbox(box)
%  h=plotbox(box,plot_arguments)
%
% Input:
%  box [4 x numOfBoxes] box coordinates when each column has the format
%    [top_left_col top_left_row bottom_right_col bottom_right_row]
%
%  plot_arguments [...] agruments passed to plot fuction.
%
% Output:
%  h [4 x numOfBoxes] hnadles to lines forming the boxes.
%
%

if nargin < 2
    line_style = {'b'};
else
    line_style= varargin;
end

current_ishold = ishold;
hold on;

if min(size(box)) == 1

    h = [0 0 0 0]';
    h(1)=plot([box(1) box(1)],[box(2) box(4)],line_style{:});
    h(2)=plot([box(3) box(3)],[box(2) box(4)],line_style{:});
    h(3)=plot([box(1) box(3)],[box(2) box(2)],line_style{:});
    h(4)=plot([box(1) box(3)],[box(4) box(4)],line_style{:});
else
    if size(box,1) ~= 4
        box = box';
    end

    h=[];
    for i=1:size(box,2)
        h = [h plotbox(box(:,i),line_style{:})];
    end
end

if ~current_ishold
    hold off;
end

%EOF

author: uricamic

repo: flandmark

save_path: github-repos/MATLAB/uricamic-flandmark


text:
%########################################################################
%
%	- PPGI Toolbox -
%   A MATLAB toolbox for Photoplethysmography Imaging (PPGI)
%
% Author   : Christian S. Pilz
% Company  : The Nature of Space of Time
% Date     : 07.05.2019
%
% Contact  : cpi@partofthestars.com
% Web Page : www.partofthestars.com
%
% Version  : beta0.1
%
%########################################################################
%
%	skin.m:
%
% Description:
%
%   A static MATLAB class to extract skin pixels based upon
%   YCbCr color space thresholding
%

classdef skin

   methods(Static)
       function out = get(rgb)
           %convert the image from RGB to YCbCr
           img_ycbcr = rgb2ycbcr(rgb);
           Cb = img_ycbcr(:,:,2);
           Cr = img_ycbcr(:,:,3);

           %detect skin
           [r,c,v] = find(Cb>=98 & Cb<=142 & Cr>=133 & Cr<=177);
            numind = size(r,1);

            %extract skin Pixels
            for i=1:numind
                out(i,:)=double(rgb(r(i),c(i),:));
            end
       end
   end
end

author: partofthestars

repo: PPGI-Toolbox


text:
clc;
clear variables;
image=imread('lena_color.bmp');
[r,c,d] = size(image);
zoom = 1.5;
zr=zoom*r;
zc=zoom*c;

for i=1:1:zr
     for j=1:1:zc
         x=i/zoom;
         mapi=round(x);
         y=j/zoom;
         mapj=round(y);
          if mapi==0
            mapi=1;
         end
         if mapj==0
             mapj=1;
         end
         res(i,j)=image(mapi,mapj);
     end
end
figure
imshow(image);
figure
imshow(res);

author: TheAlgorithms

repo: MATLAB-Octave


text:
function [vol] = nfgFibers2ROIImage(fg,volExFile,roiFile)
%Converts fiber endpoints into ROI image
%
%   [vol] = nfgFibers2ROIImage(fg,volExFile,roiFile)
%
%   Will also write out the image to roiFIle if provided.
%
% AUTHORS:
% 2009.08.05 : AJS wrote it.
%
% NOTES:

if ieNotDefined('roiFile'); roiFile=[]; end

fiberLen = cellfun('size',fg.fibers,2);
fc = horzcat(fg.fibers{:});
eID = cumsum(fiberLen);
sID = [1 1+eID(1:end-1)];
coords1 = fc(:,sID);
coords2 = fc(:,eID);
vol = mtrImageFromCoords(coords1, coords2, volExFile, roiFile);

return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function annotate(obj,varargin)
% annotate to a existing figure

% is only applicable for MTEX figures
if isempty(gcm), return; end

aS = getMTEXpref('annotationStyle');
plot(obj,aS{:},'add2all',varargin{:});
pause(0.01);
drawNow(gcm);

end


text:
function [ grid_level, grid_point ] = cc_levels_constrained ( dim_num, ...
  q_max, alpha, level_min, level_max, grid_num, point_num )

%*****************************************************************************80
%
%% CC_LEVELS_CONSTRAINED: CC grids with constrained levels.
%
%  Discussion:
%
%    The constraint on the levels of the 1D Clenshaw Curtis rule in
%    spatial dimension I is:
%
%      LEVEL_MIN(I) <= LEVEL(I) <= LEVEL_MAX(I)
%
%    The constraint on the collection of levels making up a rule is:
%
%      Sum ( 1 <= I <= DIM_NUM ) ALPHA(I) * LEVEL(I) <= Q_MAX.
%
%    The relationship of level to order is roughly
%
%      ORDER = 2**LEVEL+1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 November 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the spatial dimension.
%
%    Input, real Q_MAX, the maximum values of
%    Q, the sum of the weighted orders in each spatial coordinate.
%
%    Input, real ALPHA(DIM_NUM), the weight factors for
%    the orders in each spatial dimension.
%
%    Input, integer LEVEL_MIN(DIM_NUM), LEVEL_MAX(DIM_NUM), the minimum
%    and maximum values of the level of the 1D Clenshaw Curtis rule
%    in each spatial dimension.
%
%    Input, integer GRID_NUM, the number of Clenshaw Curtis
%    grids in the constraint set.
%
%    Input, integer POINT_NUM, the total number of points in the grids.
%
%    Output, integer GRID_LEVEL(DIM_NUM,GRID_NUM), contains, for each
%    grid, the level of the Clenshaw-Curtis rule in each dimension.
%
%    Output, real GRID_POINT(DIM_NUM,POINT_NUM), contains
%    a list of all the abscissas of all the rules, listed one grid at
%    a time.  If a point occurs in several grids, it will be listed
%    several times.
%
  point_num = 0;
  grid_num = 0;

  level_1d = [];
  more = 0;

  while ( 1 )

    [ level_1d, more ] = vector_constrained_next4 ( dim_num, alpha, level_min, ...
      level_max, level_1d, q_max, more );

    if ( ~more )
      break
    end

    order_1d = cc_level_to_order ( dim_num, level_1d );

    order_nd = prod ( order_1d(1:dim_num) );

    grid_point(1:dim_num,point_num+1:point_num+order_nd) = cc_grid ( dim_num, ...
      order_1d, order_nd );

    point_num = point_num + order_nd;

    grid_num = grid_num + 1;
    grid_level(1:dim_num,grid_num) = level_1d(1:dim_num);

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function [branch, hash] = tapas_get_tapas_revision(verbose)
%%
%
% Input
%
% Output
%

%
% aponteeduardo@gmail.com
% copyright (C) 2017
%

n = 0;

n = n + 1;
if nargin < n
    verbose = 1;
end

% Get current location
f = mfilename('fullpath');

[tdir, ~, ~] = fileparts(f);

tdir = fullfile(tdir, '..');
try
    [branch, hash] = tapas_get_revision_info(tdir);
catch err
    if strcmp('tapas:get_revision_info', err.identifier)
        if verbose
            display(getReport(err))
        end
        branch = '';
        hash = '';
    else
        rethrow(err)
    end
end

end

author: translationalneuromodeling

repo: tapas


text:
clc; clear variables; format long g; close all;

%Include matlabrc, hopefully
%#function matlabrc

%set pathes if not deployed
if(~isdeployed)
    addpath(genpath('helper_methods'));
    addpath(genpath('formsGUIs'));
    addpath(genpath('kspTOT_RTS'));
    addpath(genpath('kspTOT_MissionArchitect'));
%     addpath('zArchive');
end

%set look and feel if deployed
if(isdeployed)
    if(ispc)
        javax.swing.UIManager.setLookAndFeel(com.sun.java.swing.plaf.windows.WindowsLookAndFeel);
    elseif(isunix)
        javax.swing.UIManager.setLookAndFeel(com.jgoodies.looks.plastic.Plastic3DLookAndFeel);
    elseif(ismac)
        javax.swing.UIManager.setLookAndFeel(com.apple.laf.AquaLookAndFeel);
    end
end

doesAppOptionsFileExist = exist('appOptions.ini','file');
if(doesAppOptionsFileExist)
    [appOptionsFromINI,~,~] = inifile('appOptions.ini','readall');
    appOptionsFromINI = addMissingAppOptionsRows(appOptionsFromINI);
else
    appOptionsFromINI = createDefaultKsptotOptions();
    inifile('appOptions.ini','write',appOptionsFromINI);
end
appOptions = processINIBodyInfo(appOptionsFromINI, false, 'appOptions'); %turns out this function works for other ini files too lol!

%Initalize celestial body data
if(isprop(appOptions.ksptot,'bodiesinifile') && ~isempty(appOptions.ksptot.bodiesinifile) && exist(appOptions.ksptot.bodiesinifile,'file'))
    [celBodyDataFromINI,~,~] = inifile(appOptions.ksptot.bodiesinifile,'readall');
else
    [celBodyDataFromINI,~,~] = inifile('bodies.ini','readall');
end
celBodyData = processINIBodyInfo(celBodyDataFromINI, false, 'bodyInfo');

multiFlyByManeuverSequencer(celBodyData);

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
function varargout = myloadnii3(varargin)
% MYLOADNII3 MATLAB code for myloadnii3.fig
%      MYLOADNII3, by itself, creates a new MYLOADNII3 or raises the existing
%      singleton*.
%
%      H = MYLOADNII3 returns the handle to a new MYLOADNII3 or the handle to
%      the existing singleton*.
%
%      MYLOADNII3('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MYLOADNII3.M with the given input arguments.
%
%      MYLOADNII3('Property','Value',...) creates a new MYLOADNII3 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before myloadnii3_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to myloadnii3_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 myloadnii3

% Last Modified by GUIDE v2.5 07-Apr-2012 12:55:04

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @myloadnii3_OpeningFcn, ...
                   'gui_OutputFcn',  @myloadnii3_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 myloadnii3 is made visible.
function myloadnii3_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 myloadnii3 (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = myloadnii3_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 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)
global gg gc;

h=guidata(gcbo);
% set(h.message_text,'String','');  % Clear Messages
gg=gg+2;
h.image_filename=1;
h.image_pathname=1;
[filename, pathname] = uigetfile({'*.nii'},'Pick a file'); % Load Image file and path names
    if filename~=0
        gg=1;
        h.gg=1;
        h.image_filename=filename;  % Image file name
        h.image_pathname=pathname;  % Image path name
%         set(h.Showaxes,'visible','off');
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
        image_1=load_untouch_nii([pathname filename]); % Load Image
%         image_1=load_nii([pathname filename]); % Load Image
        imshow(image_1.img(:,:,10),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);
    end

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h=guidata(gcbo);
image_1 = h.image_1;
slice_no = str2num(get(h.edit1,'String'))+1;
set(h.edit1,'String',num2str(slice_no));
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
        imshow(image_1.img(:,:,slice_no),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h=guidata(gcbo);
image_1 = h.image_1;
slice_no = str2num(get(h.edit1,'String'));
slice_no = slice_no - 1 ;
set(h.edit1,'String',num2str(slice_no));
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
        imshow(image_1.img(:,:,slice_no),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);

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

h=guidata(gcbo);
image_1 = h.image_1;
slice_no = str2num(get(h.edit1,'String'));
% slices = h.slices;
figure,imshow(image_1.img(:,:,slice_no),[])

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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h=guidata(gcbo);
image_1 = h.image_1;
% image_2 = image_1.img;
for i = 1:size(image_1.img,3)
    image_1.img(:,:,i) = imrotate(image_1.img(:,:,i),90);
end
    h.image_1.img = image_1.img;
        axes(h.axes1);
%         set(h.figure1_title,'Visible','on');
%         image_1=imread([pathname filename]); % Load Image
slice_no = str2num(get(h.edit1,'String'));
        imshow(image_1.img(:,:,slice_no),[]);                     % Show Loaded Image
        h.image_1=image_1;
        guidata(gcbo,h);


text:
function [p,priors]=edo_params()
% Conversion of Dynare file [Dynare_edo.mod] into RISE file [edo.rs]
%
% Done 22-Jul-2017 19:19:44.
%
% Remarks:
% - The parameters and shocks variances or
%   standard deviations found in the dynare file are assigned.
% - Shock standard deviations not assigned in the
%   dynare file get a value of 0 following dynare's convention
% - RISE will set all other parameters without a value to nan

p=struct();

p.h=0.715162417869797;
p.r_inf=1.46344163969035;
p.r_y=0.263123294207851;
p.phi_pc=3.54471453295450;
p.phi_H=3.22894079106560;
p.phi_wc=5.49395755514723;
p.phi_ic=0.253308786976374;
p.phi_cd=0.470089385005009;
p.phi_ech=9.13986886546163;
p.gam_pc=0.314488926051065;
p.gam_wc=-0.230018833252054;
p.sigman=39.4075260618789;
p.sigmah=21.8859803402692;
p.rho_R=0.833200065745674;
p.rho_XiL=0.263567746111198;
p.rho_lpref=0.979092048897712;
p.rho_B=0.895267027146152;
p.rho_STAR=0.909187927454138;
p.rho_EFFK=0.937829274540004;
p.rho_EFFECD=-0.240286975088701;
p.rho_HG=0.582395471123139;
p.rho_EFFECH=0.877235725078934;
p.tp2=0.000307314910763576;
p.sig_HG=0.579315931803017;
p.sig_XiL=2.49313873916751;
p.sig_lpref=5.66476748114241;
p.sig_R=0.124100461010359;
p.sig_MUZK=0.936167718269030;
p.sig_MUZM=0.597390920898135;
p.sig_PMKC=0.451830653200989;
p.sig_PMKK=0.685376191952156;
p.sig_EFFECH=0.514704527091087;
p.sig_EFFECD=9.11199585973990;
p.sig_EFFK=0.402779878811407;
p.sig_B=0.295232712196573;
p.sig_STAR=0.104877885500673;
p.r_dy=0;
p.ONE=1;
p.MUZKSS=1.009250;
p.MUZMSS=1.001000;
p.gam_ic=1.0;
p.gam_icd=1.0;
p.r_dinf=0;
p.rpr=0.965;
p.phi_u=1;
p.rho_MUZK=0;
p.rho_MUZM=0;
p.pbeta=0.99862;
p.delta_=0.03;
p.h_cd=0.0;
p.h_ch=0.0;
p.delta_cd=0.055;
p.delta_ch=0.0035;
p.alpha_=0.26;
p.theta_c=7;
p.theta_k=7;
p.unempSS=.06;
p.g_y=0.0;
p.a_ks=0.2;
p.s_AS=0.2;
p.gam_h=1;
p.gam_ech=1;
p.icoef=3;
p.betarl=.958;
p.std_eHG=p.sig_HG;
p.std_eXiL=p.sig_XiL;
p.std_eLpref=p.sig_lpref;
p.std_eR=p.sig_R;
p.std_eMUZK=p.sig_MUZK;
p.std_eMUZM=p.sig_MUZM;
p.std_ePMKC=p.sig_PMKC;
p.std_ePMKK=p.sig_PMKK;
p.std_eEFFECH=p.sig_EFFECH;
p.std_eEFFECD=p.sig_EFFECD;
p.std_eEFFK=p.sig_EFFK;
p.std_eB=p.sig_B;
p.std_eSTAR=p.sig_STAR;

priors=struct();

priors.h={.673, -1, 1};

priors.r_inf={1.461, 1.5000, 0.0625000, 'normal', -999, 999};

priors.r_y={0.214, 0.125, 0.125000, 'normal', -999, 999};

priors.phi_pc={3.126, 4.0000, 4.0000^.5, 'gamma', 0, 999};

priors.phi_H={4.064, 4.0000, 4.0000^.5, 'gamma', 0, 999};

priors.phi_wc={5.119, 4.0000, 4.0000^.5, 'gamma', 0, 999};

priors.phi_ic={.325, 4.0000, 4.0000^.5, 'gamma', 0, 999};

priors.phi_cd={.651, 4.0000, 4.0000^.5, 'gamma', 0, 999};

priors.phi_ech={10.948, 4.0000, 4.0000^.5, 'gamma', 0, 999};

priors.gam_pc={0.386, 0.000, 0.250, 'normal', -999, 999};

priors.gam_wc={0.213, 0.000, 0.250, 'normal', -999, 999};

priors.sigman={1.25, 1.25, 12.5^.5, 'gamma', 0, 999};

priors.sigmah={10, 10, 100^.5, 'gamma', 0, 999};

priors.rho_R={0.654, 0.5, 0.25, 'normal', -1, 1};

priors.rho_XiL={0.654, 0.5, 0.25, 'normal', -1, 1};

priors.rho_lpref={0.954, 0.5, 0.25, 'normal', -1, 1};

priors.rho_B={0.825, 0, 0.5, 'normal', -1, 1};

priors.rho_STAR={0.825, 0, 0.5, 'normal', -1, 1};

priors.rho_EFFK={0.850, 0, 0.5, 'normal', -1, 1};

priors.rho_EFFECD={.230, 0, 0.5, 'normal', -1, 1};

priors.rho_HG={0.596, 0.5, 0.015^.5, 'beta'};

priors.rho_EFFECH={0.844, 0, 0.5, 'normal', -1, 1};

priors.tp2={0.001, 0.0, 0.0005, 'normal', -999, 999};

priors.std_eHG={.745, 1.772454, 4, 'inv_gamma', 0.0001, 999};

priors.std_eXiL={3.621, 1.772454, 4, 'inv_gamma', 0.0001, 999};

priors.std_eLpref={1.621, 1.772454, 4, 'inv_gamma', 0.0001, 999};

priors.std_eR={0.165, 0.354491, 4, 'inv_gamma', 0.0001, 999};

priors.std_eMUZK={.834, 0.443113, 4, 'inv_gamma', 0.0001, 999};

priors.std_eMUZM={.484, 0.443113, 4, 'inv_gamma', 0.0001, 999};

priors.std_ePMKC={.391, 0.354491, 4, 'inv_gamma', 0.0001, 999};

priors.std_ePMKK={.552, 0.354491, 4, 'inv_gamma', 0.0001, 999};

priors.std_eEFFECH={.526, 1.772454, 4, 'inv_gamma', 0.0001, 999};

priors.std_eEFFECD={13.349, 1.772454, 4, 'inv_gamma', 0.0001, 999};

priors.std_eEFFK={.499, 1.772454, 4, 'inv_gamma', 0.0001, 999};

priors.std_eB={0.5, 1.772454, 4, 'inv_gamma', 0.0001, 999};

priors.std_eSTAR={0.05, 0.354491, 4, 'inv_gamma', 0.0001, 999};

author: jmaih


text:
function tc=TurnningCurver_power(angle,amplitute,binwidth,sampleTime,smoothfactor)

% input:
% amplitute: the calcium signal in each frame;
% angle: the angle in each frame;
% the binwidth to make the histogrom;

% amplitute must have the same length as angle

angle = mod(angle, 360); % Make sure 0 <= theta <= 2*pi
numBins = ceil(360 / binwidth);
x = (0:numBins-1) * 360/numBins + 180./numBins;
tc(:, 1)= x;
%     edges = sort(mod([(x(2:end) + x(1:end-1))/2 (x(end) + x(1) + twoPi)/2], twoPi));
%     edges = [edges edges(1) + twoPi];

[timeperbin, edge] = histcounts(angle(:,1), numBins(:,1), 'binlimits', [0 360]);
Amplituteperbin=zeros(numBins,1);

for i=1:1:size(angle,1)
    if ceil(angle(i)/binwidth)==0
        Amplituteperbin(1)=Amplituteperbin(1)+amplitute(i);
    else
        Amplituteperbin(ceil(angle(i)/binwidth))=Amplituteperbin(ceil(angle(i)/binwidth))+amplitute(i);
    end
end
timeperbin=timeperbin*sampleTime;
tc(:, 2)=Amplituteperbin./(timeperbin'+eps);
tc(:, 3)=timeperbin';
tc(:, 2)=general.smooth(tc(:, 2), smoothfactor);

end

author: kavli-ntnu


text:
classdef SmoothingRectangleVademecum < handle

    properties (Access = private)
        outPutPath
        smoothVad
        nonSmoothVad
        difDB

        firstVademecum
        secondVademecum
    end

    methods (Access = public)

        function obj = SmoothingRectangleVademecum()
            obj.init();
            obj.smoothVad    = obj.computeVademecum(obj.firstVademecum);
            obj.nonSmoothVad = obj.computeVademecum(obj.secondVademecum);
            obj.postprocessDifVademecum();
        end

    end

    methods (Access = private)

        function init(obj)
            obj.createOutPutPath();
            obj.firstVademecum = 'SuperEllipseQ2';
            %obj.firstVademecum = 'SuperEllipseQOptAnalytic';
            obj.secondVademecum = 'SuperEllipseQMax';
        end

        function createOutPutPath(obj)
            firstPart  = fullfile('/home','alex');
            secondPart = fullfile('git-repos','MicroStructurePaper','Other');
            obj.outPutPath = fullfile(firstPart,secondPart);
        end

        function vc = computeVademecum(obj,fileName)
            d.fileName = fileName;
            d.outPutPath = fullfile(obj.outPutPath,[d.fileName,'/']);
            vc = VademecumComputerAndPlotter(d);
            vc.compute();
        end

        function postprocessDifVademecum(obj)
            fV = obj.firstVademecum;
            sV = obj.secondVademecum;
            folderPath = fullfile(obj.outPutPath,['DifferenceFrom',fV,'to',sV],'/');
            mkdir(folderPath);
            d.fileName   = 'ReactangleDifference';
            d.outPutPath = folderPath;
            d.smoothVD   = obj.smoothVad.vademecumData;
            d.smoothVD.feasibleIndex = obj.smoothVad.getFeasibleIndex();
            d.nonSmoothVD = obj.nonSmoothVad.vademecumData;
            d.nonSmoothVD.feasibleIndex = obj.nonSmoothVad.getFeasibleIndex();
            vc = VademecumDifferenceComputerAndPlotter(d);
            vc.compute();
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
%GENDATM Generation of multi-class 2-D data
%
% 	A = GENDATM(N)
%
% INPUT
%   N   Vector of class sizes (default: 20)
%
% OUTPUT
%   A   Dataset
%
% DESCRIPTION
% Generation of N samples in 8 classes of 2 dimensionally distributed data
% vectors. Classes have equal prior probabilities. If N is a vector of
% sizes, exactly N(I) objects are generated for class I, I = 1..8.
%
% SEE ALSO (PRTools Guide)
% DATASETS, PRDATASETS

% Copyright: R.P.W. Duin, duin@ph.tn.tudelft.nl
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands

% $Id: gendatm.m,v 1.2 2006/03/08 22:06:58 duin Exp $

function a = gendatm(n)

	  if (nargin == 0)
		prwarning(3,'number of samples to generate not specified, assuming 20');
		n = repmat(20,1,8);
	end;

	% Set equal priors and generate a class distribution according to it.

	p = repmat(1/8,1,8); n = genclass(n,p);

	% Generate 8 classes...

	a1 = +gendath(n(1:2));			% ...first 2 classes: Highleyman data.
	a2 = +gendatc(n(3:4))./5;		% ...next 2 classes : spherical classes.
	a3 = +gendatb(n(5:6))./5;		% ...next 2 classes : banana data.
	a4 = +gendatl(n(7:8))./5;		% ...next 2 classes : Lithuanian data.

	% Glue classes together with some proper offsets.

	a = [a1; a2+5; a3+repmat([5,0],n(5)+n(6),1); a4+repmat([0 5],n(7)+n(8),1)];

	lab = genlab(n,['a';'b';'c';'d';'e';'f';'g';'h']);
	a = prdataset(a,lab,'name','Multi-Class Problem');
  a = setprior(a,0); % make all classes equally probable

return

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function nuDot = forwardDynamics(tau, JL, JR, M, h, f, LEFT_RIGHT_FOOT_IN_CONTACT)

    % get the robot accelerations using the joint torques, the
    % dynamics model, the robot state and the contact constraints.
    ndof  = size(M,1)-6;
    B     = [zeros(6,ndof); eye(ndof)];

    nuDot = M\(B*tau+LEFT_RIGHT_FOOT_IN_CONTACT(1)*JL'*f(1:6)+LEFT_RIGHT_FOOT_IN_CONTACT(2)*JR'*f(7:end)-h);

end

author: robotology

repo: whole-body-controllers


text:
function varargout = ma_MissionOptimizerGUI(varargin)
% MA_MISSIONOPTIMIZERGUI MATLAB code for ma_missionoptimizergui.fig
%      MA_MISSIONOPTIMIZERGUI, by itself, creates a new MA_MISSIONOPTIMIZERGUI or raises the existing
%      singleton*.
%
%      H = MA_MISSIONOPTIMIZERGUI returns the handle to a new MA_MISSIONOPTIMIZERGUI or the handle to
%      the existing singleton*.
%
%      MA_MISSIONOPTIMIZERGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MA_MISSIONOPTIMIZERGUI.M with the given input arguments.
%
%      MA_MISSIONOPTIMIZERGUI('Property','Value',...) creates a new MA_MISSIONOPTIMIZERGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before ma_MissionOptimizerGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to ma_MissionOptimizerGUI_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 ma_missionoptimizergui

% Last Modified by GUIDE v2.5 20-May-2016 22:12:18

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @ma_MissionOptimizerGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @ma_MissionOptimizerGUI_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 ma_missionoptimizergui is made visible.
function ma_MissionOptimizerGUI_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 ma_missionoptimizergui (see VARARGIN)

% Choose default command line output for ma_missionoptimizergui
    handles.output = hObject;
    handles.exists = true;

    % Update handles structure
    handles.ma_MainGUI = varargin{1};
    guidata(hObject, handles);

    maData = getappdata(handles.ma_MainGUI,'ma_data');

    excludeList = {'Distance Traveled','Distance to Ref. Station','Dry Mass','Eclipse','Elevation Angle w.r.t. Ref. Station', ...
                   'Line of Sight to Ref. Spacecraft','Line of Sight to Ref. Station','Liquid Fuel/Ox Mass','Monopropellant Mass','Xenon Mass'};
    taskList = ma_getGraphAnalysisTaskList(excludeList);

    propNames = maData.spacecraft.propellant.names;
    for(i=1:length(propNames))
        taskList{end+1} = sprintf('%s Mass', propNames{i}); %#ok<AGROW>
    end
    taskList = sort(taskList);

    set(handles.availConstListbox, 'String', taskList);

    initUserData(handles, maData);

    setOptVarListbox(handles.optVarListbox, maData);
    optVarListbox_Callback(handles.optVarListbox, [], handles);

    setOptVarListbox(handles.eventObjFuncCombo, maData);
    populateBodiesCombo(getappdata(handles.ma_MainGUI,'celBodyData'), handles.bodyObjFuncCombo);
    bodyObjFuncCombo_Callback(handles.objFuncCombo, [], handles);

    populateGUIFromOptSettings(handles, maData);
    objFuncCombo_Callback(handles.objFuncCombo, [], handles);

    % UIWAIT makes ma_missionoptimizergui wait for user response (see UIRESUME)
    uiwait(handles.ma_MissionOptimizerGUI);

function initUserData(handles, maData)
    set(handles.optVarListbox,'UserData',zeros(length(maData.script),5));
    set(handles.actConstsListbox,'UserData',{});

function setOptVarListbox(hListbox, maData)
    script = maData.script;

    i = 1;
    listboxStr = {};
    for(eventArr = script)
        event = eventArr{1};
        listboxStr{end+1} = ['Event ', num2str(i), ': ', event.name]; %#ok<AGROW>
        i = i+1;
    end

    set(hListbox,'String',listboxStr);

function populateGUIFromOptSettings(handles, maData)
    script = maData.script;

    if(isfield(maData.optimizer,'objective') && ~isempty(maData.optimizer.objective))
        value = findValueFromComboBox(maData.optimizer.objective{1}, handles.objFuncCombo);
        if(value <= length(get(handles.objFuncCombo,'String')))
            set(handles.objFuncCombo,'value',value);
        else
            set(handles.objFuncCombo,'value',length(get(handles.objFuncCombo,'String')));
        end

        eventID = maData.optimizer.objective{5};
        [~, eventNum] = getEventByID(eventID, script);
        if(eventNum <= length(get(handles.eventObjFuncCombo,'String')))
            [~, eventNum] = getEventByID(eventID, script);
            if(eventNum >= 1)
                set(handles.eventObjFuncCombo,'value',eventNum);
            else
                set(handles.eventObjFuncCombo,'value',length(get(handles.eventObjFuncCombo,'String')));
            end
        else
            set(handles.eventObjFuncCombo,'value',length(get(handles.eventObjFuncCombo,'String')));
        end

        if(maData.optimizer.objective{4} <= length(get(handles.bodyObjFuncCombo,'String')))
            set(handles.bodyObjFuncCombo,'value',maData.optimizer.objective{4});
        else
            set(handles.bodyObjFuncCombo,'value',length(get(handles.bodyObjFuncCombo,'String')));
        end
    end

    if(~isempty(maData.optimizer.constraints))
        constDetails = maData.optimizer.constraints{1};
        constDetailsToDelete = [];
        for(i=1:size(constDetails,1))
            try
                row = constDetails(i,:);
                details = row{5};

                eventID = details(7);
                [event, eventNum] = getEventByID(eventID, script);
                row{1} = ma_getConstraintStr(row{3}, eventNum);
                constDetails(i,:) = row;
                if(isempty(event) || eventNum<1 || ~isstruct(event) || ~isfield(event,'id') || event.id ~= eventID)
                    constDetailsToDelete(end+1) = i; %constraint no longer applicable, delete
                end

                otherSCID = details(8);
                oSCInfo = getOtherSCInfoByID(maData, otherSCID);
                if(isempty(oSCInfo) && otherSCID >= 0)
                    constDetailsToDelete(end+1) = i;
                end
            catch
                constDetailsToDelete(end+1) = i;
                continue;
            end
        end

        for(i=length(constDetailsToDelete):-1:1)
            idToDelete = constDetailsToDelete(i);
            constDetails(idToDelete,:) = [];
        end

        preSize = size(constDetails);
        constDetails(all(cellfun(@isempty,constDetails),2),:) = [];
        postSize = size(constDetails);

        if(~all(preSize==postSize))
            set(handles.actConstsListbox,'UserData',constDetails);
            updateActConstListBox(handles);
        end

        set(handles.actConstsListbox,'UserData',constDetails);
        updateActConstListBox(handles);
    end

% --- Outputs from this function are returned to the command line.
function varargout = ma_MissionOptimizerGUI_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 selection change in objFuncCombo.
function objFuncCombo_Callback(hObject, eventdata, handles)
% hObject    handle to objFuncCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns objFuncCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from objFuncCombo
    contents = cellstr(get(hObject,'String'));
    selected = deblank(contents{get(hObject,'Value')});

    switch selected
        case 'Minimize Distance to Body'
            set(handles.eventObjFuncCombo,'Enable','on');
            set(handles.bodyObjFuncCombo,'Enable','on');

        case 'Maximize Spacecraft Mass'
            set(handles.eventObjFuncCombo,'Enable','on');
            set(handles.bodyObjFuncCombo,'Enable','off');

        case 'Minimize Inclination'
            set(handles.eventObjFuncCombo,'Enable','on');
            set(handles.bodyObjFuncCombo,'Enable','off');

        case 'Minimize Eccentricity'
            set(handles.eventObjFuncCombo,'Enable','on');
            set(handles.bodyObjFuncCombo,'Enable','off');

        case 'Maximize Inclination'
            set(handles.eventObjFuncCombo,'Enable','on');
            set(handles.bodyObjFuncCombo,'Enable','off');

        case 'Maximize Eccentricity'
            set(handles.eventObjFuncCombo,'Enable','on');
            set(handles.bodyObjFuncCombo,'Enable','off');

        case 'Minimize Mission Duration'
            set(handles.eventObjFuncCombo,'Enable','off');
            set(handles.bodyObjFuncCombo,'Enable','off');

        case 'No Optimization (Satisfy Constraints Only)'
            set(handles.eventObjFuncCombo,'Enable','off');
            set(handles.bodyObjFuncCombo,'Enable','off');
    end

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

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

% --- Executes on selection change in eventObjFuncCombo.
function eventObjFuncCombo_Callback(hObject, eventdata, handles)
% hObject    handle to eventObjFuncCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns eventObjFuncCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from eventObjFuncCombo

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

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

% --- Executes on selection change in optVarListbox.
function optVarListbox_Callback(hObject, eventdata, handles)
% hObject    handle to optVarListbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns optVarListbox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from optVarListbox
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');

    eventNum = get(hObject,'Value');
    event = maData.script{eventNum};

    updateEventInfo(handles.varEventInfoLabel, event, celBodyData);
%     setOptFlagLbUb(handles, eventNum);

function setOptFlagLbUb(handles, eventNum)
    maData = getappdata(handles.ma_MainGUI,'ma_data');

    userData = get(handles.optVarListbox,'UserData');
    if(eventNum > size(userData,1))
        userData = [userData; zeros(eventNum-size(userData,1),5)];
    end
    eventID = ma_GetEventIDByEventNum(eventNum, maData.script);
    event = getEventByID(eventID, maData.script);

    blacklist = false;
    if(strcmpi(event.type,'Mass_Dump'))
        blacklist = true;
    elseif(strcmpi(event.type,'Set_State'))
        blacklist = true;
    elseif(strcmpi(event.type,'Coast'))
        bool1 = strcmpi(event.coastType,'goto_ut');
        bool2 = strcmpi(event.coastType,'goto_dt');
        bool3 = strcmpi(event.coastType,'goto_tru');
        if(~(bool1 || bool2 || bool3))
            blacklist = true;
        end
    elseif(strcmpi(event.type,'DV_Maneuver'))
        bool1 = strcmpi(event.maneuverType,'dv_inertial');
        bool2 = strcmpi(event.maneuverType,'dv_orbit');
        if(~(bool1 || bool2))
            blacklist = true;
        end
    end

    if(blacklist)
        set(handles.varOptEventCheckbox,'Enable','off', 'value',0);
        set(handles.lbVarText,'Enable','off');
        set(handles.ubVarText,'Enable','off');
    else
        set(handles.lbVarText,'Enable','on');
        set(handles.ubVarText,'Enable','on');
        set(handles.varOptEventCheckbox,'Enable','on');

        row = userData(eventNum,:);
        set(handles.varOptEventCheckbox, 'value', row(1));
        set(handles.lbVarText, 'String', num2str(row(2)));
        set(handles.ubVarText, 'String', num2str(row(3)));
    end

function updateEventInfo(hVarEventInfoLabel, event, celBodyData)
    name = event.name;
    type = event.type;

    optStr = {};
    if(isfield(event,'vars'))
        vars = event.vars;
        for(i=1:size(vars,2))
            if(vars(1,i) == 1)
                optStr{i} = '(Opt)';
            else
                optStr{i} = '';
            end
        end
    end

    if(length(name)>13)
        name = [name(1:10),'...'];
    end
    if(length(type)>13)
        type = [type(1:10),'...'];
    end

    eventInfoStr = {};
    eventInfoStr{end+1} = ['Name    = ', name];
    eventInfoStr{end+1} = ['Type    = ', type];

    subtype = [];
    param1Str = 'No Parameters';
    param2Str = '';
    param3Str = '';
    switch event.type
        case 'Set_State'
            subtype = 'None';

        case 'Coast'
            subtype = event.coastType;

            switch subtype
                case 'goto_ut'
                    param1Str = ['UT = ', num2str(event.coastToValue),' sec ', optStr{1}];

                    param2Str = ['Num. of Revs = ', num2str(event.revs)];

                    if(~isempty(event.refBody))
                        bodyInfo = getBodyInfoByNumber(event.refBody.id, celBodyData);
                        param3Str = ['RefBody = ', bodyInfo.name];
                    else
                        param3Str = ['RefBody = None'];
                    end

                case 'goto_dt'
                    param1Str = ['dT = ', num2str(event.coastToValue),' sec ', optStr{1}];

                    param2Str = ['Num. of Revs = ', num2str(event.revs)];

                    bodyInfo = event.refBody;
                    if(~isempty(bodyInfo))
                        param3Str = ['RefBody = ', bodyInfo.name];
                    else
                        param3Str = ['RefBody = None'];
                    end

                case 'goto_tru'
                    param1Str = ['Tru Anom = ', num2str(rad2deg(event.coastToValue)),' deg ', optStr{1}];

                    param2Str = ['Num. of Revs = ', num2str(event.revs)];

                    bodyInfo = event.refBody;
                    if(~isempty(bodyInfo))
                        param3Str = ['RefBody = ', bodyInfo.name];
                    else
                        param3Str = ['RefBody = None'];
                    end

                otherwise
                    param1Str = ['Num. of Revs = ', num2str(event.revs)];

                    bodyInfo = event.refBody;
                    if(~isempty(bodyInfo))
                        param2Str = ['RefBody = ', bodyInfo.name];
                    else
                        param2Str = ['RefBody = None'];
                    end
            end

        case 'DV_Maneuver'
            subtype = event.maneuverType;

            switch event.maneuverType
                case 'dv_inertial'
                    param1Str = ['dVx = ', num2str(event.maneuverValue(1)*1000), ' m/s ', optStr{1}];
                    param2Str = ['dVy = ', num2str(event.maneuverValue(2)*1000), ' m/s ', optStr{2}];
                    param3Str = ['dVz = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
                case 'dv_orbit'
                    param1Str = ['dVp = ', num2str(event.maneuverValue(1)*1000), ' m/s ', optStr{1}];
                    param2Str = ['dVn = ', num2str(event.maneuverValue(2)*1000), ' m/s ', optStr{2}];
                    param3Str = ['dVr = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
                case 'finite_inertial'
                    param1Str = ['dVx = ', num2str(event.maneuverValue(1)*1000), ' m/s ', optStr{1}];
                    param2Str = ['dVy = ', num2str(event.maneuverValue(2)*1000), ' m/s ', optStr{2}];
                    param3Str = ['dVz = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
                case 'finite_steered'
                    param1Str = ['dVp = ', num2str(event.maneuverValue(1)*1000), ' m/s ', optStr{1}];
                    param2Str = ['dVn = ', num2str(event.maneuverValue(2)*1000), ' m/s ', optStr{2}];
                    param3Str = ['dVr = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
                case 'dv_inertial_spherical'
                    param1Str = ['Az. = ', num2str(rad2deg(event.maneuverValue(1))), ' deg ', optStr{1}];
                    param2Str = ['El. = ', num2str(rad2deg(event.maneuverValue(2))), ' deg ', optStr{2}];
                    param3Str = ['Mag. = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
                case 'dv_orbit_spherical'
                    param1Str = ['Az. = ', num2str(rad2deg(event.maneuverValue(1))), ' deg ', optStr{1}];
                    param2Str = ['El. = ', num2str(rad2deg(event.maneuverValue(2))), ' deg ', optStr{2}];
                    param3Str = ['Mag. = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
                case 'finite_inertial_spherical'
                    param1Str = ['Az. = ', num2str(rad2deg(event.maneuverValue(1))), ' deg ', optStr{1}];
                    param2Str = ['El. = ', num2str(rad2deg(event.maneuverValue(2))), ' deg ', optStr{2}];
                    param3Str = ['Mag. = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
                case 'finite_steered_spherical'
                    param1Str = ['Az. = ', num2str(rad2deg(event.maneuverValue(1))), ' deg ', optStr{1}];
                    param2Str = ['El. = ', num2str(rad2deg(event.maneuverValue(2))), ' deg ', optStr{2}];
                    param3Str = ['Mag. = ', num2str(event.maneuverValue(3)*1000), ' m/s ', optStr{3}];
            end

        case 'Mass_Dump'
            subtype = event.subType;
    end

    if(length(subtype)>13)
        subtype = [subtype(1:10),'...'];
    end
    eventInfoStr{end+1} = ['Subtype = ', subtype];
    eventInfoStr{end+1} = [' '];
    eventInfoStr{end+1} = param1Str;
    eventInfoStr{end+1} = param2Str;
    eventInfoStr{end+1} = param3Str;

    set(hVarEventInfoLabel, 'String',eventInfoStr);

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

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

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

% Hint: get(hObject,'Value') returns toggle state of varOptEventCheckbox
    updateVarListbox(handles);

function updateVarListbox(handles)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    varUserData = get(handles.optVarListbox,'UserData');
    eventNum = get(handles.optVarListbox,'Value');

    lb = str2double(get(handles.lbVarText,'String'));
    if(isnan(lb))
        lb = 0;
    end
    ub = str2double(get(handles.ubVarText,'String'));
    if(isnan(ub))
        ub = 0;
    end

    eventID = ma_GetEventIDByEventNum(eventNum, maData.script);
    varUserData(eventNum, :) = [get(handles.varOptEventCheckbox,'Value'), lb, ub, eventNum, eventID];
    set(handles.optVarListbox,'UserData',varUserData);

% --- Executes on button press in optimizeMissionButton.
function optimizeMissionButton_Callback(hObject, eventdata, handles)
% hObject    handle to optimizeMissionButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');
    writeOutput = getappdata(handles.ma_MainGUI,'write_to_output_func');

    contents = cellstr(get(handles.objFuncCombo,'String'));
    selectedObjFunc = deblank(contents{get(handles.objFuncCombo,'Value')});

    contents = cellstr(get(handles.bodyObjFuncCombo,'String'));
    selectedCelBody = contents{get(handles.bodyObjFuncCombo,'Value')};
    selectedCelBodyValue = get(handles.bodyObjFuncCombo,'Value');
    if(~isempty(selectedCelBody))
        bodyID = celBodyData.(strtrim(lower(selectedCelBody))).id;
    else
        bodyID = -1;
    end

    objEventNum = get(handles.eventObjFuncCombo,'value');
    objEventID = ma_GetEventIDByEventNum(objEventNum, maData.script);

    optVarData = get(handles.optVarListbox,'UserData');
    actConsts = get(handles.actConstsListbox,'UserData');

    hWaitbar = waitbar(0,'Please wait while the optimizer initializes...');

    [maData, problem] = ma_setupOptimProblem(maData, celBodyData, hWaitbar, selectedObjFunc, bodyID, selectedCelBodyValue, objEventNum, objEventID, optVarData, actConsts);
    if(isempty(problem))
        return;
    end

    setappdata(handles.ma_MainGUI,'ma_data',maData);

    %%%%%%%
    % Get Var Strings
    %%%%%%%
    varStrs = {};
    for(i=1:length(maData.optimizer.variables{2}))
        varStr = maData.optimizer.variables{2}{i}.varStr;
        varStr = varStr(:)';
        varStrs = horzcat(varStrs,varStr); %#ok<AGROW>
    end

    %%%%%%%
    % Run optimizer!
    %%%%%%%
    set(handles.ma_MissionOptimizerGUI,'Visible','off');
    drawnow;
    waitbar(1,hWaitbar);
    close(hWaitbar);

%     ma_ObserveOptimGUI(celBodyData, problem, false, writeOutput, handles.ma_MainGUI, varStrs);
    handlesObsOptimGui = ma_ObserveOptimGUI();
    handlesObsOptimGui.ma_MainGUI = handles.ma_MainGUI;

    propNames = maData.spacecraft.propellant.names;
    lbUsAll = problem.lb;
    ubUsAll = problem.ub;

    recorder = ma_OptimRecorder();
    outputFnc = @(x, optimValues, state) ma_OptimOutputFunc(x, optimValues, state, handlesObsOptimGui, problem.objective, problem.lb, problem.ub, celBodyData, recorder, propNames, writeOutput, varStrs, lbUsAll, ubUsAll);
    problem.options.OutputFcn = outputFnc;

    executeOptimProblem(handlesObsOptimGui, problem, recorder);
    close(handlesObsOptimGui.ma_ObserveOptimGUI);

    uiresume(handles.ma_MissionOptimizerGUI);
    close(handles.ma_MissionOptimizerGUI);

% --- Executes on selection change in availConstListbox.
function availConstListbox_Callback(hObject, eventdata, handles)
% hObject    handle to availConstListbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns availConstListbox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from availConstListbox
    if(strcmpi(get(handles.ma_MissionOptimizerGUI,'SelectionType'),'open'))
        addConstraintButton_Callback(handles.addConstraintButton, [], handles);
    end

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

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

% --- Executes on selection change in actConstsListbox.
function actConstsListbox_Callback(hObject, eventdata, handles)
% hObject    handle to actConstsListbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns actConstsListbox contents as cell array
%        contents{get(hObject,'Value')} returns selected item from actConstsListbox
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    actConsts = get(handles.actConstsListbox,'UserData');
    value = get(handles.actConstsListbox,'value');

    if(strcmpi(get(handles.ma_MissionOptimizerGUI,'SelectionType'),'open'))
        preSize = size(actConsts);
        actConsts(all(cellfun(@isempty,actConsts),2),:) = [];
        postSize = size(actConsts);

        if(~all(preSize==postSize))
            set(handles.actConstsListbox,'UserData',actConsts);
            updateActConstListBox(handles);
            return;
        end

        try
            const = actConsts(value,:);
            type = const{end,3};
            unit = const{end,4};
            numericConstInputs = const{end,5};
            lbLim = numericConstInputs(1);
            ubLim = numericConstInputs(2);
            lbVal = numericConstInputs(3);
            ubVal = numericConstInputs(4);
            body = numericConstInputs(5);
%             eventNum = numericConstInputs(6);
            otherSC = numericConstInputs(8);
            eventID = numericConstInputs(7);

            if(length(numericConstInputs) == 8)
                lbActive = true;
                ubActive = true;
            else
                lbActive = numericConstInputs(9);
                ubActive = numericConstInputs(10);
            end
        catch
            try
                actConsts(value,:) = [];
                set(handles.actConstsListbox,'UserData',actConsts);
                updateActConstListBox(handles);
                return;
            catch
                return;
            end
        end

        [~, eventNum] = getEventByID(eventID, maData.script);
        [constFunc, lbVal, ubVal, body, otherSC, eventID, lbActive, ubActive] = ma_ConstraintDetailsGUI(handles.ma_MainGUI, type, unit, lbLim, ubLim, lbVal, ubVal, body, eventNum, otherSC, eventID, lbActive, ubActive);
        if(~isempty(constFunc))
            [~, eventNum] = getEventByID(eventID, maData.script);
            constStr = ma_getConstraintStr(type, eventNum);

            actConsts = get(handles.actConstsListbox,'UserData');
            actConsts{value,1} = constStr;
            actConsts{value,2} = [];
            actConsts{value,3} = type;
            actConsts{value,4} = unit;
            actConsts{value,5} = [lbLim, ubLim, lbVal, ubVal, body, eventNum, eventID, otherSC, lbActive, ubActive];
            set(handles.actConstsListbox,'UserData',actConsts);

            updateActConstListBox(handles);
        end
    end

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

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

% --- Executes on button press in addConstraintButton.
function addConstraintButton_Callback(hObject, eventdata, handles)
% hObject    handle to addConstraintButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    contents = cellstr(get(handles.availConstListbox,'String'));
    type = deblank(contents{get(handles.availConstListbox,'Value')});

    eventNum = -1;
    eventID = -1;

    [unit, lbLim, ubLim, lbVal, ubVal, body, othersc] = ma_getConstraintStaticDetails(type);
    lbActive = true;
    ubActive = true;

    [constFunc, lbVal, ubVal, body, othersc, eventID, lbActive, ubActive] = ma_ConstraintDetailsGUI(handles.ma_MainGUI, type, unit, lbLim, ubLim, lbVal, ubVal, body, eventNum, othersc, eventID, lbActive, ubActive);
    if(~isempty(constFunc))
        [~, eventNum] = getEventByID(eventID, maData.script);
        constStr = ma_getConstraintStr(type, eventNum);

        actConsts = get(handles.actConstsListbox,'UserData');
        actConsts = ma_getConstCellArr(actConsts, constStr, constFunc, type, unit, lbLim, ubLim, lbVal, ubVal, body, eventNum, eventID, othersc, lbActive, ubActive);
        set(handles.actConstsListbox,'UserData',actConsts);

        updateActConstListBox(handles);
    end

function updateActConstListBox(handles)
    actConsts = get(handles.actConstsListbox,'UserData');
    value = get(handles.actConstsListbox,'value');

    listboxStr = cell(size(actConsts,1),1);
    for(i=1:size(actConsts,1))
        listboxStr{i} = actConsts{i,1};
    end

    if(length(listboxStr)==1)
        set(handles.actConstsListbox,'String',listboxStr);
        set(handles.actConstsListbox,'value',1);
    elseif(length(listboxStr) < value)
        set(handles.actConstsListbox,'value',length(listboxStr));
        set(handles.actConstsListbox,'String',listboxStr);
    else
        set(handles.actConstsListbox,'String',listboxStr);
%         set(handles.actConstsListbox,'value',length(listboxStr));
    end

    setActConstListboxTooltip(handles);

function setActConstListboxTooltip(handles)
    actConsts = get(handles.actConstsListbox,'UserData');
    maData = getappdata(handles.ma_MainGUI,'ma_data');
    celBodyData = getappdata(handles.ma_MainGUI,'celBodyData');

    tooltipStr = 'Active Constraints:\n \n';
    for(i=1:size(actConsts,1)) %#ok<*NO4LP>
        try
            constType = actConsts{i,3};
            constUnit = actConsts{i,4};
            constLB = actConsts{i,5}(3);
            constUB = actConsts{i,5}(4);
            constEventID = actConsts{i,5}(7);
            [~, constEventNum] = getEventByID(constEventID, maData.script);
            constBodyID = actConsts{i,5}(5);
        catch
            continue;
        end

        try
            otherSCID = actConsts{i,5}(8);
        catch
            otherSCID = -1;
        end

        if(length(actConsts{i,5}) == 8)
            lbActive = true;
            ubActive = true;
        else
            lbActive = actConsts{i,5}(9);
            ubActive = actConsts{i,5}(10);
        end

        if(constBodyID == -1)
            constBodyStrFull = '';
        else
            bodyInfo = getBodyInfoByNumber(constBodyID, celBodyData);
            constBodyStr = bodyInfo.name;
            constBodyStrFull = ['Body: ', constBodyStr,'\n'];
        end

        if(otherSCID == -1)
            constOSCStrFull = '';
        else
            otherSCInfo = getOtherSCInfoByID(maData, otherSCID);
            if(~isempty(otherSCInfo) && isfield(otherSCInfo,'name'))
                constOSCStr = otherSCInfo.name;
                constOSCStrFull = ['Spacecraft: ',constOSCStr,'\n'];
            else
                constOSCStrFull = '';
            end
        end

        lbActiveStr = '';
        if(lbActive == false)
            lbActiveStr = ' (Inactive)';
        end

        ubActiveStr = '';
        if(ubActive == false)
            ubActiveStr = ' (Inactive)';
        end

        lbStr = ['Lower Bnd: ', num2str(constLB), ' ', constUnit, lbActiveStr, '\n'];
        ubStr = ['Upper Bnd: ', num2str(constUB), ' ', constUnit, ubActiveStr, '\n'];

        if(constLB == 0 && constUB == 0 && isempty(constUnit) && ~strcmpi(constType, 'Eccentricity'))
            lbStr = '';
            ubStr = '';
        end

        tooltipStr = [tooltipStr,...
                      '--',constType,' Constraint--','\n'...
                      'Event: ', num2str(constEventNum),'\n',...
                      lbStr,...
                      ubStr,...
                      constBodyStrFull,...
                      constOSCStrFull,' \n']; %#ok<AGROW>
    end
    set(handles.actConstsListbox, 'TooltipString', sprintf(tooltipStr));

% --- Executes on button press in removeConstraintButton.
function removeConstraintButton_Callback(hObject, eventdata, handles)
% hObject    handle to removeConstraintButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    value = get(handles.actConstsListbox,'value');
    actConsts = get(handles.actConstsListbox,'UserData');
    if(value > 0)
        actConsts(value,:) = [];

        set(handles.actConstsListbox,'UserData',actConsts);

        updateActConstListBox(handles);
    end

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

function lbVarText_Callback(hObject, eventdata, handles)
% hObject    handle to lbVarText (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 lbVarText as text
%        str2double(get(hObject,'String')) returns contents of lbVarText as a double
    updateVarListbox(handles);

% --- Executes during object creation, after setting all properties.
function lbVarText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lbVarText (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function ubVarText_Callback(hObject, eventdata, handles)
% hObject    handle to ubVarText (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 ubVarText as text
%        str2double(get(hObject,'String')) returns contents of ubVarText as a double
    updateVarListbox(handles);

% --- Executes during object creation, after setting all properties.
function ubVarText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ubVarText (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 && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in bodyObjFuncCombo.
function bodyObjFuncCombo_Callback(hObject, eventdata, handles)
% hObject    handle to bodyObjFuncCombo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns bodyObjFuncCombo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from bodyObjFuncCombo

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

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

% --- Executes on key press with focus on ma_MissionOptimizerGUI or any of its controls.
function ma_MissionOptimizerGUI_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to ma_MissionOptimizerGUI (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)
    switch(eventdata.Key)
        case 'escape'
            close(handles.ma_MissionOptimizerGUI);
    end

% --------------------------------------------------------------------
function enableAllConstMenu_Callback(hObject, eventdata, handles)
% hObject    handle to enableAllConstMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    actConsts = get(handles.actConstsListbox,'UserData');
    for(i=1:size(actConsts,1))
        actConsts{i,5}(9) = 1;
        actConsts{i,5}(10) = 1;
    end
    set(handles.actConstsListbox,'UserData',actConsts);

% --------------------------------------------------------------------
function disableAllConstMenu_Callback(hObject, eventdata, handles)
% hObject    handle to disableAllConstMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    actConsts = get(handles.actConstsListbox,'UserData');
    for(i=1:size(actConsts,1))
        actConsts{i,5}(9) = 0;
        actConsts{i,5}(10) = 0;
    end
    set(handles.actConstsListbox,'UserData',actConsts);


text:
% Jiao Xianjun (putaoshu@msn.com; putaoshu@gmail.com)
% generate frequency domain PSS and time domain PSS signal
% A script of project: https://github.com/JiaoXianjun/rtl-sdr-LTE

function [fd_pss, td_pss] = pss_gen
fd_pss = zeros(128,3);
td_pss = zeros(128+9,3);
for i=1:3
    temp=pss(i-1);
    fd_pss(:,i)=[0 temp(32:end) zeros(1,65) temp(1:31)].';
    temp_td=idft(fd_pss(:,i))*sqrt(128/62);
    td_pss(:,i)=[temp_td(end-8:end); temp_td];
end

author: JiaoXianjun

repo: rtl-sdr-LTE


text:
function zi=interptri(tri,x,y,z,xi,yi)
% INTERPTRI Interpolate Triangulation.
% Zi = INTERPTRI(TRI,X,Y,Z,Xi,Yi) linearly interpolates the scattered data
% in vectors X,Y,Z as described by the triangulation TRI as returned by
% DELAUNAY at the individual pairs of points in Xi and Yi. That is, Zi(k)
% is the linear interpolation at the point (Xi(k),Yi(k)). Xi and Yi are not
% MESHGRIDed as they are in GRIDDATA when Xi is a row vector and and Yi is
% a column vector. Use MESHGRID when desired. For example,
%                  [Xii,Yii] = MESHGRID(Xi,Yi); % meshgrid yourself
%                         Zi = INTERPTRI(TRI,x,y,z,Xii,Yii);
% is the same as          Zi = GRIDDATA(x,y,z,Xi(:).',Yi(:));
%
% INTERPTRI is faster than GRIDDATA when the same data is interpolated more
% than once because the triangulation TRI is precomputed and passed into
% INTERPTRI, whereas it is computed within GRIDDATA each time it is called.
%
% See also GRIDDATA, MESHGRID, DELAUNAY, TRIPLOT, TRIMESH, TRISURF, TSEARCH

% D.C. Hanselman, University of Maine, Orono, ME 04469
% MasteringMatlab@yahoo.com
% Mastering MATLAB 7
% 2006-05-03

if nargin~=6
   error('Six Input Arguments Required.')
end
x=x(:); % make input data into vectors
y=y(:);
z=z(:).';
xlen=length(x);
if ~isequal(xlen,length(y),length(z))
   error('X, Y, and Z Must Have the Same Number of Elements.')
end
if size(tri,2)~=3 || any(tri(:)<0) || any(tri(:)>xlen)
   error('TRI Must Be a Valid Triangulation of the Data in X, Y, Z.')
end

zisiz=size(xi);
xi=xi(:);
yi=yi(:);
if length(xi)~=length(yi)
   error('Xi and Yi Must Have the Same Number of Elements.')
end
%ti=tsearch(x,y,tri,xi,yi); % find triangle associated with each data point.

% use tsearchn because tsearch is now gone
ti=tsearchn([x y],tri,[xi yi]);

tinan=isnan(ti);  % True for xi, yi outside the convex hull
ti(tinan)=1;      % point nan points to triangle one for now
tri=tri(ti,:);    % keep only those triangles where xi and yi exist

x1=x(tri(:,1));   % x data at vertices
x2=x(tri(:,2));
x3=x(tri(:,3));
y1=y(tri(:,1));   % y data at vertices
y2=y(tri(:,2));
y3=y(tri(:,3));

A2=(x2-x1).*(y3-y1) - (x3-x1).*(y2-y1); % shape functions
N(:,3)=((x1-xi).*(y2-yi) - (x2-xi).*(y1-yi))./A2;
N(:,2)=((x3-xi).*(y1-yi) - (x1-xi).*(y3-yi))./A2;
N(:,1)=((x2-xi).*(y3-yi) - (x3-xi).*(y2-yi))./A2;
N(tinan,:)=0;           % give zero weight to nan data
zi = sum(z(tri).*N,2);  % interpolate
zi(tinan)=nan;          % poke in nans where needed
zi=reshape(zi,zisiz);   % reshape output to match xi and yi input


text:
% SP_EVAL_BOUNDARY_SIDE: Construct the space structure of one side of the boundary.
%
%     sp_side = sp_eval_boundary_side (sp, msh_side)
%
% INPUTS:
%
%     sp:       space object (see sp_scalar)
%     msh_side: mesh structure containing the information of the quadrature
%               rule on the boundary edge (see msh_cartesian/msh_eval_boundary_side)
%
% OUTPUT:
%
%     sp_side: structure that contains the following fields
%              (see the article for a detailed description)
%
%     FIELD_NAME      (SIZE)                                   DESCRIPTION
%     ncomp           (scalar)                                 number of components of the functions of the space (actually, 1)
%     nsh_max         (scalar)                                 maximum number of shape functions per element
%     nsh             (1 x msh_side.nel vector)                actual number of shape functions per each element
%     ndof            (scalar)                                 total number of degrees of freedom
%     connectivity    (nsh_max x msh_side.nel vector)          indices of basis functions that do not vanish in each element
%     shape_functions (msh_side.nqn x nsh_max x msh_side.nel)  basis functions evaluated at each quadrature node in each element
%     dofs            (1 x ndof vector)                        numbering of the degrees of freedom in the volumetric space
%
% Copyright (C) 2009, 2010 Carlo de Falco
% Copyright (C) 2011, 2015 Rafael Vazquez
%
%    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/>.

function sp_side = sp_eval_boundary_side (sp, msh_side)

  iside = msh_side.side_number;
  sp_side = sp_precompute (sp.boundary(iside), msh_side);

end

author: rafavzqz

repo: geopdes

save_path: github-repos/MATLAB/rafavzqz-geopdes