text:
%PLOTM Plot mapping values, contours or surface
%
% 	H = PLOTM(W,S,N)
%
% INPUT
%   W   Trained mapping
%   S   Plot strings, or scalar selecting type of plot
%          1: density plot;
%          2: contour plot (default);
%          3: 3D surface plot;
%          4: 3D surface plot above 2D contour plot;
%          5; 3D mesh plot;
%          6: 3D mesh plot above 2D contour plot)
%   N   Contour level(s) to plot
%         (default: 10 contours between minimum and maximum)
%
% OUTPUT
%		H		Array of graphics handles
%
% DESCRIPTION
% This routine, similar to PLOTC, plots contours (not just decision
% boundaries) of the mapping W on predefined axis, typically generated by
% SCATTERD. Plotstrings may be set in S. The vector N selects the contour.
%
% If N = 'perc' 10 contour levels are drawn such that each level has an
% equal area in the plot.
%
% EXAMPLES
% See PREX_DENSITY
%
% SEE ALSO (PRTools Guide)
% MAPPINGS, SCATTERD, PLOTC

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands

% $Id: plotm.m,v 1.4 2009/09/25 13:15:17 duin Exp $

function handle = plotm(w,arg2,n,cnd)

	ismapping(w);				% Assert that W is a mapping.
  w = w*setbatch;     % Avoid memory prolems with large gridsizes

	% Get the parameters, the plotstrings and the number of contours.

    if (nargin < 4)
        cnd = 1;
    end;

	[k,c] = size(w);
	if (nargin < 3)
		n = [];
	end

	plottype = 2; s = [];
	if (nargin >= 2)
		if (~isstr(arg2) & ~isempty(arg2))
			plottype = arg2;
		else
			s = arg2;
		end
	end

	if plottype == 2 & size(w,1) == 1
		plottype = 1;
	end

	if (nargin < 2) | (isempty(s))
		col = 'brmk';
		s = [col' repmat('-',4,1)];
		s = char(s,[col' repmat('--',4,1)]);
		s = char(s,[col' repmat('-.',4,1)]);
		s = char(s,[col' repmat(':',4,1)]);
		s = char(s,s,s,s);
	end

	% When one contour should be plotted, two entries have to be given in
	% the contour plot (Matlab bug/feature).

	%if (~isempty(n)) & (length(n) == 1), n = [n n]; end

	% Setup the mesh-grid, use the axis of the currently active figure.
	% Note: this will be a 0-1 grid in case of no given scatterplot.

	hold on; V = axis;
	gs = gridsize; dx = (V(2)-V(1))/gs; dy = (V(4)-V(3))/gs;
    if (plottype == 1)
			m = (gs+1); X = (V(1):dx:V(2))';
			D = double([X,zeros(m,k-1)]*w);
      D = real(D);
    else
			m = (gs+1)*(gs+1); [X Y] = meshgrid(V(1):dx:V(2),V(3):dy:V(4));
	    D = double([X(:),Y(:),zeros(m,k-2)]*w);
      D = real(D);
    end;

    if (~cnd)
      % where is this used?? For what? (RD)
      D = sum(D,2);
    end;

	% HH will contain all handles to graphics created in this routine.

	hh = [];

    % Plot the densities in case of 1D output.
    if (plottype == 1)
        for j = 1:size(D,2)
            if (size(s,1) > 1), ss = s(j,:); else ss = s; end

            % Plot the densities and add the handles to HH.

    		h = plot([V(1):dx:V(2)],D(:,j),deblank(ss));
    		hh = [hh; h];
        end
        axis ([V(1) V(2) 0 1.2*max(max(D))]);
				ylabel('Density')
    end

	% Plot the contours in case of 2D output.
	if (plottype == 2) | (plottype == 4) | (plottype == 6)

		% Define the contour-heights if they are not given.

		if (isempty(n))
			n = 10;
			dmax = max(D(:)); dmin = min(D(:)); dd = (dmax-dmin)/(n+1);
			n = [dmin+dd:dd:dmax-dd];
    elseif ischar(n) && strcmp(n,'perc')
      n = prctile(D,5:10:95);
		end;

		if length(n) == 1, n = [n n]; end

		% Plot the contours for each of the classes.

   		for j = 1:size(D,2)

   			if (size(s,1) > 1), ss = s(j,:); else, ss = s; end

   			Z = reshape(D(:,j),gs+1,gs+1);

			% Plot the contours and add the handles to HH.

   			[cc, h] = contour([V(1):dx:V(2)],[V(3):dy:V(4)],Z,n,deblank(ss));
   			hh = [hh; h];

        end

		view(2);

	end

	% Plot the surface in case of 3D output.

	if (plottype == 3) | (plottype == 4) | (plottype == 5) | (plottype == 6)

		% Scale the outputs to cover the whole colour range.

		%E = D - min(D(:));
		%E = 255*E/max(E(:))+1;
        E = D; % Scaling appears disputable (RD)
		if (c>1)
        Z = reshape(sum(E,2),gs+1,gs+1);
	  else
        Z = reshape(E(:,1),gs+1,gs+1);
	  end

		if (plottype == 4) | (plottype == 6)
			Z = Z + max(max(Z));
		end;

		% Plot the surface, set up lighting and add the handles to HH.

		h = surf([V(1):dx:V(2)],[V(3):dy:V(4)],Z);

		if (plottype == 3) | (plottype == 4)
            colormap jet;
            shading interp;
			set(h,'FaceColor','interp','EdgeColor','none','FaceLighting','none ');
		else
			colormap white;
			shading faceted;
		end

		view(-37.5,20);
		camlight left; 								% Necessary to solve camlight bug?
		camlight headlight;
		camlight right;
		hh = [hh; h];

	end

	hold off; if (nargout > 0), handle = hh; end

return


text:
function is_empty = isempty(obj)

is_empty = length(obj) == 0 || isempty(obj(1).XYZ) || length(obj(1).XYZ) == 0;

end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function s = n2str(n)
% num2str with exact zero

s = num2str(setNull(n));

author: mtex-toolbox

repo: mtex

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


text:
function [im_hatch,colorlist] = applyhatch_plus(h,patterns,colorlist,dpi, ...
                                                hatchsc,lw)
%APPLYHATCH_PLUS Apply hatched patterns to a figure
%  im_hatch = applyhatch_plus(h,patterns,colorlist,dpi,hatchsc,lw)
%
%  APPLYHATCH(H,PATTERNS) creates a new figure from the figure H by
%  replacing distinct colors in H with the black and white
%  patterns in PATTERNS. The format for PATTERNS can be
%    a string of the characters like '/', '\', '|', '-', '+', 'x', '.'
%    (see makehatch_plus.m for more details) or
%    a cell array of matrices of zeros (white) and ones (black)
%
%  In addition, H can alternatively be a uint8 NxMx3 matrix of the type
%  produced by imread.  In this case, colors in this image will be
%  replaced with patterns as if it was a figure.  A final figure window
%  will be generated that displays the result.  The DPI argument
%  discussed below will be ignored if H is an image matrix.
%
%  APPLYHATCH(H,PATTERNS,COLORS) maps the colors in the n by 3
%  matrix COLORS to PATTERNS. Each row of COLORS specifies an RGB
%  color value.
%
%  Note this function makes a bitmap image of H and so is limited
%  to bitmap output.
%
%  Additional arguments:
%
%  [im_hatch,colorlist] = applyhatch_plus(h,patterns,colorlist,dpi,hatchsc,linewidth)
%
%   input   DPI         allows specification of bitmap resolution, making plot resolution
%                       better for printing.  Ignored if H is an image matrix.
%           HATCHSC     multiplier for hatch scale to increase size of pattern for better operation
%                       at higher resolutions
%                       default [] uses screen resolution as in
%                       APPLYHATCH
%           LINEWIDTH   A scaling factor to apply to line and dot sizes
%                       in hatching.  Defaults to 1.
%   output  IM_HATCH    RGB bitmap matrix of new figure
%                       use IMWRITE to output in desired format
%           COLORLIST   List of colors actually replaced.  Useful info if
%                       no colorlist initially given to function.
%                       Colorlist will be uint8, not 0-1 scale as
%                       originally specified.
%
%  Example 1:
%    bar(rand(3,4));
%    [im_hatch,colorlist] = applyhatch_plus(gcf,'\-x.',[],150);
%    imwrite(im_hatch,'im_hatch.tiff','tiff')
%
%  Example 2:
%    colormap(cool(6));
%    pie(rand(6,1));
%    legend('Jan','Feb','Mar','Apr','May','Jun');
%    im_hatch = applyhatch_plus(gcf,'|-+.\/',cool(6),150,4);
%    imwrite(im_hatch,'im_hatch.tiff','tiff')
%
%  Example 3: Produces roughly the same thing as example 1
%    bar(rand(3,4));
%    print -dtiff -r150 im.tiff
%    im = imread( 'im.tiff', 'tiff' );
%    [im_hatch,colorlist] = applyhatch_plus(im,'\-x.',[]);
%    imwrite(im_hatch,'im_hatch.tiff','tiff')
%
%
% Modification of APPLYHATCH to allow higher resolution output
% Modified Brian FG Katz    8-aout-03
% Modified David M Kaplan   19-fevrier-08
%
%  See also: APPLYHATCH, MAKEHATCH, MAKEHATCH_PLUS

%  By Ben Hinkle, bhinkle@mathworks.com
%  This code is in the public domain.

if ~exist('hatchsc','var'); hatchsc = 1      ; end
if ~exist('dpi','var'); dpi = 0          ; end     % defaults to screen resolution
if ~exist('colorlist','var'); colorlist = []   ; end
if ~exist('lw','var'); lw=1; end

if numel(h) == 1 % Assume it is a figure window
  oldppmode = get(h,'paperpositionmode');
  oldunits = get(h,'units');
  oldcolor = get(h,'color');
  oldpos = get(h,'position');
  set(h,'paperpositionmode','auto');
  set(h,'units','pixels');
  set(h,'color',[1 1 1]);
  figsize = get(h,'position');

  bits = hardcopy(h,'-dzbuffer',['-r' num2str(dpi)]);

  % % Try a different approach using a temporary file - use this if having probs
  % tn = [ tempname '.tif' ];
  % print( '-dtiff', [ '-r' num2str(dpi) ], tn )
  % bits = uint8( imread( tn, 'TIFF' ) );
  % delete(tn)

  set(h,'paperpositionmode',oldppmode);
  set(h,'color',oldcolor);
elseif size(h,3) == 3 % Assume it is an image matrix
  bits = h;
  oldunits='pixels';
  oldpos = [ 0, 0, size(bits,2), size(bits,1) ];
  figsize = oldpos;
else
  error( 'Bad first argument.' );
end

bwidth = size(bits,2);
bheight = size(bits,1);
bsize = bwidth * bheight;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The next bit basically modernizes the original
% version of this function using things like unique
% and for loops
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make bitmap one long matrix with 3 columns
bits = reshape(bits,[bsize,3]);

% Convert original color scale to 255 scale
if ~isempty(colorlist)
  % NOTE: Added "floor" below because this seems to better pick out
  % correct colors produced by "hardcopy above better than uint8 by itself

  %colorlist = uint8(255*colorlist);
  colorlist = uint8(floor(255*colorlist));
else
  % Find unique colors in image - this takes a long time at high resolution
  [B,I,J] = unique( bits, 'rows' );

  % Find just "colored" colors
  C = find( B(:,1)~=B(:,2) | B(:,1)~=B(:,3) );
  colorlist = B( C , : );
end

% Loop over list of colors and find matches
for k = 1:size(colorlist,1)

  % Find points that match color
  if exist('B','var') % Use unique colors if around
    I = C(k) == J;
  else % Otherwise test each point
    cc = colorlist(k,:);
    I = bits(:,1)==cc(1) & bits(:,2)==cc(2) & bits(:,3)==cc(3);
    if ~any(I(:)), continue, end
  end

  % What pattern to use
  pati = mod( k-1, numel(patterns) ) + 1;
  if iscell(patterns)
    pattern = patterns{pati};
  elseif isa(patterns,'char')
    pattern = makehatch_plus(patterns(pati),6*hatchsc,lw);
  else
    pattern = patterns;
  end
  pattern = uint8(255*(1-pattern));

  % Make a big pattern matching size of bits
  pheight = size(pattern,2);
  pwidth = size(pattern,1);
  ratioh = ceil(bheight/pheight);
  ratiow = ceil(bwidth/pwidth);
  bigpattern = repmat(pattern,[ratioh ratiow]);
  if ratioh*pheight > bheight
    bigpattern(bheight+1:end,:) = [];
  end
  if ratiow*pwidth > bwidth
    bigpattern(:,bwidth+1:end) = [];
  end

  % Put that pattern into bits
  bits(find(I),:) = repmat(bigpattern(I),[1,3]);
end

% Put bits back into its normal shape
bits = reshape( bits, [bheight,bwidth,3] );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Replot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
newfig = figure('units',oldunits,'visible','off');
imaxes = axes('parent',newfig,'units','pixels');
im = image(bits,'parent',imaxes);
%fpos = get(newfig,'position');
%set(newfig,'position',[fpos(1:2) figsize(3) figsize(4)+1]);
set(newfig,'position',oldpos)
set(newfig,'units','pixels')
set(imaxes,'position',[0 0 figsize(3) figsize(4)+1],'visible','off');
set(newfig,'visible','on');

set(newfig,'units','normalized');
set(imaxes,'units','normalized');
set(imaxes,'DataAspectRatio',[1 1 1],'DataAspectRatioMode','manual');

if nargout > 0, im_hatch = bits; end
if nargout < 2, clear colorlist; end

author: Sable

repo: mcbench-benchmarks


text:
function test_suite = test_distanceLines3d
%TESTDISTANCELINES3D  One-line description here, please.
%
%   output = testDistanceLines3d(input)
%
%   Example
%   testDistanceLines3d
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-01-21,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testOrthogonal(testCase) %#ok<*DEFNU>

line1 = [0 0 0   0 0 1];
line2 = [10 0 0  0 1 0];

d = distanceLines3d(line1, line2);
testCase.assertEqual(10, d, 'AbsTol', .01);

line1 = [0 0 0   0 0 1];
line2 = [0 10 0  1 0 0];

d = distanceLines3d(line1, line2);
testCase.assertEqual(10, d, 'AbsTol', .01);

line1 = [0 0 0   0 1 0];
line2 = [0 0 10  1 0 0];

d = distanceLines3d(line1, line2);
testCase.assertEqual(10, d, 'AbsTol', .01);

function testNotOrthogonal(testCase) %#ok<*DEFNU>

line1 = [0 0 0   0 2 3];
line2 = [10 0 0  0 -1 4];

d = distanceLines3d(line1, line2);
testCase.assertEqual(10, d, 'AbsTol', .01);

function testArrays(testCase)

line1 = [0 0 0   0 2 3];
line2 = [10 0 0  0 -1 4];

dist = distanceLines3d(line1, repmat(line2, 5, 1));
exp = repmat(10, 1, 5);
testCase.assertEqual(exp, dist, 'AbsTol', .01);

dist = distanceLines3d(repmat(line1, 5, 1), line2);
exp = repmat(10, 5, 1);
testCase.assertEqual(exp, dist, 'AbsTol', .01);

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function mvuInfo = mvuDeconstruct(model)

% MVUDECONSTRUCT break MVU in pieces for saving.
% FORMAT
% DESC takes an MVU model structure and breaks it into component
% parts for saving.
% ARG model : the model that needs to be saved.
% RETURN mvuInfo : a structure containing the other information
% from the MVU: what the sparse approximation is, what the inducing
% variables are.
%
% SEEALSO : mvuReconstruct
%
% COPYRIGHT : Neil D. Lawrence, 2009

% MLTOOLS

mvuInfo = model;
removeFields = {'Y'};

for i = 1:length(removeFields)
  if isfield(mvuInfo, removeFields{i})
    mvuInfo = rmfield(mvuInfo, removeFields{i});
  end
end

author: SheffieldML

repo: GPmat

save_path: github-repos/MATLAB/SheffieldML-GPmat


text:
%CentralCamera.visjac_e Visual motion Jacobian for point feature
%
% J = C.visjac_e(E, PL) is the image Jacobian (5x6) for the ellipse
% E (5x1) described by u^2 + E1v^2 - 2E2uv + 2E3u + 2E4v + E5 = 0.  The
% ellipse lies in the world plane PL = (a,b,c,d) such that aX + bY + cZ + d = 0.
%
% The Jacobian gives the rates of change of the ellipse parameters in
% terms of camera spatial velocity.
%
% Reference::
% B. Espiau, F. Chaumette, and P. Rives,
% "A New Approach to Visual Servoing in Robotics",
% IEEE Transactions on Robotics and Automation,
% vol. 8, pp. 313-326, June 1992.
%
% See also CentralCamera.visjac_p, CentralCamera.visjac_p_polar, CentralCamera.visjac_l.

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

function L = visjac_e(cam, A, plane)

    a = -plane(1)/plane(4); b = -plane(2)/plane(4); c = -plane(3)/plane(4);
    L = [
2*b*A(2)-2*a*A(1), 2*A(1)*(b-a*A(2)), 2*b*A(4)-2*a*A(1)*A(3), 2*A(4), 2*A(1)*A(3), -2*A(2)*(A(1)+1)
b-a*A(2), b*A(2)-a*(2*A(2)^2-A(1)), a*(A(4)-2*A(2)*A(3))+b*A(3), -A(3), -(2*A(2)*A(3)-A(4)), A(1)-2*A(2)^2-1
c-a*A(3), a*(A(4)-2*A(2)*A(3))+c*A(2), c*A(3)-a*(2*A(3)^2-A(5)), -A(2), 1+2*A(3)^2-A(5), A(4)-2*A(2)*A(3)
A(3)*b+A(2)*c-2*a*A(4), A(4)*b+A(1)*c-2*a*A(2)*A(4), b*A(5)+c*A(4)-2*a*A(3)*A(4), A(5)-A(1), 2*A(3)*A(4)+A(2), -2*A(2)*A(4)-A(3)
2*c*A(3)-2*a*A(5), 2*c*A(4)-2*a*A(2)*A(5), 2*c*A(5)-2*a*A(3)*A(5), -2*A(4), 2*A(3)*A(5)+2*A(3), -2*A(2)*A(5)
];
    L = L * diag([0.5,0.5,0.5, 1,1,1]);   % not sure why...

author: petercorke

repo: machinevision-toolbox-matlab


text:
function xy = ellipse_grid ( n, r, c, ng )

%*****************************************************************************80
%
%% ELLIPSE_GRID generates grid points inside an ellipse.
%
%  Discussion:
%
%    The ellipse is specified as
%
%      ( ( X - C1 ) / R1 )^2 + ( ( Y - C2 ) / R2 )^2 = 1
%
%    The user supplies a number N.  There will be N+1 grid points along
%    the shorter axis.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 November 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the number of subintervals.
%
%    Input, real R(2), the half axis lengths.
%
%    Input, real C(2), the center of the ellipse.
%
%    Input, integer NG, the number of grid points inside the ellipse.
%
%    Output, real XY(2,NG), the grid points.
%
  if ( r(1) < r(2) )
    h = 2 * r(1) / ( 2 * n + 1 );
    ni = n;
    nj = ceil ( r(2) / r(1) ) * n;
  else
    h = 2 * r(2) / ( 2 * n + 1 );
    nj = n;
    ni = ceil ( r(1) / r(2) ) * n;
  end

  p = 0;

  for j = 0 : nj
    i = 0;
    x = c(1);
    y = c(2) + j * h;
    p = p + 1;
    xy(1:2,p) = [ x, y ]';
    if ( 0 < j )
      p = p + 1;
      xy(1:2,p) = [ x, 2 * c(2) - y ]';
    end
    while ( 1 )
      i = i + 1;
      x = c(1) + i * h;
      if ( 1 < ( ( x - c(1) ) / r(1) ).^2 + ( ( y - c(2) ) / r(2) ).^2 )
        break
      end
      p = p + 1;
      xy(1:2,p) = [ x, y ]';
      p = p + 1;
      xy(1:2,p) = [ 2 * c(1) - x, y ]';
      if ( 0 < j )
        p = p + 1;
        xy(1:2,p) = [ x, 2 * c(2) - y ]';
        p = p + 1;
        xy(1:2,p) = [ 2 * c(1) - x, 2 * c(2) - y ]';
      end
    end
  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function conv_nbrhood=cosmo_convert_neighborhood(nbrhood, output_type)
% Converts between cell, matrix and struct representations of neighborhoods
%
% conv_nbrhood=cosmo_convert_neighborhood(nbrhood[, output_type])
%
% Inputs:
%     nbrhood               Either a cell, struct, or matrix with
%                           neighborhood information:
%                           - cell:    Nx1 with nbrhood{k} the indices of
%                                      the k-th neighborhood
%                           - struct:  with field .neighbors, which must
%                                      be a cell
%                           - matrix:  MxN with nbrhood(:,k) the indices of
%                                      the k-th neighborhood (non-positive
%                                      values indicating no index), with M
%                                      the maximum number of features in a
%                                      single neighborhood
%     output_type           Optional, one of 'cell', 'matrix', or
%                           'struct'.
%                           If empty or omitted, then output_type is set to
%                           'matrix', unless nbrhood is a matrix, in
%                           which case it is set to 'cell'.
% Output:
%     conv_nbrhood          Neighborhood information converted to cell,
%                           struct, or matrix (see above)
%
% Example:
%     ds=cosmo_synthetic_dataset();
%     nbrhood=cosmo_spherical_neighborhood(ds,'radius',1,'progress',false);
%     % show the neighbor indices
%     cosmo_disp(nbrhood.neighbors)
%     %|| { [ 1         4         2 ]
%     %||   [ 2         1         5         3 ]
%     %||   [ 3         2         6 ]
%     %||   [ 4         1         5 ]
%     %||   [ 5         4         2         6 ]
%     %||   [ 6         5         3 ]           }
%     %
%     % convert to matrix representation
%     mx=cosmo_convert_neighborhood(nbrhood,'matrix');
%     cosmo_disp(mx)
%     %|| [ 1         2         3         4         5         6
%     %||   4         1         2         1         4         5
%     %||   2         5         6         5         2         3
%     %||   0         3         0         0         6         0 ]
%     %
%     % convert to cell representation
%     neighbors=cosmo_convert_neighborhood(nbrhood,'cell');
%     cosmo_disp(neighbors)
%     %|| { [ 1         4         2 ]
%     %||   [ 2         1         5         3 ]
%     %||   [ 3         2         6 ]
%     %||   [ 4         1         5 ]
%     %||   [ 5         4         2         6 ]
%     %||   [ 6         5         3 ]           }
%
% Notes:
%    - the rationale of this function is that cell or struct
%      representations are more intuitive and possible more space
%      efficient, but also slower to access than matrix representations.
%      This function provides conversion between different representations.
%
% #   For CoSMoMVPA's copyright information and license terms,   #
% #   see the COPYING file distributed with CoSMoMVPA.           #

    if nargin<2, output_type=''; end

    if isnumeric(nbrhood)
        converter=@convert_matrix;
    elseif iscell(nbrhood)
        converter=@convert_cell;
    elseif isstruct(nbrhood)
        converter=@convert_struct;
    else
        error('Expected matrix, cell, or struct input');
    end

    conv_nbrhood=converter(nbrhood, output_type);

function y=convert_cell(x,output_type)
    check_cell(x);
    switch output_type
        case {'','matrix'}
            y=convert_cell2matrix(x);
        case 'struct'
            y=convert_cell2struct(x);
        case {'cell'}
            y=x;
        otherwise
            throw_illegal_output_type_error();
    end

function y=convert_matrix(x,output_type)
    check_matrix(x);
    switch output_type
        case {'','cell'}
            y=convert_matrix2cell(x);
        case 'struct'
            y=convert_matrix2struct(x);
        case 'matrix'
            y=x;
        otherwise
            throw_illegal_output_type_error();
    end

function y=convert_struct(x,output_type)
    check_struct(x);
    switch output_type
        case 'cell'
            y=convert_struct2cell(x);
        case {'','matrix'}
            y=convert_struct2matrix(x);
        case 'struct'
            y=x;
        otherwise
            throw_illegal_output_type_error();
    end

function check_matrix(neighbors)
    if numel(size(neighbors))~=2
        error('input is not a matrix');
    end

    assert(isnumeric(neighbors));

    if ~isequal(round(neighbors),neighbors)
        error('input has non-integer values');
    end

function check_struct(nbrhood)
    cosmo_check_neighborhood(nbrhood,'show_warning',false);

function check_cell(neighbors)
    check_struct(convert_cell2struct(neighbors));

function nbrhood=convert_cell2struct(neighbors)
    nbrhood=struct();
    nbrhood.neighbors=neighbors;
    nbrhood.fa=struct();
    nbrhood.a=struct();

function neighbors=convert_struct2cell(nbrhood)
    neighbors=nbrhood.neighbors;

function neighbor_matrix=convert_cell2matrix(neighbors)
    nfeatures=numel(neighbors);
    nnbrs=cellfun(@numel, neighbors);
    maxn=max(nnbrs);

    neighbor_matrix=zeros(maxn, nfeatures);
    for k=1:nfeatures
        nbrs=neighbors{k};
        neighbor_matrix(1:numel(nbrs),k)=nbrs;
    end

function neighbors=convert_matrix2cell(neighbor_matrix)
    nfeatures=size(neighbor_matrix,2);
    neighbors=cell(nfeatures,1);

    for k=1:nfeatures
        nbrs=neighbor_matrix(:,k);
        neighbors{k}=nbrs(nbrs>0)';
    end

function nbrhood=convert_matrix2struct(neighbor_matrix)
    nbrhood=convert_cell2struct(convert_matrix2cell(neighbor_matrix));

function neighbor_matrix=convert_struct2matrix(nbrhood)
    neighbor_matrix=convert_cell2matrix(convert_struct2cell(nbrhood));

function throw_illegal_output_type_error()
    valid_output_types={'','matrix','struct','cell'};
    error('illegal output type, valid is one of: ''%s''.',...
                cosmo_strjoin(valid_output_types,''', '''));

author: CoSMoMVPA

repo: CoSMoMVPA

save_path: github-repos/MATLAB/CoSMoMVPA-CoSMoMVPA


text:
function varargout = sp_gen(varargin)
%
%
% sp_gen is a GUI for generating Spirals.
%
%A. Select the plane that will be parallel to the spiral
%B. Select the type of spiral:
%You can choose from Archimedean,Logarithmic,Fermat,Hyperbolic,Lituus,Spherical and Polynomial Spirals.
%you can see the equations used for the selected spiral, and change the parameters.
%C. Select the normal component of the spiral. Note that this feature is
%not available for the spherical spirals.
%D. Add thickness to the spiral. This will provide volume and will give you
%the possibility to generate surfaces. Note that this feature is not
%available for the polynomial spirals.
%E. Generate and export spiral variables to the workspace.
%
%%%%%%BUGS
%
%I am aware of the surface bug. This is clearly visible in the spherical
%spiral, but also in the other spirals if you play with the normal
%component.This is caused because the surface twists around itself. I
%provide a partial correction, in function 'generate_thickness' in the 'if'
%statement in lines 1128-1130.
%
% If anybody comes with a solution to this or finds other bugs, please post
% on File EXchange.
%
%
%Created by Katelouzos Ioannis.

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @sp_gen_OpeningFcn, ...
                   'gui_OutputFcn',  @sp_gen_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 sp_gen is made visible.
function sp_gen_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 sp_gen (see VARARGIN)

% Choose default command line output for sp_gen
handles.output = hObject;
handles.plane=[0 0 1];
vr=[[1 0;-1 0;0 1;0 -1]*null([0 0 1])';0 0 0];
fc=[1 5 3;2 5 3;2 5 4;1 4 5];
fv.vertices=vr;
fv.faces=fc;
handles.fv=fv;
handles.xpl=zeros(3,3);
handles.ypl=zeros(3,3);
handles.zpl=zeros(3,3);
handles.surface=0;
handles.scloud=0;
handles.cloud=0;
handles.cerchi=[0;0;0];
handles.oct=zeros(8,3);
handles.spiral=zeros(3,1);
% Update handles structure
guidata(hObject, handles);

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

% --- Outputs from this function are returned to the command line.
function varargout = sp_gen_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 spiral_type.
function spiral_type_Callback(hObject, eventdata, handles)
% hObject    handle to spiral_type (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
val=(get(hObject,'Value'));
zz=(get(handles.zcomp,'Value'));
switch val
    case 1
        set(handles.text15,'String','r = a + b * theta');
        set(handles.g,'Enable','off');
        set(handles.h,'Enable','off');
        set(handles.i,'Enable','off');
        set(handles.alpha,'Enable','on');
        set(handles.beta,'Enable','on');
        set(handles.zcomp,'Enable','on');
        set(handles.thick,'Enable','on');
        set(handles.surfface,'Enable','on');
        if zz~=1
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');

        end
    case 2
        set(handles.text15,'String','r = a * exp( b * theta )');
        set(handles.g,'Enable','off');
        set(handles.h,'Enable','off');
        set(handles.i,'Enable','off');
        set(handles.alpha,'Enable','on');
        set(handles.beta,'Enable','on');
        set(handles.zcomp,'Enable','on');
        set(handles.thick,'Enable','on');
        set(handles.surfface,'Enable','on');
        if zz~=1
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');

        end
    case 3
        set(handles.text15,'String','r = +- sqrt( theta )');
        set(handles.g,'Enable','off');
        set(handles.h,'Enable','off');
        set(handles.i,'Enable','off');
        set(handles.alpha,'Enable','off');
        set(handles.beta,'Enable','off');
        set(handles.zcomp,'Enable','on');
        set(handles.thick,'Enable','on');
        set(handles.surfface,'Enable','on');
        if zz~=1
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');

        end
    case 4
        set(handles.text15,'String','r = a / theta');
        set(handles.g,'Enable','off');
        set(handles.h,'Enable','off');
        set(handles.i,'Enable','off');
        set(handles.alpha,'Enable','on');
        set(handles.beta,'Enable','off');
        set(handles.zcomp,'Enable','on');
        set(handles.thick,'Enable','on');
        set(handles.surfface,'Enable','on');
        if zz~=1
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');

        end
    case 5
        set(handles.text15,'String','r = sqrt( 1 / theta )');
        set(handles.g,'Enable','off');
        set(handles.h,'Enable','off');
        set(handles.i,'Enable','off');
        set(handles.alpha,'Enable','off');
        set(handles.beta,'Enable','off');
        set(handles.zcomp,'Enable','on');
        set(handles.thick,'Enable','on');
        set(handles.surfface,'Enable','on');
        if zz~=1
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');

        end
    case 6
        set(handles.text15,'String','x=cos(t)cos(c) y=sin(t)cos(c)  z=-sin(c) c=atan(a*t)');
        set(handles.g,'Enable','off');
        set(handles.h,'Enable','off');
        set(handles.i,'Enable','off');
        set(handles.alpha,'Enable','on');
        set(handles.beta,'Enable','off');
        set(handles.zcomp,'Enable','off');
        set(handles.c,'Enable','off');
        set(handles.d,'Enable','off');
        set(handles.e,'Enable','off');
        set(handles.f,'Enable','off');
        set(handles.thick,'Enable','on');
        set(handles.surfface,'Enable','on');
    otherwise
        set(handles.text15,'String','curvature = f(curve length) k=a*s^4+b*s^3+g*s^2+h*s+i');
        set(handles.g,'Enable','on');
        set(handles.h,'Enable','on');
        set(handles.i,'Enable','on');
        set(handles.alpha,'Enable','on');
        set(handles.beta,'Enable','on');
        set(handles.zcomp,'Enable','on');
        set(handles.thick,'Enable','off');
        set(handles.surfface,'Enable','off');
        if zz~=1
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');
        end

end
guidata(hObject, handles);
% Hints: contents = get(hObject,'String') returns spiral_type contents as cell array
%        contents{get(hObject,'Value')} returns selected item from spiral_type

% --- Executes during object creation, after setting all properties.
function spiral_type_CreateFcn(hObject, eventdata, handles)
% hObject    handle to spiral_type (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

function Xeq_Callback(hObject, eventdata, handles)
% hObject    handle to Xeq (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pl=handles.plane;
x=str2double(get(hObject,'String'));
if pl(3)==0 && pl(2)==0, x=1;
set(hObject,'String','1');
end
handles.plane(1)=x;
handles=refresh_plane(handles);
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of Xeq as text
%        str2double(get(hObject,'String')) returns contents of Xeq as a double

% --- Executes during object creation, after setting all properties.
function Xeq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Xeq (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.
handles.plane(1)=str2double(get(hObject,'String'));
guidata(hObject, handles);
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function Yeq_Callback(hObject, eventdata, handles)
% hObject    handle to Yeq (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pl=handles.plane;
x=str2double(get(hObject,'String'));
if pl(1)==0 && pl(3)==0, x=1;
set(hObject,'String','1');
end
handles.plane(2)=x;
handles=refresh_plane(handles);
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of Yeq as text
%        str2double(get(hObject,'String')) returns contents of Yeq as a double

% --- Executes during object creation, after setting all properties.
function Yeq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Yeq (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.
handles.plane(2)=str2double(get(hObject,'String'));
guidata(hObject, handles);
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function Zeq_Callback(hObject, eventdata, handles)
% hObject    handle to Zeq (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 Zeq as text
%        str2double(get(hObject,'String')) returns contents of Zeq as a double
pl=handles.plane;
x=str2double(get(hObject,'String'));
if pl(1)==0 && pl(2)==0, x=1;
set(hObject,'String','1');
end
handles.plane(3)=x;
handles=refresh_plane(handles);
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function Zeq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Zeq (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.
handles.plane(3)=str2double(get(hObject,'String'));
guidata(hObject, handles);
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in show_plane.
function show_plane_Callback(hObject, eventdata, handles)
% hObject    handle to show_plane (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles=refresh_plane(handles);
guidata(hObject, handles);
% Hint: get(hObject,'Value') returns toggle state of show_plane

function thick_Callback(hObject, eventdata, handles)
% hObject    handle to thick (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=str2double(get(hObject,'String'));
if x<0;
set(hObject,'String','0');
end
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of thick as text
%        str2double(get(hObject,'String')) returns contents of thick as a double

% --- Executes during object creation, after setting all properties.
function thick_CreateFcn(hObject, eventdata, handles)
% hObject    handle to thick (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 lengt_Callback(hObject, eventdata, handles)
% hObject    handle to lengt (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 lengt as text
%        str2double(get(hObject,'String')) returns contents of lengt as a double

x=str2double(get(hObject,'String'));
pr=str2double(get(handles.precision,'String'));
if x<=2*pr;
pr=str2double(get(handles.precision,'String'));
set(hObject,'String',sprintf('%g', pr*2));
end
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function lengt_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lengt (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 h=refresh_plane(handles)
cpos=get(handles.axes1,'CameraPosition');
pl=handles.plane;
 vr=[[1 0;-1 0;0 1;0 -1;1 1; 1 -1;-1 -1;-1 1]*null(pl)';0 0 0];
fv.vertices=vr;
xpl=[vr(8,1) vr(3,1) vr(5,1);vr(2,1) vr(9,1) vr(1,1);vr(7,1) vr(4,1) vr(6,1)];
ypl=[vr(8,2) vr(3,2) vr(5,2);vr(2,2) vr(9,2) vr(1,2);vr(7,2) vr(4,2) vr(6,2)];
zpl=[vr(8,3) vr(3,3) vr(5,3);vr(2,3) vr(9,3) vr(1,3);vr(7,3) vr(4,3) vr(6,3)];
handles.xpl=xpl;
handles.ypl=ypl;
handles.zpl=zpl;
spir=handles.spiral;

if isempty(find(spir));
    mm=1;
else mm=max(max(abs(spir)));
end
xpl=xpl.*mm/2;
ypl=ypl.*mm/2;
zpl=zpl.*mm/2;
plot3(spir(1,:),spir(2,:),spir(3,:));
hold on;
if get(handles.show_plane,'Value')==1
    mesh(xpl,ypl,zpl,'FaceAlpha',0.1,'FaceColor','g','EdgeAlpha',0.5,'EdgeColor','k');
end
set(handles.axes1,'CameraPosition',cpos);
set(handles.axes1,'DataAspectRatio',[1 1 1]);
set(get(handles.axes1,'XLabel'),'String','X','Color','r','FontWeight','bold');
set(get(handles.axes1,'YLabel'),'String','Y','Color','r','FontWeight','bold');
set(get(handles.axes1,'ZLabel'),'String','Z','Color','r','FontWeight','bold');
hold off;
h=handles;

% --- Executes on button press in export_internal.
function export_internal_Callback(hObject, eventdata, handles)
% hObject    handle to export_internal (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cloud=handles.cloud;
assignin('base','Spiral_IntCloud',cloud);

% --- Executes on button press in show_scloud.
function show_scloud_Callback(hObject, eventdata, handles)
% hObject    handle to show_scloud (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.export_scloud,'BackgroundColor',[0 1 0]);
set(handles.export_scloud,'Enable','on');
H=figure(2);
title('Surface Cloud Ordinary','Color','b','FontWeight','bold');
oct=handles.oct;
hold on;
for it=1:length(oct(1,1,:))
    plot3(oct(:,1,it),oct(:,2,it),oct(:,3,it),'.');
end
set(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);
set(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');
hold off;
H=figure(3);
title('Surface Cloud Random','Color','b','FontWeight','bold');
scloud=gen_scloud(handles,oct);
handles.scloud=scloud;
hold on;
plot3(scloud(:,1),scloud(:,2),scloud(:,3),'.');
set(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);
set(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');
hold off;
guidata(hObject, handles);

% --- Executes on button press in show_surface.
function show_surface_Callback(hObject, eventdata, handles)
% hObject    handle to show_surface (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.export_surface,'BackgroundColor',[0 1 0]);
set(handles.export_surface,'Enable','on');
H=figure(4);

oct=handles.oct;
C = permute(cat(1, oct, oct(1,:,:)),[3,1,2]);
xsurf=squeeze(C(:,:,1));
ysurf=squeeze(C(:,:,2));
zsurf=squeeze(C(:,:,3));
surface.x=xsurf;
surface.y=ysurf;
surface.z=zsurf;
handles.surface=surface;
mesh(xsurf,ysurf,zsurf,'FaceAlpha',0.1,'FaceColor','g','EdgeAlpha',0.5,'EdgeColor','k');
title('Surface','Color','b','FontWeight','bold');
set(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);
set(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');
guidata(hObject, handles);

% --- Executes on button press in show_internal.
function show_internal_Callback(hObject, eventdata, handles)
% hObject    handle to show_internal (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.export_internal,'BackgroundColor',[0 1 0]);
set(handles.export_internal,'Enable','on');
H=figure(1);
title('Internal Cloud','Color','b','FontWeight','bold');
oct=handles.oct;

cloud=gen_cloud(handles,oct);
handles.cloud=cloud;
hold on;
plot3(cloud(:,1),cloud(:,2),cloud(:,3),'.');
set(get(H,'CurrentAxes'),'DataAspectRatio',[1 1 1]);
set(get(get(H,'CurrentAxes'),'XLabel'),'String','X','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'YLabel'),'String','Y','Color','r','FontWeight','bold');
set(get(get(H,'CurrentAxes'),'ZLabel'),'String','Z','Color','r','FontWeight','bold');
hold off;
guidata(hObject, handles);

% --- Executes on button press in export_scloud.
function export_scloud_Callback(hObject, eventdata, handles)
% hObject    handle to export_scloud (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
oct=handles.oct;
scloud=handles.scloud;
B = permute(oct,[1 3 2]);
ou = reshape(B,length(oct(:,1,1))*size(oct,3),3);
assignin('base','Spiral_SurCloud_ord',ou);
assignin('base','Spiral_SurCloud_rand',scloud);

% --- Executes on button press in export_surface.
function export_surface_Callback(hObject, eventdata, handles)
% hObject    handle to export_surface (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
surface=handles.surface;
assignin('base','Spiral_Surface',surface);

% --- Executes on button press in export_line.
function export_line_Callback(hObject, eventdata, handles)
% hObject    handle to export_line (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
assignin('base','Spiral_line',handles.spiral);

% --- Executes on button press in gen_spiral.
function gen_spiral_Callback(hObject, eventdata, handles)
% hObject    handle to gen_spiral (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cpos=get(handles.axes1,'CameraPosition');
stype=get(handles.spiral_type,'Value');
alpha=str2double(get(handles.alpha,'String'));
beta=str2double(get(handles.beta,'String'));
c=str2double(get(handles.c,'String'));
d=str2double(get(handles.d,'String'));
e=str2double(get(handles.e,'String'));
f=str2double(get(handles.f,'String'));
g=str2double(get(handles.g,'String'));
h=str2double(get(handles.h,'String'));
i=str2double(get(handles.i,'String'));
thick=str2double(get(handles.thick,'String'));
pr=str2double(get(handles.precision,'String'));
lengt=str2double(get(handles.lengt,'String'));
theta=0:pr:lengt*pi;
switch stype
    case 1
        r=alpha+beta*theta;
    case 2
        r=alpha*(exp(beta*theta));
    case 3
        r=sqrt(theta);
        r2=-r;
    case 4
        r=alpha./theta;
    case 5
        r=sqrt(1./theta);
    case 6
        t=-lengt:pr:lengt;
        c=atan(alpha*t);
        x=cos(t).*cos(c);
        y=sin(t).*cos(c);
        z=-sin(c);
        [theta,r]=cart2pol(x,y);
    otherwise
        if alpha>0
            l=sqrt(lengt);
            p=pr^2;
        else
            l=lengt;
            p=pr;
        end
        [x y]=curv2cart(alpha,beta,g,h,i,l,p,handles);
        [theta,r]=cart2pol(x,y);
end
zc=(get(handles.zcomp,'Value'));
if stype~=6
switch zc
    case 1
        z=zeros(1,length(theta));
    case 2
        z=c*r.^d+e*theta.^f;
    case 3
        z = c*sin(r.*d) + e*sin(theta.*f);
    case 4
        z = c*exp(d*r) + e*exp(f*theta);
    otherwise
        z = c*log(r).^d + e*log(theta).^f;
end
end
if stype==4 || stype==5
    theta=theta(end:-1:2);
    r=r(end:-1:2);
    z=z(end:-1:2);
end
[x,y]=pol2cart(theta,r);
spiral=[x;y;z];
if stype==3
    [x2,y2]=pol2cart(theta,r2);
    z2=-z;
    spiral=[fliplr(x2) x(2:end);fliplr(y2) y(2:end);fliplr(z2) z(2:end)];
end
pl=handles.plane;
rotate= vrrotvec([0 0 1],pl);
rm = vrrotvec2mat(rotate);
spir=rm*spiral;
nnn=sum(spir,1);
w=nnn==nnn;
w=find(w==0);
spir(:,w)=[];
handles.spiral=spir;
if ~isempty(find(spir))
    refresh_plane(handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   cerchiles generation
hold on;
if thick>0
    if stype==1 || stype==2 || stype ==6 ||stype==4 ||stype==5
        [cerchi oct]=generate_thickness(1,handles);
    elseif stype==3
        [cerchi oct]=generate_thickness(2,handles);
    else %stype==7
        cerchi=[0;0;0];
        oct=zeros(8,3);
    end
handles.cerchi=cerchi;
handles.oct=oct;
end
end
set(handles.axes1,'CameraPosition',cpos);
set(handles.axes1,'DataAspectRatio',[1 1 1]);
set(get(handles.axes1,'XLabel'),'String','X','Color','r','FontWeight','bold');
set(get(handles.axes1,'YLabel'),'String','Y','Color','r','FontWeight','bold');
set(get(handles.axes1,'ZLabel'),'String','Z','Color','r','FontWeight','bold');
hold off;
if stype ~= 7 && thick >0
set(handles.show_internal,'BackgroundColor',[0 1 0]);
set(handles.show_internal,'Enable','on');
set(handles.show_scloud,'BackgroundColor',[0 1 0]);
set(handles.show_scloud,'Enable','on');
set(handles.show_surface,'BackgroundColor',[0 1 0]);
set(handles.show_surface,'Enable','on');
set(handles.export_line,'BackgroundColor',[0 1 0]);
set(handles.export_line,'Enable','on');
set(handles.export_internal,'BackgroundColor',[1 0 0]);
set(handles.export_internal,'Enable','off');
set(handles.export_scloud,'BackgroundColor',[1 0 0]);
set(handles.export_scloud,'Enable','off');
set(handles.export_surface,'BackgroundColor',[1 0 0]);
set(handles.export_surface,'Enable','off');
else
    set(handles.show_internal,'BackgroundColor','r');
set(handles.show_internal,'Enable','off');
set(handles.show_scloud,'BackgroundColor','r');
set(handles.show_scloud,'Enable','off');
set(handles.show_surface,'BackgroundColor','r');
set(handles.show_surface,'Enable','off');
set(handles.export_line,'BackgroundColor',[0 1 0]);
set(handles.export_line,'Enable','on');
set(handles.export_internal,'BackgroundColor','r');
set(handles.export_internal,'Enable','off');
set(handles.export_scloud,'BackgroundColor','r');
set(handles.export_scloud,'Enable','off');
set(handles.export_surface,'BackgroundColor','r');
set(handles.export_surface,'Enable','off');
end
guidata(hObject, handles);

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

% --- Executes during object creation, after setting all properties.
function alpha_CreateFcn(hObject, eventdata, handles)
% hObject    handle to alpha (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 beta_Callback(hObject, eventdata, handles)
% hObject    handle to beta (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 beta as text
%        str2double(get(hObject,'String')) returns contents of beta as a double

% --- Executes during object creation, after setting all properties.
function beta_CreateFcn(hObject, eventdata, handles)
% hObject    handle to beta (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 zcomp.
function zcomp_Callback(hObject, eventdata, handles)
% hObject    handle to zcomp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
val=(get(hObject,'Value'));
switch val
    case 1
        set(handles.text20,'String','z = 0');
        set(handles.c,'Enable','off');
        set(handles.d,'Enable','off');
        set(handles.e,'Enable','off');
        set(handles.f,'Enable','off');
    case 2
        set(handles.text20,'String','z = c*r^d + e*theta^f');
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');
    case 3
        set(handles.text20,'String','z = c*sin(r*d) + e*sin(theta*f)');
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');
    case 4
        set(handles.text20,'String','z = c*exp(d*r) + e*exp(f*theta)');
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');
    otherwise
        set(handles.text20,'String','z = c*log(r)^d + e*log(theta)^f');
        set(handles.c,'Enable','on');
        set(handles.d,'Enable','on');
        set(handles.e,'Enable','on');
        set(handles.f,'Enable','on');
end
guidata(hObject, handles);
% Hints: contents = get(hObject,'String') returns zcomp contents as cell array
%        contents{get(hObject,'Value')} returns selected item from zcomp

% --- Executes during object creation, after setting all properties.
function zcomp_CreateFcn(hObject, eventdata, handles)
% hObject    handle to zcomp (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

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

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

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

% Hint: 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 f_Callback(hObject, eventdata, handles)
% hObject    handle to f (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 f as text
%        str2double(get(hObject,'String')) returns contents of f as a double

% --- Executes during object creation, after setting all properties.
function f_CreateFcn(hObject, eventdata, handles)
% hObject    handle to f (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 c_Callback(hObject, eventdata, handles)
% hObject    handle to c (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 c as text
%        str2double(get(hObject,'String')) returns contents of c as a double

% --- Executes during object creation, after setting all properties.
function c_CreateFcn(hObject, eventdata, handles)
% hObject    handle to c (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 d_Callback(hObject, eventdata, handles)
% hObject    handle to d (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 d as text
%        str2double(get(hObject,'String')) returns contents of d as a double

% --- Executes during object creation, after setting all properties.
function d_CreateFcn(hObject, eventdata, handles)
% hObject    handle to d (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 g_Callback(hObject, eventdata, handles)
% hObject    handle to g (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 g as text
%        str2double(get(hObject,'String')) returns contents of g as a double

% --- Executes during object creation, after setting all properties.
function g_CreateFcn(hObject, eventdata, handles)
% hObject    handle to g (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 h_Callback(hObject, eventdata, handles)
% hObject    handle to h (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 h as text
%        str2double(get(hObject,'String')) returns contents of h as a double

% --- Executes during object creation, after setting all properties.
function h_CreateFcn(hObject, eventdata, handles)
% hObject    handle to h (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 i_Callback(hObject, eventdata, handles)
% hObject    handle to i (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 i as text
%        str2double(get(hObject,'String')) returns contents of i as a double

% --- Executes during object creation, after setting all properties.
function i_CreateFcn(hObject, eventdata, handles)
% hObject    handle to i (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 [xo yo]=curv2cart(a,b,c,d,e,l,p,handles)
set(handles.timebar_text,'Visible','on','String','Generating Spiral');
drawnow update
s=0:p:l;
s2=-s;
x1=zeros(1,length(s));
y1=zeros(1,length(s));
x2=zeros(1,length(s));
y2=zeros(1,length(s));
k=a*s.^4+b*s.^3+c*s.^2+d*s+e;
k2=a*s2.^4+b*s2.^3+c*s2.^2+d*s2+e;
x1(2)=s(2);
y1(2)=0;
x2(2)=s2(2);
y2(2)=0;
perc=(length(s)*2-4)/100;
ls=length(s)-2;
for i=3:(length(s))
    sss=sprintf('Genetaring Spiral...%3.1f %%', i/perc);
    set(handles.timebar_text,'String',sss);
    drawnow update
    dth=k(i)*s(2);
    cth=(x1(i-1)-x1(i-2))/norm([x1(i-1) y1(i-1)]-[x1(i-2) y1(i-2)]);
    sth=(y1(i-1)-y1(i-2))/norm([x1(i-1) y1(i-1)]-[x1(i-2) y1(i-2)]);
    if sth>=0
        scorr=1;
    else scorr=-1;
    end
    newth=dth+scorr*acos(cth);
    xx=cos(newth);
    yy=sin(newth);
    x1(i)=(xx*s(2))+x1(i-1);
    y1(i)=(yy*s(2))+y1(i-1);
end

for i=3:(length(s))
    sss=sprintf('Genetaring Spiral...%3.1f %%', (i+ls)/perc);
    set(handles.timebar_text,'String',sss);
    drawnow update
    dth=k2(i)*s2(2);
    cth=(x2(i-1)-x2(i-2))/norm([x2(i-1) y2(i-1)]-[x2(i-2) y2(i-2)]);
    sth=(y2(i-1)-y2(i-2))/norm([x2(i-1) y2(i-1)]-[x2(i-2) y2(i-2)]);
    if sth>=0
        scorr=1;
    else scorr=-1;
    end
    newth=dth+scorr*acos(cth);
    xx=cos(newth);
    yy=sin(newth);
    x2(i)=(xx*s(2))+x2(i-1);
    y2(i)=(yy*s(2))+y2(i-1);
end
set(handles.timebar_text,'Visible','off');
xo=[fliplr(x2) x1];
yo=[fliplr(y2) y1];

function precision_Callback(hObject, eventdata, handles)
% hObject    handle to precision (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=str2double(get(hObject,'String'));
l=str2double(get(handles.lengt,'String'));
if x<=0
    set(hObject,'String','0.1');
    x=0.1;
elseif x>1
    set(hObject,'String','1');
    x=1;
end
    if l<=2*x
        set(hObject,'String',sprintf('%g', l/2));
    end

guidata(hObject, handles);

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

% --- Executes during object creation, after setting all properties.
function precision_CreateFcn(hObject, eventdata, handles)
% hObject    handle to precision (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 clear.
function clear_Callback(hObject, eventdata, handles)
% hObject    handle to clear (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
        set(handles.text20,'String','z = 0');
        set(handles.c,'Enable','off');
        set(handles.d,'Enable','off');
        set(handles.e,'Enable','off');
        set(handles.f,'Enable','off');
        set(handles.text15,'String','r = a + b * theta');
        set(handles.g,'Enable','off');
        set(handles.h,'Enable','off');
        set(handles.i,'Enable','off');
        set(handles.alpha,'Enable','on');
        set(handles.beta,'Enable','on');
        set(handles.zcomp,'Enable','on');
        set(handles.spiral_type,'Value',1);
        set(handles.zcomp,'Value',1);
        set(handles.thick,'Enable','on');
        set(handles.surfface,'Enable','on');
handles.plane=[0 0 1];
set(handles.Xeq,'String','0');
set(handles.Yeq,'String','0');
set(handles.Zeq,'String','1');
vr=[[1 0;-1 0;0 1;0 -1]*null([0 0 1])';0 0 0];
fc=[1 5 3;2 5 3;2 5 4;1 4 5];
fv.vertices=vr;
fv.faces=fc;
handles.fv=fv;
handles.cerchi=[0;0;0];
handles.oct=zeros(8,3);
handles.surface=0;
handles.scloud=0;
handles.cloud=0;
handles.spiral=zeros(3,1);
set(handles.show_internal,'BackgroundColor','r');
set(handles.show_internal,'Enable','off');
set(handles.show_scloud,'BackgroundColor','r');
set(handles.show_scloud,'Enable','off');
set(handles.show_surface,'BackgroundColor','r');
set(handles.show_surface,'Enable','off');
set(handles.export_line,'BackgroundColor','r');
set(handles.export_line,'Enable','off');
set(handles.export_internal,'BackgroundColor','r');
set(handles.export_internal,'Enable','off');
set(handles.export_scloud,'BackgroundColor','r');
set(handles.export_scloud,'Enable','off');
set(handles.export_surface,'BackgroundColor','r');
set(handles.export_surface,'Enable','off');
guidata(hObject, handles);
refresh_plane(handles);
guidata(hObject, handles);

function [cerchi oct]=generate_thickness(a,handles)
surfface=str2double(get(handles.surfface,'String'));
stype=get(handles.spiral_type,'Value');
thick=str2double(get(handles.thick,'String'));
spir=handles.spiral;
set(handles.timebar_text,'Visible','on','String','Generating Thickness');
drawnow update;
if a==1
cerchi=[[0;0;0] spir(:,2:end)-spir(:,1:end-1)];
start=2;
else cerchi=spir(:,2:(end+1)/2)-spir(:,1:(end+1)/2-1);
    start=1;
end
oct=zeros(surfface,3,length(cerchi));
perc=(length(cerchi)-1)/100;
    for it=start:length(cerchi)
        sss=sprintf('Genetaring Thickness...%3.1f %%', it/perc);
        set(handles.timebar_text,'String',sss);
        drawnow update;
        cerc=cerchi(:,it);
        mm=norm(cerc)*thick;
        nullity=(null(cerc'))';
        if dot(cerc,[1 0 0])>0
            nullity=[-1 0;0 1]*nullity;
        end
        vects=gen_polygon(handles,surfface,mm);
        piu=zeros(3,surfface);
        piu=bsxfun(@plus,piu,spir(:,it));
        oct(:,:,it)=vects*nullity+piu';
    end
if a==2
    oct(:,:,end)=oct(:,:,end)-vects*nullity/2;
    cerchi=[cerchi fliplr(-cerchi)];
    oct= cat(3, oct, flipdim(-oct,3));
end
if stype==6
    piu=zeros(3,surfface);
    piu=bsxfun(@plus,piu,spir(:,1));
    oct(:,:,1)=piu';
    piu=zeros(3,surfface);
    piu=bsxfun(@plus,piu,spir(:,end));
    oct(:,:,end)=piu';
end

for it=start:length(cerchi)
    plot3(oct(:,1,it),oct(:,2,it),oct(:,3,it));
end
set(handles.timebar_text,'Visible','off');

function surfface_Callback(hObject, eventdata, handles)
% hObject    handle to surfface (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 surfface as text
%        str2double(get(hObject,'String')) returns contents of surfface as a double
x=floor(str2double(get(hObject,'String')));
if x<4;
x=4;
end
sss=sprintf('%d', x);
set(hObject,'String',sss);
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function surfface_CreateFcn(hObject, eventdata, handles)
% hObject    handle to surfface (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 vects=gen_polygon(handles,surfface,mm)
div=0:2*pi/surfface:2*pi-2*pi/surfface;
vects=[cos(div')*mm sin(div')*mm];

function scloud=gen_scloud(handles,oct)
set(handles.timebar_text,'Visible','on','String','Generating Thickness');
drawnow update;
faces=length(oct(:,1,1))-1;
perc=(length(oct(1,1,:))-1)*faces/100;
oct=cat(1, oct, oct(1,:,:));
pl=1;
scloud=zeros(2*perc*100,3);
for slength=1:length(oct(1,1,:))-1
for polygon=1:faces
    it=(slength-1)*faces+polygon;
    sss=sprintf('Genetaring Surface Cloud...%3.1f %%', it/perc);
        set(handles.timebar_text,'String',sss);
        drawnow update;
p1=oct(polygon,:,slength);
p2=oct(polygon+1,:,slength);
p3=oct(polygon+1,:,slength+1);
p4=oct(polygon,:,slength+1);
p=[p1;p2;p3;p4];
[or,in]=min([norm(p1);norm(p2);norm(p3);norm(p4)]);
p=circshift(p,-in+1);
dx=p(2,:)-p(1,:);
dy=p(4,:)-p(1,:);
x1=p(1,:)/2+dx*rand;
y1=p(1,:)/2+dy*rand;
pp1=x1+y1;
x2=p(1,:)/2+dx*rand;
y2=p(1,:)/2+dy*rand;
pp2=x2+y2;
scloud(pl,:)=pp1;
pl=pl+1;
scloud(pl,:)=pp2;
pl=pl+1;
end
end

function cloud=gen_cloud(handles,oct)
set(handles.timebar_text,'Visible','on','String','Generating Internal Cloud');
drawnow update;
faces=length(oct(:,1,1));
perc=(length(oct(1,1,:)))*faces/100;
oct=cat(1, oct, oct(1,:,:));
pl=1;
j=2;    % j*faces is the number of points in every spital slice
pp=zeros(j*perc*100,3);

for slength=1:length(oct(1,1,:))-1
for polygon=1:faces-1
    it=(slength-1)*faces+polygon;
    sss=sprintf('Genetaring Internal Cloud...%3.1f %%', it/perc);
        set(handles.timebar_text,'String',sss);
        drawnow update;
    apenanti=mod(floor(faces/2)+polygon+1,faces);
    if apenanti==0,apenanti=faces;end
p1=oct(polygon+1,:,slength);
p2=oct(polygon,:,slength);
p3=oct(apenanti,:,slength);
p4=oct(apenanti,:,slength+1);
p5=oct(polygon+1,:,slength+1);
p6=oct(polygon,:,slength+1);
p=[p1;p2;p3;p4;p5;p6];

dy=p2-p1;
dz=p3-p1;
dx=p5-p1;

for k=1:j
dyp=dy*rand;
dxp=dx*rand;
dzn=norm(dy-dyp)*norm(dz)/norm(dy);
dzp=dz./norm(dz)*rand*dzn;
pp(pl,:)=p(1,:)+dzp+dxp+dyp;
pl=pl+1;
end
end
end
cloud=pp;


text:
function stochastic_rk_test ( )

%*****************************************************************************80
%
%% STOCHASTIC_RK_TEST tests the STOCHASTIC_RK library.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 June 2010
%
%  Author:
%
%    John Burkardt
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'STOCHASTIC_RK_TEST\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Test the STOCHASTIC_RK library.\n' );

  stochastic_rk_test01 ( );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'STOCHASTIC_RK_TEST\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end


text:
function	[W ,Ydim, Xdim, Dtau] = get_estimated_weight(Model,parm,wmode);
% return Weight matrix from 'Model'
%  [W ,Ydim, Xdim, Dtau] = get_estimated_weight(Model,parm,wmode);
% W : Weight matrix : 2D-matrix [Ydim x (Xdim * Dtau)]
% Dtau : time embedding dim
% Ydim : Output space dim
% Xdim : Input space dim
%   To get temporal filter shape of Weight matrix
% Wd = reshape( W, [Ydim, Xdim, Dtau]);
% Wd(n,m,:) : Weight for n-th output & m-th input data
%
% 2008-5-20 Masa-aki Sato

if isfield(parm,'Dtau')
	Dtau  = parm.Dtau;
else
	Dtau  = 1;
end

M_all = Model.M_all;
Ydim  = size(Model.W,1);
Xdim  = M_all/Dtau;

if isfield(Model,'ix_act')
	% Active index
	ix_act = Model.ix_act;

	W = zeros(Ydim ,M_all);
	W(:,ix_act) = Model.W;
else
	W =  Model.W;
end

if exist('wmode','var') && wmode==0, return; end;

if length(parm.xmean) == Xdim,
	parm.xmean = repmat(parm.xmean ,[Dtau 1]);
	parm.xnorm = repmat(parm.xnorm ,[Dtau 1]);
end

% Scale back by normalization factor
if isfield(parm,'xnorm') & isfield(parm,'ynorm')
	W = (parm.ynorm(:)*(1./parm.xnorm(:)')) .* W;
end

author: KamitaniLab

repo: GenericObjectDecoding


text:
clear all; close all; clc

% training & testing set sizes
n1=100;  % training set size
n2=50;   % test set size

% random ellipse 1 centered at (0,0)
x=randn(n1+n2,1)-2;
y=0.5*randn(n1+n2,1);

x5=2*randn(n1+n2,1)+1;
y5=0.5*randn(n1+n2,1);

% random ellipse 2 centered at (1,-2)
x2=randn(n1+n2,1)+2;
y2=0.2*randn(n1+n2,1)-2;

% rotate ellipse 2 by theta
theta=pi/4;
A=[cos(theta) -sin(theta); sin(theta) cos(theta)];
x3=A(1,1)*x2+A(1,2)*y2;
y3=A(2,1)*x2+A(2,2)*y2;

subplot(2,2,1)
plot(x(1:n1),y(1:n1),'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8), hold on   % [0.49 1 .63]
plot(x3(1:n1),y3(1:n1),'bo','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8)
axis([-6 6 -2 2]), set(gca,'Fontsize',[14])

subplot(2,2,2)
plot(x(1:70),y(1:70),'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8), hold on   % [0.49 1 .63]
plot(x3(1:70),y3(1:70),'bo','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8)
plot(x(71:100),y(71:100),'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0 1 0.2],...
                'MarkerSize',8), hold on   % [0.49 1 .63]
plot(x3(71:100),y3(71:100),'bo','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.9 0 1],...
                'MarkerSize',8)
axis([-6 6 -2 2]), set(gca,'Fontsize',[14])

subplot(2,2,3)
plot(x5(1:n1),y5(1:n1),'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8), hold on   % [0.49 1 .63]
plot(x3(1:n1),y3(1:n1),'bo','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8)
axis([-6 6 -2 2]), set(gca,'Fontsize',[14])

subplot(2,2,4)
plot(x5(1:70),y5(1:70),'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8), hold on   % [0.49 1 .63]
plot(x3(1:70),y3(1:70),'bo','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.8 0.8 0.8],...
                'MarkerSize',8)
plot(x5(71:100),y5(71:100),'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0 1 0.2],...
                'MarkerSize',8), hold on   % [0.49 1 .63]
plot(x3(71:100),y3(71:100),'bo','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.9 0 1],...
                'MarkerSize',8)
axis([-6 6 -2 2]), set(gca,'Fontsize',[14])

%%
figure(2)
% random ellipse 1 centered at (0,0)
subplot(2,2,1)
n1=300;  % training set size
x1=1.5*randn(n1,1)-1.5;
y1=1.2*randn(n1,1)+(x1+1.5).^2-7;
x2=1.5*randn(n1,1)+1.5;
y2=1.2*randn(n1,1)-(x2-1.5).^2+7;

plot(x1,y1,'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0 1 0.2],...
                'MarkerSize',8), hold on
plot(x2,y2,'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.9 0 1],...
                'MarkerSize',8)
axis([-6 6 -12 12]), set(gca,'Fontsize',[14])

subplot(2,2,2)
r=7+randn(n1,1);
th=2*pi*rand(n1,1);
xr=r.*cos(th);
yr=r.*sin(th);
x5=randn(n1,1);
y5=randn(n1,1);
plot(xr,yr,'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0 1 0.2],...
                'MarkerSize',8), hold on
plot(x5,y5,'ro','Linewidth',[1],'MarkerEdgeColor','k',...
                'MarkerFaceColor',[0.9 0 1],...
                'MarkerSize',8)
axis([-10 10 -10 10]), set(gca,'Fontsize',[14])

author: dynamicslab


text:
function res=NODDI_erfi(x)
% %erfi(x). The Imaginary error function, as it is defined in Mathematica
% %erfi(z)==erf(iz)/i (z could be complex) using
% %the incomplete gamma function in matlab: gammainc
% %Using "@": erfi = @(x) real(-sqrt(-1).*sign(x).*gammainc(-x.^2,1/2))
% %Note: limit(x->0) erfi(x)/x -> 2/sqrt(pi)
%
% %Example 1:
% x=linspace(0.001,6,100);
% y=exp(-x.^2).*erfi(x)./2./x;
% figure(1), clf;plot(x,y*sqrt(pi))
%
% %Example 2:
% [x,y]=meshgrid(linspace(-3,3,180),linspace(-3,3,180));
% z=x+i*y;
% figure(1), clf;contourf(x,y,log(erfi(z)))
% axis equal;axis off

% MATLAB only:
% xc=5.7;%cut for asymptotic approximation (when x is real)
% res=~isreal(x).*(-(sqrt(-x.^2)./(x+isreal(x))).*gammainc(-x.^2,1/2))+...
%     isreal(x).*real(-sqrt(-1).*sign(x).*((x<xc).*gammainc(-x.^2,1/2))+...
%     (x>=xc).*exp(x.^2)./x/sqrt(pi));

try % FASTER AND COMPATIBLE WITH BOTH MATLAB AND OCTAVE:
    res = Faddeeva_erfi(x);
catch
    if ~moxunit_util_platform_is_octave
    xc=5.7;%cut for asymptotic approximation (when x is real)
    res=~isreal(x).*(-(sqrt(-x.^2)./(x+isreal(x))).*gammainc(-x.^2,1/2))+...
        isreal(x).*real(-sqrt(-1).*sign(x).*((x<xc).*gammainc(-x.^2,1/2))+...
        (x>=xc).*exp(x.^2)./x/sqrt(pi));
    else
        error('Faddeeva_erfi was not build correctly. run Faddeeva_build.m')
    end
end

author: qMRLab

repo: qMRLab

save_path: github-repos/MATLAB/qMRLab-qMRLab


text: %END Mapping overload

author: marianux

repo: ecg-kit

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


text:
function out = isdecay(f)
%ISDECAY   Test if a SINGFUN decays faster than a single root at endpoints.
%   ISDECAY(F) returns a 1x2 row vector each of which indicates whether F
%   vanishes at one of the endpoints faster than a single root. An entry TRUE is
%   returned if F has a boundary root with multiplicity larger than one, FALSE
%   otherwise.
%
%   Note that ISDECAY is designed for and expected to be called only by UNBNDFUN
%   class for handling functions defined on unbounded domains.

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

out = isdecay(f.smoothPart);

%% Left endpoint:

if ( ~out(1) && f.exponents(1) > 1 )
    out(1) = 1;
end

%% Right endpoint:

if ( ~out(2) && f.exponents(2) > 1 )
    out(2) = 1;
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function E = feval(disc, location, direction)
%FEVAL   Evaluation functional for CHEBCOLLOC.
%   FEVAL(DISC, LOC, DIRN) returns a functional that evaluates the Chebyshev
%   polynomial represented by a COLLOC discretization at the given point LOC as
%   approached from the direction DIRN (either +1 or -1).

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

n = disc.dimension;

% Find the collocation points and create an empty functional.
[x, ignored, v] = functionPoints(disc);
offset = cumsum([0 ; n(:)]);
N = offset(end);
E = zeros(1, N);

% Only one subinterval creates nonzero entries in E.
intnum = disc.whichInterval(location, direction);
active = offset(intnum) + (1:n(intnum));
E(1, active) = barymat(location, x(active), v(active));

end


text:
function [mm] = nm2mm(nm)
% Convert length from nanometers to millimeters.
% Chad A. Greene 2012
mm = nm*0.000001;


text:
%% Copyright (C) 2014, 2016-2017, 2019, 2022 Colin B. Macdonald
%% Copyright (C) 2020 Mike Miller
%% Copyright (C) 2020 Fernando Alvarruiz
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy 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 software 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 software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @defun mat_rclist_asgn (@var{A}, @var{r}, @var{c}, @var{B})
%% Private helper routine for sym array assigment using lists.
%%
%% @code{(R(i),C(i))} specify entries of the matrix @var{A}.
%% We execute @code{A(R(i),C(i)) = B(i)}.
%%
%% Notes:
%% @itemize
%% @item  @var{B} is accessed with linear indexing.
%% @item  @var{B} might be a scalar, used many times.
%% @item  @var{A} might need to get bigger, if so it will be padded
%%        with zeros.
%% @end itemize
%%
%% @end defun

function z = mat_rclist_asgn(A, r, c, B)

  if (isempty (r) && isempty (c) && (isempty (B) || isscalar (B)))
    z = A;
    return
  end

  if ~( isvector(r) && isvector(c) && (length(r) == length(c)) )
    error('this routine is for a list of rows and cols');
  end

  if ((numel(B) == 1) && (numel(r) > 1))
    B = repmat(B, size(r));
  end
  if (length(r) ~= numel(B))
    error('not enough/too much in B')
  end

  % Easy trick to copy A into larger matrix AA:
  %    AA = sp.Matrix.zeros(n, m)
  %    AA[0, 0] = A
  % Also usefil: .copyin_matrix

  cmd = { '(A, r, c, B) = _ins'
          '# B linear access fix, transpose for sympy row-based'
          'if B is None or not B.is_Matrix:'
          '    B = sp.Matrix([[B]])'
          'BT = B.T'
          '# make a resized copy of A, and copy existing stuff in'
          'if isinstance(A, list):'
          '    assert len(A) == 0, "unexpectedly non-empty list: report bug!"'
          '    n = max(max(r) + 1, 1)'
          '    m = max(max(c) + 1, 1)'
          '    AA = [[0]*m for i in range(n)]'
          'elif A is None or not isinstance(A, MatrixBase):'
          '    # we have non-matrix, put in top-left'
          '    n = max(max(r) + 1, 1)'
          '    m = max(max(c) + 1, 1)'
          '    AA = [[0]*m for i in range(n)]'
          '    AA[0][0] = A'
          'else:'
          '    # build bigger matrix'
          '    n = max(max(r) + 1, A.rows)'
          '    m = max(max(c) + 1, A.cols)'
          '    AA = [[0]*m for i in range(n)]'
          '    # copy current matrix in'
          '    for i in range(A.rows):'
          '        for j in range(A.cols):'
          '            AA[i][j] = A[i, j]'
          '# now insert the new bits from B'
          'for i, (r, c) in enumerate(zip(r, c)):'
          '    AA[r][c] = BT[i]'
          'return sp.Matrix(AA),' };

  rr = num2cell(int32(r-1));
  cc = num2cell(int32(c-1));
  z = pycall_sympy__ (cmd, A, rr, cc, B);

  % a simpler earlier version, but only for scalar r,c
  %cmd = { '(A, r, c, b) = _ins'
  %        'if not A.is_Matrix:'
  %        '    A = sp.Matrix([[A]])'
  %        'AA = sp.Matrix.zeros(max(r+1, A.rows), max(c+1, A.cols))'
  %        'AA[0, 0] = A'
  %        'AA[r, c] = b'
  %        'return AA,' };
end

repo: octsympy


text:
% Calculate the eigenvalues of massive 3x3 real symmetric matrices.
% Computation is based on matrix operation and GPU computation is
% supported.
% Syntax:
% [eigenvalue1,eigenvalue2,eigenvalue3] = eigenvaluefield33( a11, a12, a13, a22, a23, a33)
% a11, a12, a13, a22, a23 and a33 specify the symmetric 3x3 real symmetric
% matrices as:
%   a11 a12 a13
% [ a12 a22 a13 ]
%   a13 a23 a33
% These six inputs must have the same size. They can be 2D, 3D or any
% dimension. The outputs eigenvalue1, eigenvalue2 and eigenvalue3 will
% follow the size and dimension of these inputs. Owing to the use of
% trigonometric functions, the inputs must be double to maintain the
% accuracy.
%
% eigenvalue1, eigenvalue2 and eigenvalue3 are the unordered resultant
% eigenvalues. They are solved using the cubic equation solver, see
% http://en.wikipedia.org/wiki/Eigenvalue_algorithm
%
% The peak memory consumption of the method is about 1.5 times of the total
% of all inputs, in addition to the original inputs. GPU computation is
% used automatically if all inputs are matlab GPU arrays.
%
% Author: Max W.K. Law
% Email:  max.w.k.law@gmail.com
% Page:   http://www.cse.ust.hk/~maxlawwk/
%
function [b,j,d] = eigenvaluefield33( a11, a12, a13, a22, a23, a33)
%    multiprocess;
%    b=a11*0;
%    j=a11*0;
%    d=a11*0;
%    parfor i=1:numel(a11)
%        [~,l]=eig([a11(i) a12(i) a13(i); a12(i) a22(i) a23(i); a13(i) a23(i) a33(i)]);
%        b(i)=l(1,1);
%        j(i)=l(2,2);
%        d(i)=l(3,3);
%    end
%    return;

    ep=1e-50;
    b=double(a11)+ep;
    d=double(a22)+ep;
    j=double(a33)+ep;

    c=-(double(a12).^2 + double(a13).^2 + double(a23).^2 - b.*d - d.*j - j.*b);
    d=-(b.*d.*j - double(a23).^2.*b - double(a12).^2.*j - double(a13).^2.*d + 2*double(a13).*double(a12).*double(a23));

    b=-double(a11) - double(a22) - double(a33) - ep - ep -ep;

    d = d + ((2*b.^3) - (9*b.*c))/27;

%     c=c-(b.^2)/3;
%     c=c.^3;
%     c=c/27;
%     c=(d.^2/4-(d.^2/4 + c));

%%%%    c=(d.^2/4-(d.^2/4 + ((3 * c - (b.^2))/3).^3/27));
    c=(b.^2)/3 - c;
    c=c.^3;
    c=c/27;
    c=max(c,0);
    c=realsqrt(c);

    j=c.^(1/3);
    c=c+(c==0);
    d=-d/2./c;
    d=min(d, 1);
    d=max(d, -1);

    d=real(acos(d)/3);
%    d=real(acos(-(d/2./c))/3);
    c=j.*cos(d);
    d=j.*sqrt(3).*sin(d);
    b=-b/3;

    j = single(-c-d+b);
    d = single(-c+d+b);

    b = single(2*c+b);

end

% Old version
%     ep=1e-20;
%     b=double(a11)+ep;
%     d=double(a22)+ep;
%     j=double(a33)+ep;
%
%     c=-double(double(a12).^2 + double(a13).^2 + double(a23).^2 - b.*d - d.*j - j.*b);
%     d=-(b.*d.*j - double(a23).^2.*b - double(a12).^2.*j - double(a13).^2.*d + 2*double(a13).*double(a12).*double(a23));
%
%     b=-double(a11) - double(a22) - double(a33) - ep - ep -ep;
%
%
%     d = ((2*b.^3) - (9*b.*c) + (27*d))/27;
%     %clear d;
%     %x = (((3*c) - (b.^2))/3);
%
%     %c = (d^2/4 + (((3*c) - (b.^2))/3).^3/27);
%
%     %clear x;
%     c=(d.^2/4-(d.^2/4 + (((3*c) - (b.^2))/3).^3/27));
%     c(c<0)=0;
%     c=realsqrt(c);
%     %clear c;
%
%
%     j=c.^(1/3);
%     d=real(acos(-(d/2./c))/3);
%     c=j.*cos(d);
%     d=j.*sqrt(3).*sin(d);
%     b=-b/3;
%
%
%     j = single(-c-d+b);
%     d = single(-c+d+b);
%
%     b = single(2*c+b);


text:
function value = torus_square_volume_3d ( r1, r2 )

%*****************************************************************************80
%
%% TORUS_SQUARE_VOLUME_3D returns the volume of a square torus in 3D.
%
%  Integration region:
%
%    Points (X,Y,Z) such that:
%
%      R1 - R2 <= SQRT ( X**2 + Y**2 ) <= R1 + R2,
%      -R2 <= Z <= R2.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 May 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, real R1, R2, the two radii that define the torus.
%
%    Output, real TORUS_SQUARE_VOLUME_3D, the volume of the torus.
%
  value = 8.0E+00 * pi * r1 * r2 * r2;

  return
end