text:
%CCODEFUNCTIONSTRING Converts a symbolic expression into a C-code function
%
% [FUNSTR, HDRSTR] = ccodefunctionstring(SYMEXPR, ARGLIST) returns a string
% representing a C-code implementation of a symbolic expression SYMEXPR.
% The C-code implementation has a signature of the form:
%
%         void funname(double[][n_o] out, const double in1,
%           const double* in2, const double[][n_i] in3);
%
% depending on the number of inputs to the function as well as the
% dimensionality of the inputs (n_i) and the output (n_o).
% The whole C-code implementation is returned in FUNSTR, while HDRSTR
% contains just the signature ending with a semi-colon (for the use in
% header files).
%
% Options::
% 'funname',name    Specify the name of the generated C-function. If
%                   this optional argument is omitted, the variable name
%                   of the first input argument is used, if possible.
% 'output',outVar   Defines the identifier of the output variable in the C-function.
% 'vars',varCells   The inputs to the C-code function must be defined as a cell array. The
%                   elements of this cell array contain the symbolic variables required to
%                   compute the output. The elements may be scalars, vectors or matrices
%                   symbolic variables. The C-function prototype will be composed accoringly
%                   as exemplified above.
% 'flag',sig        Specifies if function signature only is generated, default (false).
%
% Example::
%          % Create symbolic variables
%          syms q1 q2 q3
%
%          Q = [q1 q2 q3];
%          % Create symbolic expression
%          myrot = rotz(q3)*roty(q2)*rotx(q1)
%
%          % Generate C-function string
%          [funstr, hdrstr] = ccodefunctionstring(myrot,'output','foo', ...
%          'vars',{Q},'funname','rotate_xyz')
%
% Notes::
% - The function wraps around the built-in Matlab function 'ccode'. It does
%   not check for proper C syntax. You must take care of proper
%   dimensionality of inputs and outputs with respect to your symbolic
%   expression on your own. Otherwise the generated C-function may not
%   compile as desired.
%
% Author::
%  Joern Malzahn, (joern.malzahn@tu-dortmund.de)
%
% See also ccode, matlabFunction.

% Copyright (C) 2012-2018, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB 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.
%
% RTB 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 RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

function [funstr hdrstr] = ccodefunctionstring(f,varargin)

% option defaults
opt.funname = inputname(1);
opt.output{1} = zeros(size(f));
opt.outputName{1} = inputname(1);
opt.flag = 0;

if isempty(opt.outputName{1})
    opt.outputName{1} = 'myout';
end
opt.vars = {};

% tb_optparse is not applicable here,
% since handling cell inputs and extracting input variable names is
% required.
% Thus, scan varargin manually:
if mod(nargin,2)==0
    error('CodeGenerator:codefunctionstring:wrongArgumentList',...
        'Wrong number of elements in the argument list.');
end
for iArg = 1:2:nargin-1
    switch lower(varargin{iArg})
        case 'funname'
            opt.funname = varargin{iArg+1};
        case 'output'
            if ~isempty(varargin{iArg+1})
                opt.outputName{1} = varargin{iArg+1};
            end
        case 'vars'
            opt.vars = varargin{iArg+1};
        case 'flag'
            opt.flag = varargin{iArg+1};
        otherwise
            error('ccodefunctionstring:unknownArgument',...
                ['Argument ',inputname(iArg),' unknown.']);
    end
end

nOut = numel(opt.output);
nIn = numel(opt.vars);

%% Function signature
funstr = sprintf('void %s(', opt.funname);
initstr = '';

% outputs
for iOut = 1:nOut
    tmpOutName = opt.outputName{iOut};
    tmpOut = opt.output{iOut};

    if ~isscalar(tmpOut);
        funstr = [funstr, sprintf('double %s[][%u]', tmpOutName, size(tmpOut,1) ) ];
        for iRow = 1:size(tmpOut,1)
            for iCol = 1:size(tmpOut,2)
                initstr = sprintf(' %s %s[%u][%u]=0;\n',initstr,tmpOutName,iCol-1,iRow-1);
            end
        end
    else
        funstr = [funstr, sprintf('double %s', tmpOutName ) ];
    end

    % separate argument list by commas
    if ( iOut ~= nOut ) || ( nIn > 0 )
        funstr = [funstr,', '];
    end

end

% inputs
for iIn = 1:nIn
    tmpInName = ['input',num2str(iIn)];%opt.varsName{iIn};
    tmpIn = opt.vars{iIn};

    % treat different dimensionality of input variables
    if isscalar(tmpIn)
        funstr = [funstr, sprintf('const double %s', tmpInName ) ];
    elseif isvector(tmpIn)
        funstr = [funstr, sprintf('const double* %s', tmpInName ) ];
    elseif ismatrix(tmpIn)
        funstr = [funstr, sprintf('const double %s[][%u]', tmpInName, size(tmpIn,2) ) ];
    else
        error('ccodefunctionstring:UnsupportedOutputType', 'Unsupported datatype for %s', tmpOutName)
    end

    % separate argument list by commas
    if ( iIn ~= nIn )
        funstr = [funstr,', '];
    end

end
funstr = [funstr,sprintf('%s', ')')];

% finalize signature for the use in header files
if nargout > 1
    hdrstr = [funstr,sprintf('%s', ';')];
end
if opt.flag
    return;         %% STOP IF FLAG == TRUE
end

% finalize signature for use in function definition
funstr = [funstr,sprintf('%s', '{')];
funstr = sprintf('%s\n%s',funstr,sprintf('%s', ' ') ); % empty line

%% Function body
% input paramter expansion
for iIn = 1:nIn
    tmpInName = ['input',num2str(iIn)];%opt.varsName{iIn};
    tmpIn = opt.vars{iIn};

    % for scalars
    %   -> do nothing

    % for vectors
    if ~isscalar(tmpIn) && isvector(tmpIn)
        nEl = numel(tmpIn);
        for iEl = 1:nEl
            funstr = sprintf('%s\n%s',...
                funstr,...
                sprintf('  double %s = %s[%u];', char(tmpIn(iEl)), tmpInName,iEl-1 ));
        end

        % for matrices
    elseif ~isscalar(tmpIn) && ~isvector(tmpIn) && ismatrix(tmpIn)
        nRow = size(tmpIn,1);
        nCol = size(tmpIn,2);
        for iRow = 1:nRow
            for iCol = 1:nCol

                funstr = sprintf('%s\n%s',...
                    funstr,...
                    sprintf('  double %s%u%u = %s[%u][%u];', char(tmpIn(iRow,iCol)), iRow, iCol, tmpInName{iIn},iRow-1,iCol-1 ));
            end
        end
    end

end

funstr = sprintf('%s\n%s',...
    funstr,...
    sprintf('%s', ' ') );
funstr = sprintf('%s\n%s',...
    funstr,...
    sprintf('%s\n\n', initstr) );

% Actual code
% use f.' here, because of column/row indexing in C
codestr = '';
if ~isequal(f, sym(zeros(size(f))))
    eval([opt.outputName{1}, ' = f.''; codestr = ccode(',opt.outputName{1},');'])
end

if isscalar(f)
    % in the case of scalar expressions the resulting ccode always
    % begins with '  t0'. Replace that with the desired name.
    codestr = strrep(codestr,'t0',opt.outputName{1});
end

funstr = sprintf('%s\n%s',...
    funstr,...
    codestr );

funstr = sprintf('%s\n%s',...
    funstr,sprintf('%s', '}') );
funstr = sprintf('%s\n%s',...
    funstr,sprintf('%s', ' ') ); % empty line

author: petercorke

repo: robotics-toolbox-matlab


text:
function [ozf] = kip2ozf(kip)
% Convert force from kip to ounces-force.
% Chad A. Greene 2012
ozf = kip*16000;

author: Sable

repo: mcbench-benchmarks


text:
classdef VademecumPtensorComputer < VademecumVariablesComputer

    properties (Access = private)
       pNorm
    end

    methods (Access = public)

        function obj = VademecumPtensorComputer(d)
            obj.init(d);
            obj.pNorm = d.pNorm;
        end

    end

    methods (Access = protected)

        function computeAmplificators(obj,imx,imy)
            obj.createAmplificatorInput();
            d = obj.amplificatorInput;
            d.pNorm = obj.pNorm;
            ga = AmplificatorComponentsCalculator(d);
            ga.compute();
            obj.vademecumData.variables{imx,imy}.Ptensor = ga.Phomog;
            obj.vademecumData.monomials = ga.monom;
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function y = r8mat_mv ( m, n, a, x )

%*****************************************************************************80
%
%% R8MAT_MV multiplies a matrix times a vector.
%
%  Discussion:
%
%    In FORTRAN90, this operation can be more efficiently carried
%    out by the command
%
%      Y(1:M) = MATMUL ( A(1:M,1:N), X(1:N) )
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns of the matrix.
%
%    Input, real A(M,N), the M by N matrix.
%
%    Input, real X(N), the vector to be multiplied by A.
%
%    Output, real Y(M), the product A*X.
%
  y(1:m) = a(1:m,1:n) * x(1:n);

  return
end

author: johannesgerer

repo: jburkardt-m


text:
%kkcpfromval 'Copy Value Segment Into One Segment of Output'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kcpfromval.pane file
%
% Parameters:
% InputFile: i 'Input', required: 'Source input file'
% OutputFile: o 'Output ', required: 'output file'
% Toggle: val 'Value', default: 0: 'If -val flag is selected, operate on Value segment'
% Toggle: map 'Map', default: 0: 'If -map flag is selected, operate on map segment'
% Toggle: mask 'Mask', default: 0: 'If -mask flag is selected, operate on Mask segment'
% Toggle: loc 'Location', default: 0: 'If -loc flag is selected, operate on Location segment'
% Toggle: time 'Time', default: 0: 'If -time flag is selected, operate on Time segment'
%
% Example: o = kkcpfromval(i, {'i','';'o','';'val',0;'map',0;'mask',0;'loc',0;'time',0})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kcpfromval - Copy Value Segment Into One Segment of Output
%
%  DESCRIPTION
% This routine copies the five dimensional value segment from the source
% object to the specified segment specified in the
% destination_object. The data will be copied into the lowest order
% dimension of the destination segment, then the next order will be
% used, and the next, and so forth, until all the value data is copied.
% If the dimensionality of the destination is less than five, then the
% last dimension of the destination segment will have all the higher
% order dimensions rolled into it.
% If segment is specified to be a polymorphic segment by setting one of
% the toggles (value, location, time, mask, map) then the segment
% dimensionalities and index orders specified by the polymorphic model
% will be used. If the segment is not one of the polymorphic segments,
% then the dimensionality of the value segment will be used, and the
% segment will be given an index order of width, height, depth, time, and
% elements.
% Only the size and data type attribute will be changed, all others will
% not be transferred to the destination segment.  If the segment does
% not exist in the destination and is not a polymorphic segment the
% dimension and index order will be set.  If it is a polymorphic segment
% the default polymorphic dimension and index order will be used.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
% Results guaranteed only if dimension of destination segment is 5.
% Other dimensions are not tested and may produce poor results.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkcpfromval(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kkcpfromval(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'o', '__output';'val', 0;'map', 0;'mask', 0;'loc', 0;'time', 0};
maxval={0,0,0,0,0,0,0};
minval={0,0,0,0,0,0,0};
istoggle=[0,0,1,1,1,1,1];
was_set=istoggle * 0;
paramtype={'InputFile','OutputFile','Toggle','Toggle','Toggle','Toggle','Toggle'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'kcpfromval"  '],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function varargout=spm_figure(varargin)
% Setup and callback functions for Graphics window
% FORMAT varargout=spm_figure(varargin)
%       - An embedded callback, multi-function function
%       - For detailed programmers comments, see format specifications
%         in main body of code
%_______________________________________________________________________
%
% spm_figure creates and manages the 'Graphics' window. This window and
% these facilities may be used independently of SPM, and any number of
% Graphics windows my be used within the same MATLAB session. (Though
% only one SPM 'Graphics' 'Tag'ed window is permitted.
%
% The Graphics window is provided with a menu bar at the top that
% facilitates editing and printing of the current graphic display,
% enabling interactive editing of graphic output prior to printing
% (e.g. selection of color maps, deleting, moving and editing graphics
% objects or adding text). (This menu is also provided as a figure
% background "ContextMenu" - right-clicking on the figure background
% should bring up the menu.)
%
% Print: Graphics windows with multi-page axes are printed page by page.
%
% Clear: Clears the Graphics window. If in SPM usage (figure 'Tag'ed as
% 'Graphics') then all SPM windows are cleared and reset.
%
% Colormap options:
% * gray, hot, pink: Sets the colormap to its default values and loads
%                 either a grayscale, 'hot metal' or color map.
% * gray-hot, etc: Creates a 'split' colormap {128 x 3 matrix}.
%          The lower half is a gray scale and the upper half
%          is 'hot metal' or 'pink'.  This color map is used for
%      viewing 'rendered' SPMs on a PET, MRI or other background images
%
% Colormap effects:
% * Invert: Inverts (flips) the current color map.
% * Brighten and Darken: Brighten and Darken the current colourmap
%      using the MATLAB BRIGHTEN command, with  beta's of +0.2 and -0.2
%      respectively.
%
% Editing: Right button ('alt' button) cancels operations
% * Cut  : Deletes the graphics object next selected (if deletable)
%          Select with middle mouse button to delete blocks of text,
%          or to delete individual elements from a plot.
% * Move : To re-position a text, uicontrol or axis object using a
%          'drag and drop' implementation (i.e. depress - move - release)
%          Using the middle 'extend' mouse button on a text object moves
%          the axes containing the text - i.e. blocks of text.
% * Size : Re-sizes the text, uicontrol or axis object next selected
%          {left button - decrease, middle button  - increase} by a factor
%          of 1.24 (or increase/decrease FontSize by 2 dpi)
% * Text : Creates an editable text widget that produces a text object as
%          its CallBack.
%          The text object is provided with a ContextMenu, obtained by
%          right-clicking ('alt') on the text, allowing text attributes
%          to be changed. Alternatively, the edit facilities on the window
%          menu bar or ContextMenu can be used.
% * Edit : To edit text, select a text object with the circle cursor,
%          and edit the text in the editable text widget that appears.
%          A middle 'extend' mouse click places a context menu on the text
%          object, facilitating easy modification of text atributes.
%
% For SPM usage, the figure should be 'Tag'ed as 'Graphics'.
%
% For SPM power users, and programmers, spm_figure provides utility
% routines for using the SPM graphics interface. Of particular use are
% the GetWin, FindWin and Clear functions See the embedded callback
% reference in the main body of spm_figure, below the help text.
%
% See also: spm_print, spm_clf
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Andrew Holmes
% $Id$

%=======================================================================
% - FORMAT specifications for embedded CallBack functions
%=======================================================================
%( This is a multi function function, the first argument is an action  )
%( string, specifying the particular action function to take. Recall   )
%( MATLAB's command-function duality: `spm_figure Create` is           )
%( equivalent to `spm_figure('Create')`.                               )
%
% FORMAT F = spm_figure
% [ShortCut] Defaults to Action 'Create'
%
% FORMAT F = spm_figure(F) - numeric F
% [ShortCut] Defaults to spm_figure('CreateBar',F)
%
% FORMAT F = spm_figure('Create',Tag,Name,Visible)
% Create a full length WhiteBg figure 'Tag'ed Tag (if specified),
% with a ToolBar and background context menu.
% Equivalent to spm_figure('CreateWin','Tag') and spm_figure('CreateBar')
% Tag     - 'Tag' string for figure.
% Name    - Name for window
% Visible - 'on' or 'off'
% F   - Figure used
%
% FORMAT F = spm_figure('FindWin',F)
% Finds window with 'Tag' or figure numnber F - returns empty F if not found
% F - (Input)  Figure to use [Optional] - 'Tag' string or figure number.
%   - Defaults to 'Graphics'
% F - (Output) Figure number (if found) or empty (if not).
%
% FORMAT F = spm_figure('GetWin',Tag)
% Like spm_figure('FindWin',Tag), except that if no such 'Tag'ged figure
% is found and 'Tag' is recognized, one is created. Further, the "got"
% window is made current.
% Tag   - Figure 'Tag' to get, defaults to 'Graphics'
% F - Figure number (if found/created) or empty (if not).
%
% FORMAT F = spm_figure('ParentFig',h)
% Finds window containing the object whose handle is specified
% h - Handle of object whose parent figure is required
%   - If a vector, then first object handle is used
% F - Number or parent figure
%
% FORMAT spm_figure('Clear',F,Tags)
% Clears figure, leaving ToolBar (& other objects with invisible handles)
% Optional third argument specifies 'Tag's of objects to delete.
% If figure F is 'Tag'ged 'Interactive' (SPM usage), then the window
% name and pointer are reset.
% F - 'Tag' string or figure number of figure to clear, defaults to gcf
% Tags  - 'Tag's (string matrix or cell array of strings) of objects to delete
%         *regardless* of 'HandleVisibility'. Only these objects are deleted.
%         '!all' denotes all objects
%
%
% FORMAT spm_figure('Print',F)
% F - [Optional] Figure to print. ('Tag' or figure number)
%     Defaults to figure 'Tag'ed as 'Graphics'.
%     If none found, uses CurrentFigure if avaliable.
% If objects 'Tag'ed 'NextPage' and 'PrevPage' are found, then the
% pages are shown and printed in order. In breif, pages are held as
% separate axes, with ony one 'Visible' at any one time. The handles of
% the "page" axes are stored in the 'UserData' of the 'NextPage'
% object, while the 'PrevPage' object holds the current page number.
% See spm_help('!Disp') for details on setting up paging axes.
%
% FORMAT [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',hPage)
% SPM pagination function: Makes objects with handles hPage paginated
% Creates pagination buttons if necessary.
% hPage                         - Handles of objects to stick to this page
% hNextPage, hPrevPage, hPageNo - Handles of pagination controls
%
% FORMAT spm_figure('TurnPage',move,F)
% SPM pagination function: Turn to specified page
%
% FORMAT spm_figure('DeletePageControls',F)
% SPM pagination function: Deletes page controls
% F - [Optional] Figure in which to attempt to turn the page
%         Defaults to 'Graphics' 'Tag'ged window
%
% FORMAT n = spm_figure('#page')
% Returns the current number of pages.
%
% FORMAT n = spm_figure('CurrentPage');
% Return the current page number.
%
% FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm)
% Adds watermark to figure windows.
% F - Figure for watermark. Defaults to gcf
% str   - Watermark string. Defaults (missing or empty) to SPM
% Tag   - Tag for watermark axes. Defaults to ''
% Angle - Angle for watermark. Defaults to -45
% Perm  - If specified, then watermark is permanent (HandleVisibility 'off')
%
% FORMAT F = spm_figure('CreateWin',Tag,Name,Visible)
% Creates a full length WhiteBg figure 'Tag'ged Tag (if specified).
% F   - Figure created
% Tag     - Tag for window
% Name    - Name for window
% Visible - 'on' or 'off'
%
% FORMAT WS = spm_figure('GetWinScale')
% Returns ratios of current display dimensions to that of a 1152 x 900
% Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other
% GUI elements.
% (Function duplicated in spm.m, repeated to reduce inter-dependencies.)
%
% FORMAT FS = spm_figure('FontSizes',FS)
% Returns fontsizes FS scaled for the current display.
% FS     - (vector of) Font sizes to scale
%          [default [08,09,11,13,14,6:36]]
%
% FORMAT spm_figure('CreateBar',F)
% Creates toolbar in figure F (defaults to gcf). F can be a 'Tag'
% If the figure is 'Tag'ed as 'Graphics' (SPM usage), then the Print button
% callback is set to attempt to clear an 'Interactive' figure too.
%
% FORMAT spm_figure('ColorMap')
% Callback for "ColorMap" buttons
%
% FORMAT h = spm_figure('GraphicsHandle',F)
% GUI choose object for handle identification. LeftMouse 'normal' returns
% handle, MiddleMouse 'extend' returns parents handle, RightMouse 'alt' cancels.
% F - figure to do a GUI "handle ID" in [Default gcbf]
%_______________________________________________________________________

%-Condition arguments
%-----------------------------------------------------------------------
if (nargin==0), Action = 'Create'; else Action = varargin{1}; end

switch lower(Action), case 'create'
%=======================================================================
% F = spm_figure('Create',Tag,Name,Visible)
%-Condition arguments
if nargin<4, Visible='on'; else Visible=varargin{4}; end
if nargin<3, Name=''; else, Name=varargin{3}; end
if nargin<2, Tag=''; else Tag=varargin{2}; end

F = spm_figure('CreateWin',Tag,Name,Visible);
spm_figure('CreateBar',F);
spm_figure('FigContextMenu',F);
varargout = {F};

case 'findwin'
%=======================================================================
% F=spm_figure('FindWin',F)
% F=spm_figure('FindWin',Tag)
%-Find window: Find window with FigureNumber# / 'Tag' attribute
%-Returns empty if window cannot be found - deletes multiple tagged figs.

if nargin<2, F='Graphics'; else F=varargin{2}; end

shh = get(0,'showhiddenhandles');
set(0,'showhiddenhandles','on');

if isempty(F)
    % Leave F empty
elseif ischar(F)
    % Finds Graphics window with 'Tag' string - delete multiples
    Tag=F;
    F = findobj(get(0,'Children'),'Flat','Tag',Tag);
    if length(F) > 1
        % Multiple Graphics windows - close all but most recent
        close(F(2:end))
        F = F(1);
    end
else
    % F is supposed to be a figure number - check it
    if ~any(F==get(0,'Children')), F=[]; end
end
set(0,'showhiddenhandles',shh);
varargout = {F};

case 'getwin'
%=======================================================================
% F=spm_figure('GetWin',Tag)

if nargin<2, Tag='Graphics'; else Tag=varargin{2}; end
F = spm_figure('FindWin',Tag);

if isempty(F)
    if ischar(Tag)
        switch Tag

            case 'Graphics'
                F = spm_figure('Create','Graphics','Graphics');
            case 'DEM'
                F = spm_figure('Create','DEM','Dynamic Expectation Maximisation');
            case 'DFP'
                F = spm_figure('Create','DFP','Variational filtering');
            case 'FMIN'
                F = spm_figure('Create','FMIN','Function minimisation');
            case 'MFM'
                F = spm_figure('Create','MFM','Mean-field and neural mass models');
            case 'MVB'
                F = spm_figure('Create','MVB','Multivariate Bayes');
            case 'SI'
                F = spm_figure('Create','SI','System Identification');
            case 'PPI'
                F = spm_figure('Create','PPI','Physio/Psycho-Physiologic Interaction');
            case 'Interactive'
                F = spm('CreateIntWin');
            otherwise
                F = spm_figure('Create',Tag,Tag);
        end
    end
else
    set(0,'CurrentFigure',F);
    figure(F);
end
varargout = {F};

case 'parentfig'
%=======================================================================
% F=spm_figure('ParentFig',h)
if nargin<2, error('No object specified'), else h=varargin{2}; end
F = get(h(1),'Parent');
while ~strcmp(get(F,'Type'),'figure'), F=get(F,'Parent'); end
varargout = {F};

case 'clear'
%=======================================================================
% spm_figure('Clear',F,Tags)

%-Sort out arguments
%-----------------------------------------------------------------------
if nargin<3, Tags=[]; else Tags=varargin{3}; end
if nargin<2, F=get(0,'CurrentFigure'); else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end

%-Clear figure
%-----------------------------------------------------------------------
if isempty(Tags)
    %-Clear figure of objects with 'HandleVisibility' 'on'
    pos = get(F,'Position');
    delete(findobj(get(F,'Children'),'flat','HandleVisibility','on'));
    drawnow
    set(F,'Position',pos);

    %-Reset figures callback functions
    zoom(F,'off');
    rotate3d(F,'off');
    set(F,'KeyPressFcn','',...
        'WindowButtonDownFcn','',...
        'WindowButtonMotionFcn','',...
        'WindowButtonUpFcn','')
    %-If this is the 'Interactive' window, reset name & UserData
    if strcmp(get(F,'Tag'),'Interactive')
        set(F,'Name','','UserData',[]), end
else
    %-Clear specified objects from figure
    cSHH = get(0,'ShowHiddenHandles');
    set(0,'ShowHiddenHandles','on')
    if ischar(Tags); Tags=cellstr(Tags); end
    if any(strcmp(Tags(:),'!all'))
        delete(get(F,'Children'))
    else
        for tag = Tags(:)'
        delete(findobj(get(F,'Children'),'flat','Tag',tag{:}));
        end
    end
    set(0,'ShowHiddenHandles',cSHH)
end
set(F,'Pointer','Arrow')
movegui(F);

case 'print'
%=======================================================================
% spm_figure('Print',F,fname)

%-Arguments & defaults
if nargin<3, fname=''; else fname=varargin{3};end
if nargin<2, F='Graphics'; else F=varargin{2}; end

%-Find window to print, default to gcf if specified figure not found
% Return if no figures
if ~isempty(F), F = spm_figure('FindWin',F); end
if  isempty(F), F = get(0,'CurrentFigure'); end
if  isempty(F), return, end

%-Note current figure, & switch to figure to print
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)

%-See if window has paging controls
hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo   = findobj(F,'Tag','PageNo');
iPaged    = ~isempty(hNextPage);

%-Construct print command
%-----------------------------------------------------------------------

%-Temporarily change all units to normalized prior to printing
% (Fixes bizzarre problem with stuff jumping around!)
%-----------------------------------------------------------------------
H  = findobj(get(F,'Children'),'flat','Type','axes');
if ~isempty(H),
    un = cellstr(get(H,'Units'));
    set(H,'Units','normalized')
end;

%-Print
%-----------------------------------------------------------------------
if ~iPaged
    spm_print(fname)
else
    hPg       = get(hNextPage,'UserData');
    Cpage     = get(hPageNo,  'UserData');
    nPages    = size(hPg,1);

    set([hNextPage,hPrevPage,hPageNo],'Visible','off')
    if Cpage~=1
        set(hPg{Cpage,1},'Visible','off'), end
    for p = 1:nPages
        set(hPg{p,1},'Visible','on');
        spm_print(fname);
        set(hPg{p,1},'Visible','off')
    end
    set(hPg{Cpage,1},'Visible','on')
    set([hNextPage,hPrevPage,hPageNo],'Visible','on')
end
if ~isempty(H), set(H,{'Units'},un); end;
set(0,'CurrentFigure',cF)

case 'printto'
%=======================================================================
%spm_figure('PrintTo',F)

%-Arguments & defaults
if nargin<2, F='Graphics'; else F=varargin{2}; end

%-Find window to print, default to gcf if specified figure not found
% Return if no figures
F=spm_figure('FindWin',F);
if isempty(F), F = get(0,'CurrentFigure'); end
if isempty(F), return, end

[fn pn] = uiputfile('*.ps', 'Print to File');
if fn == 0
    return;
end;

psname = fullfile(pn, fn);
spm_figure('Print',F,psname);

case 'newpage'
%=======================================================================
% [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',h)
if nargin<2 || isempty(varargin{2}) error('No handles to paginate')
else h=varargin{2}(:)'; end

%-Work out which figure we're in
F = spm_figure('ParentFig',h(1));

hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo   = findobj(F,'Tag','PageNo');

%-Create pagination widgets if required
%-----------------------------------------------------------------------
if isempty(hNextPage)
    WS = spm('WinScale');
    FS = spm('FontSizes');
    SatFig = findobj('Tag','Satellite');
    if ~isempty(SatFig)
        SatFigPos    = get(SatFig,'Position');
        hNextPagePos = [SatFigPos(3)-25 15 15 15];
        hPrevPagePos = [SatFigPos(3)-40 15 15 15];
        hPageNo      = [SatFigPos(3)-40  5 30 10];
    else
        hNextPagePos = [580 022 015 015].*WS;
        hPrevPagePos = [565 022 015 015].*WS;
        hPageNo      = [550 005 060 015].*WS;
    end

    hNextPage = uicontrol(F,'Style','Pushbutton',...
        'HandleVisibility','on',...
        'String','>','FontSize',FS(10),...
        'ToolTipString','next page',...
        'Callback','spm_figure(''TurnPage'',''+1'',gcbf)',...
        'Position',hNextPagePos,...
        'ForegroundColor',[0 0 0],...
        'Tag','NextPage','UserData',[]);
    hPrevPage = uicontrol(F,'Style','Pushbutton',...
        'HandleVisibility','on',...
        'String','<','FontSize',FS(10),...
        'ToolTipString','previous page',...
        'Callback','spm_figure(''TurnPage'',''-1'',gcbf)',...
        'Position',hPrevPagePos,...
        'Visible','on',...
        'Enable','off',...
        'Tag','PrevPage');
    hPageNo = uicontrol(F,'Style','Text',...
        'HandleVisibility','on',...
        'String','1',...
        'FontSize',FS(6),...
        'HorizontalAlignment','center',...
        'BackgroundColor','w',...
        'Position',hPageNo,...
        'Visible','on',...
        'UserData',1,...
        'Tag','PageNo','UserData',1);
end

%-Add handles for this page to UserData of hNextPage
%-Make handles for this page invisible if PageNo>1
%-----------------------------------------------------------------------
mVis    = strcmp('on',get(h,'Visible'));
mHit    = strcmp('on',get(h,'HitTest'));
hPg     = get(hNextPage,'UserData');
if isempty(hPg)
    hPg = {h(mVis), h(~mVis), h(mHit), h(~mHit)};
else
    hPg = [hPg; {h(mVis), h(~mVis), h(mHit), h(~mHit)}];
    set(h(mVis),'Visible','off');
        set(h(mHit),'HitTest','off');
end
set(hNextPage,'UserData',hPg)

%-Return handles to pagination controls if requested
if nargout>0, varargout = {[hNextPage, hPrevPage, hPageNo]}; end

case 'turnpage'
%=======================================================================
% spm_figure('TurnPage',move,F)
if nargin<3, F='Graphics'; else F=varargin{3}; end
if nargin<2, move=1; else move=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end

hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo   = findobj(F,'Tag','PageNo');
if isempty(hNextPage), return, end
hPg       = get(hNextPage,'UserData');
Cpage     = get(hPageNo,  'UserData');
nPages    = size(hPg,1);

%-Sort out new page number
if ischar(move), Npage = Cpage+eval(move); else Npage = move; end
Npage = max(min(Npage,nPages),1);

%-Make current page invisible, new page visible, set page number string
set(hPg{Cpage,1},'Visible','off');
set(hPg{Cpage,3},'HitTest','off');
set(hPg{Npage,1},'Visible','on');
set(hPg{Npage,3},'HitTest','on');
set(hPageNo,'UserData',Npage,'String',sprintf('%d / %d',Npage,nPages))

for k = 1:length(hPg{Npage,1}) % VG
    if strcmp(get(hPg{Npage,1}(k),'Type'),'axes')
        axes(hPg{Npage,1}(k));
    end;
end;

%-Disable appropriate page turning control if on first/last page (for neatness)
if Npage==1, set(hPrevPage,'Enable','off')
else set(hPrevPage,'Enable','on'), end
if Npage==nPages, set(hNextPage,'Enable','off')
else set(hNextPage,'Enable','on'), end

case 'deletepagecontrols'
%=======================================================================
% spm_figure('DeletePageControls',F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end

hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo   = findobj(F,'Tag','PageNo');

delete([hNextPage hPrevPage hPageNo])

case '#page'
%=======================================================================
% n = spm_figure('#Page',F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end

hNextPage = findobj(F,'Tag','NextPage');
if isempty(hNextPage)
    n = 1;
else
    n = size(get(hNextPage,'UserData'),1)+1;
end
varargout = {n};

case 'currentpage'
%=======================================================================
% n = spm_figure('CurrentPage', F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end

hPageNo   = findobj(F,'Tag','PageNo');
Cpage     = get(hPageNo,  'UserData');

varargout = {Cpage};

case 'watermark'
%=======================================================================
% spm_figure('WaterMark',F,str,Tag,Angle,Perm)
if nargin<6, HVis='on'; else HVis='off'; end
if nargin<5, Angle=-45; else Angle=varargin{5}; end
if nargin<4 || isempty(varargin{4}), Tag = 'WaterMark'; else Tag=varargin{4}; end
if nargin<3 || isempty(varargin{3}), str = 'SPM';       else str=varargin{3}; end
if nargin<2, if any(get(0,'Children')), F=gcf; else F=''; end
else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end

%-Specify watermark color from background colour
%-----------------------------------------------------------------------
Colour = get(F,'Color');
%-Only mess with grayscale backgrounds
if ~all(Colour==Colour(1)), return, end
%-Work out colour - lighter unless grey value > 0.9
Colour = Colour+(2*(Colour(1)<0.9)-1)*0.02;

cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
Units=get(F,'Units');
set(F,'Units','normalized');
h = axes('Position',[0.45,0.5,0.1,0.1],...
    'Units','normalized',...
    'Visible','off',...
    'Tag',Tag);
set(F,'Units',Units)
text(0.5,0.5,str,...
    'FontSize',spm('FontSize',80),...
    'FontWeight','Bold',...
    'FontName',spm_platform('Font','times'),...
    'Rotation',Angle,...
    'HorizontalAlignment','Center',...
    'VerticalAlignment','middle',...
    'EraseMode','normal',...
    'Color',Colour,...
    'ButtonDownFcn',[...
        'if strcmp(get(gcbf,''SelectionType''),''open''),',...
            'delete(get(gcbo,''Parent'')),',...
        'end'])
set(h,'HandleVisibility',HVis)
set(0,'CurrentFigure',cF)

case 'createwin'
%=======================================================================
% F=spm_figure('CreateWin',Tag,Name,Visible)

%-Condition arguments
%-----------------------------------------------------------------------
if nargin<4 || isempty(varargin{4}), Visible='on'; else Visible=varargin{4}; end
if nargin<3, Name=''; else Name = varargin{3}; end
if nargin<2, Tag='';  else Tag  = varargin{2}; end

WS   = spm('WinScale');           %-Window scaling factors
FS   = spm('FontSizes');          %-Scaled font sizes
PF   = spm_platform('fonts');     %-Font names (for this platform)
Rect = spm('WinSize','Graphics'); %-Graphics window rectangle
S0   = spm('WinSize','0',1);      %-Screen size (of the current monitor)

F    = figure(...
    'Tag',Tag,...
    'Position',[S0(1) S0(2) 0 0] + Rect,...
    'Resize','off',...
    'Color','w',...
    'ColorMap',gray(64),...
    'DefaultTextColor','k',...
    'DefaultTextInterpreter','none',...
    'DefaultTextFontName',PF.helvetica,...
    'DefaultTextFontSize',FS(10),...
    'DefaultAxesColor','w',...
    'DefaultAxesXColor','k',...
    'DefaultAxesYColor','k',...
    'DefaultAxesZColor','k',...
    'DefaultAxesFontName',PF.helvetica,...
    'DefaultPatchFaceColor','k',...
    'DefaultPatchEdgeColor','k',...
    'DefaultSurfaceEdgeColor','k',...
    'DefaultLineColor','k',...
    'DefaultUicontrolFontName',PF.helvetica,...
    'DefaultUicontrolFontSize',FS(10),...
    'DefaultUicontrolInterruptible','on',...
    'PaperType','A4',...
    'PaperUnits','normalized',...
    'PaperPosition',[.0726 .0644 .854 .870],...
    'InvertHardcopy','off',...
    'Renderer',spm_get_defaults('renderer'),...
    'Visible','off',...
    'Toolbar','none');
if ~isempty(Name)
    set(F,'Name',sprintf('%s%s: %s',spm('ver'),...
        spm('GetUser',' (%s)'),Name),'NumberTitle','off')
end
set(F,'Visible',Visible)
varargout = {F};

case 'getwinscale'
%=======================================================================
% WS = spm_figure('GetWinScale')
warning('spm_figure(''GetWinScale''... is Grandfathered: use spm(''WinScale''')
varargout = {spm('WinScale')};

case 'fontsizes'
%=======================================================================
% FS = spm_figure('FontSizes',FS)
warning('spm_figure(''FontSizes''... is Grandfathered: use spm(''FontSizes''')
if nargin<2, FS=[08,09,11,13,14,6:36]; else FS=varargin{2}; end
varargout = {round(FS*min(spm('WinScale')))};

%=======================================================================
 case 'createbar'
%=======================================================================
% spm_figure('CreateBar',F)
if nargin<2, if any(get(0,'Children')), F=gcf; else F=''; end
else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end

cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')

t0 = findobj(get(F,'Children'),'Flat','Label','&Help');
if isempty(t0), t0 = uimenu( F,'Label','&Help'); end;

set(findobj(t0,'Position',1),'Separator','on');
uimenu(t0,'Position',1,...
    'Label','SPM web',...
    'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/'');');
uimenu(t0,'Position',1,...
    'Label','SPM help','ForegroundColor',[0 1 0],...
    'CallBack','spm_help');

t0=uimenu( F,'Label','Colours','HandleVisibility','off');
t1=uimenu(t0,'Label','ColorMap');
uimenu(t1,'Label','Gray',     'CallBack','spm_figure(''ColorMap'',''gray'')');
uimenu(t1,'Label','Hot',      'CallBack','spm_figure(''ColorMap'',''hot'')');
uimenu(t1,'Label','Pink',     'CallBack','spm_figure(''ColorMap'',''pink'')');
uimenu(t1,'Label','Jet','CallBack','spm_figure(''ColorMap'',''jet'')');
uimenu(t1,'Label','Gray-Hot', 'CallBack','spm_figure(''ColorMap'',''gray-hot'')');
uimenu(t1,'Label','Gray-Cool','CallBack','spm_figure(''ColorMap'',''gray-cool'')');
uimenu(t1,'Label','Gray-Pink','CallBack','spm_figure(''ColorMap'',''gray-pink'')');
uimenu(t1,'Label','Gray-Jet', 'CallBack','spm_figure(''ColorMap'',''gray-jet'')');
t1=uimenu(t0,'Label','Effects');
uimenu(t1,'Label','Invert','CallBack','spm_figure(''ColorMap'',''invert'')');
uimenu(t1,'Label','Brighten','CallBack','spm_figure(''ColorMap'',''brighten'')');
uimenu(t1,'Label','Darken','CallBack','spm_figure(''ColorMap'',''darken'')');
uimenu( F,'Label','Clear','HandleVisibility','off','CallBack','spm_figure(''Clear'',gcbf)');
t0=uimenu( F,'Label','SPM-Print','HandleVisibility','off');
%uimenu( F,'Label','SPM-Print','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)');
t1=uimenu(t0,'Label','default print file','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)');
t1=uimenu(t0,'Label','other print file','HandleVisibility','off','CallBack','spm_figure(''PrintTo'',spm_figure(''FindWin'',''Graphics''))');

% ### CODE FOR SATELLITE FIGURE ###
% Code checks if there is a satellite window and if results are currently displayed
% It assumes that if hReg is invalid then there are no results currently displayed
% Modified by DRG to display a satellite figure 02/14/01.
cb = ['global SatWindow,',...
        'try,',...
        'tmp = get(hReg);,',...
        'ResFlag = 1;',...
        'catch,',...
        'ResFlag = 0;',...
        'end,',...
        'if SatWindow,',...
        'figure(SatWindow),',...
        'else,',...
        'if ResFlag,',...
        'spm_setup_satfig,',...
        'end,',...
        'end'];
uimenu( F,'Label','Results-Fig','HandleVisibility','off','Callback',cb);
% ### END NEW CODE ###

set(0,'ShowHiddenHandles',cSHH)
try
    spm_jobman('pulldown');
end

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

case 'figcontextmenu'
%=======================================================================
% h = spm_figure('FigContextMenu',F)
if nargin<2
    F = get(0,'CurrentFigure');
    if isempty(F), error('no figure'), end
else
    F = spm_figure('FindWin',varargin{2});
    if isempty(F), error('no such figure'), end
end
h       = uicontextmenu('Parent',F,'HandleVisibility','CallBack');
cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')
copy_menu(F,h);
set(0,'ShowHiddenHandles',cSHH)
set(F,'UIContextMenu',h)
varargout = {h};

case 'colormap'
%=======================================================================
% spm_figure('ColorMap',ColAction,h)
if nargin<3, h=[]; else h=varargin{3}; end
if nargin<2, ColAction='gray'; else ColAction=varargin{2}; end

switch lower(ColAction), case 'gray'
    colormap(gray(64))
case 'hot'
    colormap(hot(64))
case 'pink'
    colormap(pink(64))
case 'jet'
    colormap(jet(64))
case 'gray-hot'
    tmp = hot(64 + 16);  tmp = tmp((1:64) + 16,:);
    colormap([gray(64); tmp]);
case 'gray-cool'
    cool = [zeros(10,1) zeros(10,1) linspace(0.5,1,10)';
            zeros(31,1) linspace(0,1,31)' ones(31,1);
            linspace(0,1,23)' ones(23,1) ones(23,1) ];
    colormap([gray(64); cool]);
case 'gray-pink'
    tmp = pink(64 + 16); tmp = tmp((1:64) + 16,:);
    colormap([gray(64); tmp]);
case 'gray-jet'
    colormap([gray(64); jet(64)]);
case 'invert'
    colormap(flipud(colormap));
case 'brighten'
    colormap(brighten(colormap, 0.2));
case 'darken'
    colormap(brighten(colormap, -0.2));
otherwise
    error('Illegal ColAction specification');
end

case 'graphicshandle'
%=======================================================================
% h = spm_figure('GraphicsHandle',F)
if nargin<2, F=gcbf; else F=spm_figure('FindWin',varargin{2}); end
if isempty(F), return, end

tmp = get(F,'Name');
set(F,'Name',...
    'Handle: Select item to identify, MiddleMouse=parent, RightMouse=cancel...');
set(F,'Pointer','CrossHair')
waitforbuttonpress;
h        = gco(F);
hType    = get(h,'Type');
SelnType = get(gcf,'SelectionType');
set(F,'Pointer','Arrow','Name',tmp)

if ~strcmp(SelnType,'alt') && ~isempty(h) && gcf==F
    str = sprintf('Selected (%s) object',get(h,'Type'));
    if strcmp(SelnType,'normal')
        str = sprintf('%s: handle',str);
    else
        h = get(h,'Parent');
        str = sprintf('%s: handle of parent (%s) object',str,get(h,'Type'));
    end
    if nargout==0
        assignin('base','ans',h)
        fprintf('\n%s: \n',str)
        ans = h
    else
        varargout={h};
    end
else
    varargout={[]};
end

otherwise
%=======================================================================
warning(['Illegal Action string: ',Action])
end
return;
%=======================================================================

%=======================================================================
function copy_menu(F,G)
%=======================================================================
handles = findobj(get(F,'Children'),'Flat','Type','uimenu','Visible','on');
if isempty(handles), return; end;
for F1=handles',
    if ~strcmp(get(F1,'Label'),'&Window'),
        G1 = uimenu(G,'Label',get(F1,'Label'),...
            'CallBack',get(F1,'CallBack'),...
            'Position',get(F1,'Position'),...
            'Separator',get(F1,'Separator'));
        copy_menu(F1,G1);
    end;
end;
return;
%=======================================================================

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
clear all; close all; clear classes; clc;

%% Set flags.
inspect_only = false;

%% Solve the system.
s = 120;
w = 40;
b = (s + w/2)*2;
dL = 10;
dl = 2;
wvlen = 200;
clear solveropts;
[E, H, obj_array, src_array, J] = maxwell_run(...
	'OSC', 1e-9, wvlen, ...
	'DOM', {'vacuum', 'none', 1.0}, [-610 610; -610 610; 0 dl], [dL dL dl], BC.p, [10*dL 10*dL 0], ...
	'OBJ', {'vacuum', 'none', 1.0}, Box([-w/2 w/2; -w/2 w/2; 0 dl], dl), ...
	'SOBJ', ...  % scatter objects
		{'Johnson/Au', 'y'}, ...
			PolygonalCylinder(Axis.z, dl, dl/2, [w/2 0; w/2+s*sqrt(3)/2 -s/2; w/2+s*sqrt(3)/2 s/2], dl), ...
			PolygonalCylinder(Axis.z, dl, dl/2, [-w/2 0; -w/2-s*sqrt(3)/2 s/2; -w/2-s*sqrt(3)/2 -s/2], dl), ...
	'SRCJ', TFSFPlaneSrc([-b b; -b b; 0 dl], Axis.y, Axis.x), ...
	inspect_only);

%% Visualize the solution.
figure
clear opts
opts.withobjsrc = true;
opts.withabs = true;
% opts.withinterp = false;
% opts.withgrid = true;
% opts.cscale = 1e-1;
% opts.cmax = 1.4;
z_location = 0;
vis2d(E{Axis.x}, Axis.z, z_location, obj_array, src_array, opts)
% vis2d(H{Axis.z}, Axis.z, z_location, obj_array, src_array, opts)

% %% Calculate the power emanating from the source.
% power = powerflux_box(E,H,[-10 10; -10 10; 0 1]);
% fprintf('power = %e\n', power);

author: wsshin

repo: maxwellfdfd

save_path: github-repos/MATLAB/wsshin-maxwellfdfd


text:
function quad_mesh_order1_display ( prefix )

%*****************************************************************************80
%
%% QUAD_MESH_ORDER1_DISPLAY plots piecewise constant quad mesh data.
%
%  Discussion:
%
%    This program reads three data files defining piecewise constant
%    data over a mesh of quadrilaterals, and displays a 3D MATLAB plot
%    of the data.
%
%  Usage:
%
%    quad_mesh_order1_display ( 'prefix' )
%
%    where
%
%    * 'prefix'_nodes.txt contains the node coordinates;
%    * 'prefix'_elements.txt contains the element definitions.
%    * 'prefix'_values.txt contains the values associated with each element.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    24 January 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string PREFIX, the common file prefix.
%
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUAD_MESH_ORDER1_DISPLAY:\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read and plot piecewise constant data on a quadrilateral mesh.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  This program expects to find three files to read:\n' );
  fprintf ( 1, '  * a node file,\n' );
  fprintf ( 1, '  * an element file,\n' );
  fprintf ( 1, '  * a value file (one value per element)\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  It reads the files and displays a plot.\n' );
%
%  The command line argument is the common filename prefix.
%
  if ( nargin < 1 )

    fprintf ( 1, '\n' );

    prefix = input ( 'Enter the filename prefix, in quotes:  ' );

  end
%
%  Create the filenames.
%
  node_filename = strcat ( prefix, '_nodes.txt' );
  element_filename = strcat ( prefix, '_elements.txt' );
  value_filename = strcat ( prefix, '_values.txt' );
%
%  Read the node data.
%
  [ dim_num, node_num ] = r8mat_header_read ( node_filename );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the header of "%s".', node_filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Spatial dimension DIM_NUM = %d\n', dim_num );
  fprintf ( 1, '  Number of points NODE_NUM = %d\n', node_num );

  if ( dim_num ~= 2 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!\n' );
    fprintf ( 1, '  Dataset must have spatial dimension 2.\n' );
    error ( 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!' );
  end

  node_xy = r8mat_data_read ( node_filename, dim_num, node_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the data in "%s".\n', node_filename );

  r8mat_transpose_print_some ( dim_num, node_num, node_xy, 1, 1, dim_num, 5, ...
    '  First 5 nodes:' );
%
%  Read the element data.
%
  [ element_order, element_num ] = i4mat_header_read ( element_filename );

  if ( element_order ~= 4 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!\n' );
    fprintf ( 1, '  Data is not for a 4-node quadrilateral mesh.\n' );
    error ( 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!' );
  end

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the header of "%s".\n', element_filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Element order = %d\n', element_order );
  fprintf ( 1, '  Number of elements ELEMENT_NUM  = %d\n', element_num );

  element_node = i4mat_data_read ( element_filename, element_order, element_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the data in "%s".\n', element_filename );

  i4mat_transpose_print_some ( element_order, element_num, ...
    element_node, 1, 1, element_order, 10, '  First 10 elements:' );
%
%  Detect and correct 0-based indexing.
%
  element_node = mesh_base_one ( node_num, element_order, element_num, ...
    element_node );
%
%  Read the values.
%
  [ value_dim, value_num ] = r8mat_header_read ( value_filename );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the header of "%s".', value_filename );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Spatial dimension = %d\n', value_dim );
  fprintf ( 1, '  Number of values  = %d\n', value_num );

  if ( value_dim ~= 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!\n' );
    fprintf ( 1, '  VALUE data must be scalar.\n' );
    error ( 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!' );
  end

  if ( value_num ~= element_num )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!\n' );
    fprintf ( 1, '  Number of values must equal number of elements.\n' );
    error ( 'QUAD_MESH_ORDER1_DISPLAY - Fatal error!' );
  end

  value = r8mat_data_read ( value_filename, value_dim, value_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Read the data in "%s".\n', value_filename );

  r8mat_transpose_print_some ( value_dim, value_num, value, 1, 1, value_dim, 5, ...
    '  First 5 values:' );
%
%  Display the mesh.
%
  figure ( 1 )
  clf
  hold on

  value_min = min ( value(1:element_num) );
  value_max = max ( value(1:element_num) );

  caxis ( [ value_min, value_max ] );

  for e = 1 : element_num

    n1 = element_node(1,e);
    n2 = element_node(2,e);
    n3 = element_node(3,e);
    n4 = element_node(4,e);

    x1 = node_xy(1,n1);
    x2 = node_xy(1,n2);
    x3 = node_xy(1,n3);
    x4 = node_xy(1,n4);

    y1 = node_xy(2,n1);
    y2 = node_xy(2,n2);
    y3 = node_xy(2,n3);
    y4 = node_xy(2,n4);

    fill ( [ x1, x2, x3, x4 ], [ y1, y2, y3, y4 ], value(e) );

  end

  xlabel ( 'X', 'FontName', 'Helvetica', 'FontWeight', 'bold', ...
    'FontSize', 16 );

  ylabel ( 'Y', 'FontName', 'Helvetica', 'FontWeight', 'bold', ...
    'FontSize', 16, 'Rotation', 0 );

  title ( 'Quadrilateral Mesh', 'FontName', 'Helvetica', 'FontWeight', ...
    'bold', 'FontSize', 16 );

  colorbar ( );

  hold off

  fprintf ( 1, '\n' );
  fprintf ( 1, 'Press return for 3D image:\n' );

  pause
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Here is a 3D image of the data.\n' );
  fprintf ( 1, '  Use the 3D-Rotate menu item to examine the picture.\n' );

  quad_mesh_order1_display_image ( node_xy, element_num, ...
    element_node, value );

  hold off
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'QUAD_MESH_ORDER1_DISPLAY:\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  return
end
function column_num = file_column_count ( input_file_name )

%*****************************************************************************80
%
%% FILE_COLUMN_COUNT counts the columns in the first line of a file.
%
%  Discussion:
%
%    The file is assumed to be a simple text file.
%
%    Most lines of the file are presumed to consist of COLUMN_NUM words,
%    separated by spaces.  There may also be some blank lines, and some
%    comment lines, which have a "#" in column 1.
%
%    The routine tries to find the first non-comment non-blank line and
%    counts the number of words in that line.
%
%    If all lines are blanks or comments, it goes back and tries to analyze
%    a comment line.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 February 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILE_NAME, the name of the file.
%
%    Output, integer COLUMN_NUM, the number of columns in the file.
%
  FALSE = 0;
  TRUE = 1;
%
%  Open the file.
%
  input_unit = fopen ( input_file_name );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FILE_COLUMN_COUNT - Error!\n' );
    fprintf ( 1, '  Could not open the file "%s".\n', input_file_name );
    error ( 'FILE_COLUMN_COUNT - Error!' );
  end
%
%  Read one line, but skip blank lines and comment lines.
%  Use FGETL so we drop the newline character!
%
  got_one = FALSE;

  while ( 1 )

    line = fgetl ( input_unit );

    if ( line == -1 )
      break;
    end

    if ( s_len_trim ( line ) == 0 )

    elseif ( line(1) == '#' )

    else
      got_one = TRUE;
      break;
    end

  end

  fclose ( input_unit );

  if ( got_one == FALSE )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FILE_COLUMN_COUNT - Warning!\n' );
    fprintf ( 1, '  The file does not seem to contain any data.\n' );
    column_num = -1;
    return;
  end

  column_num = s_word_count ( line );

  return
end
function row_num = file_row_count ( input_file_name )

%*****************************************************************************80
%
%% FILE_ROW_COUNT counts the number of row records in a file.
%
%  Discussion:
%
%    Each input line is a "RECORD".
%
%    The records are divided into three groups:
%
%    * BLANK LINES (nothing but blanks)
%    * COMMENT LINES (begin with a '#')
%    * DATA RECORDS (anything else)
%
%    The value returned by the function is the number of data records.
%
%    By the way, if the MATLAB routine FGETS is used, instead of
%    FGETL, then the variable LINE will include line termination
%    characters, which means that a blank line would not actually
%    have zero characters.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 December 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILE_NAME, the name of the input file.
%
%    Output, integer ROW_NUM, the number of rows found.
%
  input_unit = fopen ( input_file_name );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'FILE_ROW_COUNT - Error!\n' );
    fprintf ( 1, '  Could not open the file "%s".\n', input_file_name );
    error ( 'FILE_ROW_COUNT - Error!' );
  end

  blank_num = 0;
  comment_num = 0;
  row_num = 0;

  record_num = 0;

  while ( 1 )

    line = fgetl ( input_unit );

    if ( line == -1 )
      break;
    end

    record_num = record_num + 1;
    record_length = s_len_trim ( line );

    if ( record_length <= 0 )
      blank_num = blank_num + 1;
    elseif ( line(1) == '#' )
      comment_num = comment_num + 1;
    else
      row_num = row_num + 1;
    end

  end

  fclose ( input_unit );

  return
end
function table = i4mat_data_read ( input_filename, m, n )

%*****************************************************************************80
%
%% I4MAT_DATA_READ reads data from an I4MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 January 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Input, integer M, N, the number of rows and columns in the data.
%
%    Output, integer TABLE(M,N), the point coordinates.
%
  table = zeros ( m, n );
%
%  Build up the format string for reading M real numbers.
%
  string = ' ';

  for i = 0 : m
    string = strcat ( string, ' %d' );
  end

  input_unit = fopen ( input_filename );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_DATA_READ - Error!\n' );
    fprintf ( 1, '  Could not open the input file.\n' );
    error ( 'I4MAT_DATA_READ - Error!' );
  end

  i = 0;

  while ( i < n )

    line = fgets ( input_unit );

    if ( line == -1 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'I4MAT_DATA_READ - Error!\n' );
      fprintf ( 1, '  End of input while reading data.\n' );
      error ( 'I4MAT_DATA_READ - Error!' );
    end

    if ( line(1) == '#' )

    elseif ( s_len_trim ( line ) == 0 )

    else

      [ x, count ] = sscanf ( line, string );

      if ( count == m )
        i = i + 1;
        table(1:m,i) = x(1:m);
      end

    end

  end

  fclose ( input_unit );

  return
end
function [ m, n ] = i4mat_header_read ( input_filename )

%*****************************************************************************80
%
%% I4MAT_HEADER_READ reads the header from an I4MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 October 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Output, integer M, the spatial dimension.
%
%    Output, integer N, the number of points.
%
  m = file_column_count ( input_filename );

  if ( m <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\n' );
    fprintf ( 1, '  There was some kind of I/O problem while trying\n' );
    fprintf ( 1, '  to count the number of data columns in\n' );
    fprintf ( 1, '  the file %s.\n', input_filename );
  end

  n = file_row_count ( input_filename );

  if ( n <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'I4MAT_HEADER_READ - Fatal error!\n' );
    fprintf ( 1, '  There was some kind of I/O problem while trying\n' );
    fprintf ( 1, '  to count the number of data rows in\n' );
    fprintf ( 1, '  the file %s\n', input_filename );
  end

  return
end
function i4mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% I4MAT_TRANSPOSE_PRINT_SOME prints some of an I4MAT, transposed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    21 June 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns.
%
%    Input, integer A(M,N), an M by N matrix to be printed.
%
%    Input, integer ILO, JLO, the first row and column to print.
%
%    Input, integer IHI, JHI, the last row and column to print.
%
%    Input, string TITLE, an optional title.
%
  incx = 10;

  if ( 0 < s_len_trim ( title ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, '%s\n', title );
  end

  for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )

    i2hi = i2lo + incx - 1;
    i2hi = min ( i2hi, m );
    i2hi = min ( i2hi, ihi );

    inc = i2hi + 1 - i2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row: ' );
    for i = i2lo : i2hi
      fprintf ( 1, '%7d  ', i );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col\n' );
    fprintf ( 1, '\n' );

    j2lo = max ( jlo, 1 );
    j2hi = min ( jhi, n );

    for j = j2lo : j2hi

      fprintf ( 1, '%5d  ', j );
      for i2 = 1 : inc
        i = i2lo - 1 + i2;
        fprintf ( 1, '%7d  ', a(i,j) );
      end
      fprintf ( 1, '\n' );

    end

  end

  return
end
function element_node = mesh_base_one ( node_num, element_order, ...
  element_num, element_node )

%*****************************************************************************80
%
%% MESH_BASE_ONE ensures that the element definition is one-based.
%
%  Discussion:
%
%    The ELEMENT_NODE array contains nodes indices that form elements.
%    The convention for node indexing might start at 0 or at 1.
%    Since a MATLAB program will naturally assume a 1-based indexing, it is
%    necessary to check a given element definition and, if it is actually
%    0-based, to convert it.
%
%    This function attempts to detect 0-based node indexing and correct it.
%
%    Thanks to Feifei Xu for pointing out that I was subtracting 1 when I
%    should have been adding 1!  29 November 2012.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 November 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, integer ELEMENT_ORDER, the order of the elements.
%
%    Input, integer ELEMENT_NUM, the number of elements.
%
%    Input/output, integer ELEMENT_NODE(ELEMENT_ORDE,ELEMENT_NUM), the element
%    definitions.
%
  node_min = min ( min ( element_node(1:element_order,1:element_num) ) );
  node_max = max ( max ( element_node(1:element_order,1:element_num) ) );

  if ( node_min == 0 && node_max == node_num - 1 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MESH_BASE_ONE:\n' );
    fprintf ( 1, '  The element indexing appears to be 0-based!\n' );
    fprintf ( 1, '  This will be converted to 1-based.\n' );
    element_node(1:element_order,1:element_num) = ...
      element_node(1:element_order,1:element_num) + 1;
  elseif ( node_min == 1 && node_max == node_num )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MESH_BASE_ONE:\n' );
    fprintf ( 1, '  The element indexing appears to be 1-based!\n' );
    fprintf ( 1, '  No conversion is necessary.\n' );
  else
    fprintf ( 1, '\n' );
    fprintf ( 1, 'MESH_BASE_ONE - Warning!\n' );
    fprintf ( 1, '  The element indexing is not of a recognized type.\n' );
    fprintf ( 1, '  NODE_MIN = %d\n', node_min );
    fprintf ( 1, '  NODE_MAX = %d\n', node_max );
    fprintf ( 1, '  NODE_NUM = %d\n', node_num );
  end

  return
end
function quad_mesh_order1_display_image ( node_xy, element_num, ...
  element_node, value )

%*****************************************************************************80
%
%% QUAD_MESH_ORDER1_DISPLAY_IMAGE plots piecewise constant data.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    31 March 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer NODE_NUM, the number of nodes.
%
%    Input, integer NODE_XY(2,NODE_NUM), the coordinates of the nodes.
%
%    Input, integer ELEMENT_NUM, the number of elements.
%
%    Input, integer ELEMENT_NODE(4,ELEMENT_NUM),
%    the nodes that made up each element.
%
%    Input, real VALUE(ELEMENT_NUM), the value assigned to each element
%
  zmax = max ( value(1:element_num) );
  zmin = min ( value(1:element_num) );

  caxis ( [ zmin, zmax ] );
%
%  Pick the colors that will correspond to the minimum and maximum
%  values of Z.
%
  rmax = 0.8;
  gmax = 0.2;
  bmax = 0.1;

  rmin = 0.1;
  gmin = 0.3;
  bmin = 0.7;

  figure ( 2 )
  clf
  hold on

  for element = 1 : element_num
%
%  Pick out the nodes of the triangle.
%
    x1 = node_xy(1,element_node(1,element));
    y1 = node_xy(2,element_node(1,element));
    x2 = node_xy(1,element_node(2,element));
    y2 = node_xy(2,element_node(2,element));
    x3 = node_xy(1,element_node(3,element));
    y3 = node_xy(2,element_node(3,element));
    x4 = node_xy(1,element_node(4,element));
    y4 = node_xy(2,element_node(4,element));

    z = value(element);
%
%  Draw the top of the prism, using a color corresponding to the height.
%
    r = ( ( zmax - z ) * rmin + ( z - zmin ) * rmax ) / ( zmax - zmin );
    g = ( ( zmax - z ) * gmin + ( z - zmin ) * gmax ) / ( zmax - zmin );
    b = ( ( zmax - z ) * bmin + ( z - zmin ) * bmax ) / ( zmax - zmin );

    fill3 ( [ x1, x2, x3, x4 ], [ y1, y2, y3, y4 ], [ z, z, z, z ], z )
%
%  Draw the bottom of the prism, using black.
%
    fill3 ( [ x1, x2, x3, x4 ], [ y1, y2, y3, y4 ], [ 0, 0, 0, 0 ], z )
%
%  Draw the sides of the prism, using a lighter shade of the top color.
%
    r = sqrt ( r );
    g = sqrt ( g );
    b = sqrt ( b );

    fill3 ( [ x1, x2, x2, x1 ], [ y1, y2, y2, y1 ], [ 0, 0, z, z ], z )
    fill3 ( [ x2, x3, x3, x2 ], [ y2, y3, y3, y2 ], [ 0, 0, z, z ], z )
    fill3 ( [ x3, x4, x4, x3 ], [ y3, y4, y4, y3 ], [ 0, 0, z, z ], z )
    fill3 ( [ x4, x1, x1, x4 ], [ y4, y1, y1, y4 ], [ 0, 0, z, z ], z )

  end

  xlabel ( 'X', 'FontName', 'Helvetica', 'FontWeight', 'bold', ...
    'FontSize', 16 );

  ylabel ( 'Y', 'FontName', 'Helvetica', 'FontWeight', 'bold', ...
    'FontSize', 16, 'Rotation', 0 );

  title ( 'Z(X,Y)', 'FontName', 'Helvetica', 'FontWeight', ...
    'bold', 'FontSize', 16 );

  colorbar ( )

  view ( 3 )

  return
end
function table = r8mat_data_read ( input_filename, m, n )

%*****************************************************************************80
%
%% R8MAT_DATA_READ reads data from an R8MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 January 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Input, integer M, N, the number of rows and columns of data.
%
%    Output, real TABLE(M,N), the point coordinates.
%
  table = zeros ( m, n );
%
%  Build up the format string for reading M real numbers.
%
  string = ' ';

  for i = 0 : m
    string = strcat ( string, ' %f' );
  end

  input_unit = fopen ( input_filename );

  if ( input_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_DATA_READ - Error!\n' );
    fprintf ( 1, '  Could not open the file.\n' );
    error ( 'R8MAT_DATA_READ - Error!' );
  end

  i = 0;

  while ( i < n )

    line = fgets ( input_unit );

    if ( line == -1 )
      break;
    end

    if ( line(1) == '#' )

    elseif ( s_len_trim ( line ) == 0 )

    else

      [ x, count ] = sscanf ( line, string );

      if ( count == m )
        i = i + 1;
        table(1:m,i) = x(1:m);
      end

    end

  end

  fclose ( input_unit );

  return
end
function [ m, n ] = r8mat_header_read ( input_filename )

%*****************************************************************************80
%
%% R8MAT_HEADER_READ reads the header from an R8MAT file.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    22 October 2004
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string INPUT_FILENAME, the name of the input file.
%
%    Output, integer M, the spatial dimension.
%
%    Output, integer N, the number of points.
%
  m = file_column_count ( input_filename );

  if ( m <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\n' );
    fprintf ( 1, '  There was some kind of I/O problem while trying\n' );
    fprintf ( 1, '  to count the number of data columns in\n' );
    fprintf ( 1, '  the file %s.\n', input_filename );
  end

  n = file_row_count ( input_filename );

  if ( n <= 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8MAT_HEADER_READ - Fatal error!\n' );
    fprintf ( 1, '  There was some kind of I/O problem while trying\n' );
    fprintf ( 1, '  to count the number of data rows in\n' );
    fprintf ( 1, '  the file %s\n', input_filename );
  end

  return
end
function r8mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 May 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, N, the number of rows and columns.
%
%    Input, real A(M,N), an M by N matrix to be printed.
%
%    Input, integer ILO, JLO, the first row and column to print.
%
%    Input, integer IHI, JHI, the last row and column to print.
%
%    Input, string TITLE, an optional title.
%
  incx = 5;

  if ( 0 < s_len_trim ( title ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, '%s\n', title );
  end

  for i2lo = max ( ilo, 1 ) : incx : min ( ihi, m )

    i2hi = i2lo + incx - 1;
    i2hi = min ( i2hi, m );
    i2hi = min ( i2hi, ihi );

    inc = i2hi + 1 - i2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row: ' );
    for i = i2lo : i2hi
      fprintf ( 1, '%7d       ', i );
    end
    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col\n' );

    j2lo = max ( jlo, 1 );
    j2hi = min ( jhi, n );

    for j = j2lo : j2hi

      fprintf ( 1, '%5d ', j );
      for i2 = 1 : inc
        i = i2lo - 1 + i2;
        fprintf ( 1, '%12f', a(i,j) );
      end
      fprintf ( 1, '\n' );

    end

  end

  return
end
function len = s_len_trim ( s )

%*****************************************************************************80
%
%% S_LEN_TRIM returns the length of a character string to the last nonblank.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 June 2003
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string to be measured.
%
%    Output, integer LEN, the length of the string up to the last nonblank.
%
  len = length ( s );

  while ( 0 < len )
    if ( s(len) ~= ' ' )
      return
    end
    len = len - 1;
  end

  return
end
function word_num = s_word_count ( s )

%*****************************************************************************80
%
%% S_WORD_COUNT counts the number of "words" in a string.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 January 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, string S, the string to be examined.
%
%    Output, integer WORD_NUM, the number of "words" in the string.
%    Words are presumed to be separated by one or more blanks.
%
  FALSE = 0;
  TRUE = 1;

  word_num = 0;
  s_length = length ( s );

  if ( s_length <= 0 )
    return;
  end

  blank = TRUE;

  for i = 1 : s_length

    if ( s(i) == ' ' )
      blank = TRUE;
    elseif ( blank == TRUE )
      word_num = word_num + 1;
      blank = FALSE;
    end

  end

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% TIMESTAMP prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end


text:
function subpak_test33 ( )

%*****************************************************************************80
%
%% TEST33 tests TVEC_EVEN_BRACKET, TVEC_EVEN_BRACKET2, and TVEC_EVEN_BRACKET3.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST33\n' );
  fprintf ( 1, '  For evenly spaced angles between THETA1 and THETA2:\n' );
  fprintf ( 1, '  TVEC_EVEN_BRACKET\n' );
  fprintf ( 1, '  TVEC_EVEN_BRACKET2.\n' );
  fprintf ( 1, '  TVEC_EVEN_BRACKET3.\n' );
  fprintf ( 1, '\n' );

  nt = 4;
  theta1 = 30.0;
  theta2 = 90.0;

  t = tvec_even_bracket ( nt, theta1, theta2 );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  TVEC_EVEN_BRACKET\n' );
  fprintf ( 1, '    NT = %d\n', nt );
  fprintf ( 1, '    THETA1 = %f\n', theta1 );
  fprintf ( 1, '    THETA2 = %f\n', theta2 );
  fprintf ( 1, '\n' );
  for i = 1 : nt
    fprintf ( 1, '  %f\n', t(i) );
  end

  nt = 5;

  t = tvec_even_bracket2 ( nt, theta1, theta2 );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  TVEC_EVEN_BRACKET2\n' );
  fprintf ( 1, '    NT = %d\n', nt );
  fprintf ( 1, '    THETA1 = %f\n', theta1 );
  fprintf ( 1, '    THETA2 = %f\n', theta2 );
  fprintf ( 1, '\n' );
  for i = 1 : nt
    fprintf ( 1, '  %f\n', t(i) );
  end

  nt = 3;

  t = tvec_even_bracket3 ( nt, theta1, theta2 );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TVEC_EVEN_BRACKET3\n' );
  fprintf ( 1, '    NT = %d\n', nt );
  fprintf ( 1, '    THETA1 = %f\n', theta1 );
  fprintf ( 1, '    THETA2 = %f\n', theta2 );
  fprintf ( 1, '\n' );
  for i = 1 : nt
    fprintf ( 1, '  %f\n', t(i) );
  end

  return
end


text:
function signal = set_fit_dipoles(varargin)
% Fit dipoles for each independent component of an IC-decomposed dataset.
%
% This function uses the Dipfit plugin for EEGLAB to automatically derive dipole locations
% for all IC's in the data set. The returned coordinates are in the MNI coordinate system.
% In addition, (probabilistic) anatomical labels can be looked up from different brain atlases [1,2].
%
%
% In:
%   Signal           : data set with valid IC decomposition
%
%   HeadModel        : head model file (see pop_dipfit_settings) (default: standard BEM volume)
%
%   MRImage          : anatomical MR head image file (default: standard BEM image)
%
%   ChannelLocations : coregistered channel locations file (default: standard 10-20 locations)
%
%   LookupLabels     : whether to look up anatomical labels & probabilities (default: true)
%
%   ConfusionRange   : radius (in mm) of uncertainty over which to scan for labels (default: 4)
%
%   BrainAtlas       : brain atlas to use. Talairach has a larger repertoire of areas, but is (in
%                      this version) non-probabilistic. The LONI LBPA40 atlas is a high-quality
%                      probabilistic atlas.
%
% Out:
%   Signal : data set with added dipole annotations
%
% Notes:
%   In the default settings, a standard Eurasian BEM head model amd MR image is used, and channel
%   locations are assumed to be standard 10-20 locations if not specifically given.
%
% Examples:
%   % for a data set which is annotated with independent components, e.g. via
%   eeg = flt_ica(raw);
%
%   % ... fit dipoles for each component using default settings, and look up the nearby anatomical
%   % structures and their hit probabilities)
%   eeg = set_fit_dipoles(eeg)
%
%   % ... fit dipoles and and look up anatomical structures within a radius of 10mm around each
%   % dipole coordinate (passing arguments by name)
%   eeg = set_fit_dipoles('Signal',eeg,'ConfusionRange',10)
%
%   % ... fit dipoles but do not look up anatomical structures
%   eeg = set_fit_dipoles('Signal',eeg,'LookupLabels',false)
%
%   % ... fit dipoles using a (subject-) specific head model and MR file
%   eeg = set_fit_dipoles('Signal',eeg,'HeadModel','volXY.mat','MRImage','mriXY.mat')
%
%   % ... fit dipoles using a (subject-) specific head model and MR file, as well as digitized
%   % channel locations
%   eeg = set_fit_dipoles('Signal',eeg,'HeadModel','my_vol.mat','MRImage','my_mri.mat','ChannelLocations','my_locs.mat')
%
% References:
%   [1] Lancaster JL, Woldorff MG, Parsons LM, Liotti M, Freitas CS, Rainey L, Kochunov PV, Nickerson D, Mikiten SA, Fox PT, "Automated Talairach Atlas labels for functional brain mapping".
%       Human Brain Mapping 10:120-131, 2000
%   [2] Shattuck DW, Mirza M, Adisetiyo V, Hojatkashani C, Salamon G, Narr KL, Poldrack RA, Bilder RM, Toga AW, "Construction of a 3D probabilistic atlas of human cortical structures."
%       Neuroimage. 2008 39(3):1064-80
%
% See also:
%   flt_ica, coregister, pop_multifit
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2011-01-21

% set_fit_dipoles_version<0.91> -- for the cache

if ~exp_beginfun('filter') return; end

% declare GUI name, etc.
declare_properties('name',{'DipoleFitting','dipfit'}, 'depends','flt_ica', 'precedes','flt_project', 'independent_channels',true, 'independent_trials',true);

% define arguments...
arg_define(varargin, ...
    arg_norep({'signal','Signal'}), ...
    arg({'hdm_file','HeadModel'}, '', [],'Head model file. The BEM head model that should be used by dipfit (using a standard model if empty).'),...
    arg({'mri_file','MRImage'}, '', [],'MR head image file. The MR head image that should be used by dipfit (using a standard image if empty).'),...
    arg({'chan_file','ReferenceLocations'}, '', [],'Coregistered reference chanlocs. The coregistered electrode locations that should be used as reference for alignment warping.'),...
    arg({'lookup_labels','LookupLabels'},true,[], 'Look up dipole labels. If enabled, look up anatomical labels from the selected brain atlas.'),...
    arg({'confusion_range','ConfusionRange'}, 4, [1 4 15 30], 'Confusion Radius (mm). Assumed standard deviation of uncertainty in the dipole fits, in millimeters.'),...
    arg({'brain_atlas','BrainAtlas'}, 'Talairach', {'Talairach','LBPA40'}, 'Brain atlas to use. Talairach has a larger repertoire of areas, but is (in this version) non-probabilistic. The LONI LBPA40 atlas is a high-quality probabilistic atlas; however, you have to to download it yourself.'),...
    arg({'var_threshold','VarianceThreshold'}, 15, [1 10 25 100], 'Residual Variance Thresold (%). The threshold in dipole fit residual variance above which dipoles models are rejected.'),...
    arg({'mri_constraints','UseMRIConstraints'}, false, [], 'Use MRI constraints. If enabled, restricts dipole solutions to the grey-matter volume. The currently requires the SPM toolbox to be in the path.'),...
    arg({'discard_nonlocalizable','DiscardNonlocalizable'}, false, [], 'Discard non-localizable components.'),...
    arg({'verbose','VerboseOutput'}, false, [], 'Verbose output.'),...
    arg_norep('dipfit_info'));

if ~exist('dipfit_info','var')
    % use standard data if unspecified
    if isempty(hdm_file) %#ok<*NODEF>
        hdm_file = env_translatepath('resources:/standard_BEM/standard_vol.mat'); end
    if isempty(mri_file)
        if mri_constraints
            mri_file = env_translatepath('resources:/standard_BEM/standard_mri_gm.mat');
        else
            mri_file = '';
        end
    end
    if isempty(chan_file)
        % figure out the labeling scheme to determine the correct coregistration...
        if ~isfield(signal.chaninfo,'labelscheme')
            signal.chaninfo.labelscheme = '10-20'; end
        switch signal.chaninfo.labelscheme
            case '10-20'
                chan_file = env_translatepath('resources:/standard_BEM/elec/standard_1005.elc');
            case 'sccn_128_v1'
                chan_file = env_translatepath('resources:/sccn_BEM_coregistered_128_v1.xyz');
            case 'sccn_128_v2'
                chan_file = env_translatepath('resources:/sccn_BEM_coregistered_128_v2.xyz');
            case 'sccn_256_v1'
                chan_file = env_translatepath('resources:/sccn_BEM_coregistered_256_v1.xyz');
            case 'sccn_256_v2'
                chan_file = env_translatepath('resources:/sccn_BEM_coregistered_256_v2.xyz');
            otherwise
                error('Unknown channel labeling scheme -- please supply a chan_file argument.');
        end
    end

    disp(['Now fitting dipoles... (montage reference: ' chan_file ')']);
    % fit icaweights
    if verbose
        dipfit_info = hlp_diskcache('dipfits',@do_fitting,signal,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold);
    else
        [text,dipfit_info] = evalc('hlp_diskcache(''dipfits'',@do_fitting,signal,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold)');
    end
    try
        % check if we need to fit Amica models, too...
        if isfield(signal.etc,'amica')
            sig = signal;
            multimodel = {};
            for m=1:size(signal.etc.amica.W,3)
                sig.icaweights = signal.etc.amica.W(:,:,m);
                sig.icawinv = signal.etc.amica.A(:,:,m);
                sig.icasphere = signal.etc.amica.S;
                if verbose
                    tmp = hlp_diskcache('dipfits',@do_fitting,sig,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold);
                else
                    [text,tmp] = evalc('hlp_diskcache(''dipfits'',@do_fitting,sig,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold);');
                end
                multimodel{m} = tmp.model; %#ok<AGROW>
            end
            dipfit_info.multimodel = multimodel;
        end
    catch
        disp('Could not compute dipfit solutions for Amica models.');
    end
end

signal.dipfit = dipfit_info;
if discard_nonlocalizable
    retain_ics = ~cellfun(@isempty,{signal.dipfit.model.posxyz});
    % update the dipole model
    signal.dipfit.model = signal.dipfit.model(retain_ics);
    % restrict the ICs & some derived data
    signal.icaweights = signal.icaweights(retain_ics,:);
    signal.icawinv = signal.icawinv(:,retain_ics);
    if ~isempty(signal.icaact) && ~isscalar(signal.icaact)
        signal.icaact = signal.icaact(retain_ics,:,:); end
end

if isfield(signal.etc,'amica')
    signal.etc.amica.dipfit = dipfit_info; end

global tracking;
tracking.inspection.dipfit = dipfit_info;

% when applied online, include the dipfit info into the parameters (so it gets attached immediately)
exp_endfun('append_online',{'dipfit_info',dipfit_info});

function result = do_fitting(signal,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold)

% coregister chanlocs to reference channels
[dummy,warping] = coregister(signal.chanlocs,chan_file,'warp','auto','manual','off'); %#ok<ASGLU>
% generate the dipfit info
%nosedir needs to be set to +X here for dipfit to work
signal.chaninfo.nosedir = '+X';
tmp = pop_multifit(pop_dipfit_settings(pop_select(signal,'channel',signal.icachansind),  ...
    'mrifile',mri_file, 'hdmfile',hdm_file,'chanfile',chan_file,'coordformat','MNI','coord_transform',warping), 1:size(signal.icaweights,1),'threshold',var_threshold);
% optionally derive anatomical labels & probabilities
if lookup_labels
    switch lower(brain_atlas)

        case 'talairach'
            db = org.talairach.Database;
            db.load(env_translatepath('resources:/talairach.nii'));
            for k=1:length(tmp.dipfit.model)
                try
                    p = icbm_spm2tal(tmp.dipfit.model(k).posxyz);
                    tmp.dipfit.model(k).labels = cellfun(@(d)char(d),cell(db.search_range(p(1),p(2),p(3),1.5*confusion_range)),'UniformOutput',false);
                    % and compute structure probabilities within the selected volume
                    [structures,x,idxs] = unique(hlp_split(sprintf('%s,',tmp.dipfit.model(k).labels{:}),',')); %#ok<ASGLU>
                    probabilities = mean(bsxfun(@eq,1:max(idxs),idxs'));
                    [probabilities,reindex] = sort(probabilities,'descend');
                    structures = structures(reindex);
                    mask = ~strcmp(structures,'*');
                    tmp.dipfit.model(k).structures = structures(mask);
                    tmp.dipfit.model(k).probabilities = probabilities(mask)*5; % there are 5 partitions
                    % figure('Position',[0 0 2560 900]); topoplot(tmp.icawinv(:,k),tmp.chanlocs); title([hlp_tostring(structures(mask)) 10 hlp_tostring(5*probabilities(mask))]); pop_dipplot(tmp,k);
                catch
                    tmp.dipfit.model(k).labels = {};
                    tmp.dipfit.model(k).structures = {};
                    tmp.dipfit.model(k).probabilities = [];
                end
            end

        case 'lbpa40'
            mask = find(~cellfun('isempty',{tmp.dipfit.model.posxyz}));
            % build query
            coords = vertcat(tmp.dipfit.model.posxyz);
            coords = [coords confusion_range * ones(size(coords,1),1)];
            % look up from atlas (note: slow!)
            [probs,labels] = label_dipoles(coords);
            % determine overlapped specialty regions to match up with Talairach's labeling scheme
            L = ~cellfun('isempty',strfind(labels,' L '));
            R = ~cellfun('isempty',strfind(labels,' R '));
            B = ~cellfun('isempty',strfind(labels,'Brainstem'));
            C = ~cellfun('isempty',strfind(labels,'Cerebellum'));
            allprobs = [sum(probs(:,L),2) sum(probs(:,R),2) sum(probs(:,C),2)*[0.5 0.5] sum(probs(:,B),2)];
            allstructs = {'Left Cerebrum' 'Right Cerebrum' 'Left Cerebellum' 'Right Cerebellum' 'Brainstem'};
            % go through all gyri and add up left & right probabilities
            gyri = unique(cellfun(@(l)l(12:end),labels(1:end-2),'UniformOutput',false))';
            allstructs = [allstructs gyri];
            for g=1:length(gyri)
                curgyrus = gyri{g};
                matches = ~cellfun('isempty',strfind(labels,curgyrus));
                allprobs = [allprobs sum(probs(:,matches),2)];
            end
            for k=1:length(mask)
                % retain only those with non-zero probability
                sel = allprobs(k,:) ~= 0;
                probabilities = allprobs(k,sel);
                structures = allstructs(sel);
                % sort probs & associated structs by descending probability
                [probabilities,reindex] = sort(probabilities,'descend');
                structures = structures(reindex);
                % store in the model...
                tmp.dipfit.model(mask(k)).structures = structures;
                tmp.dipfit.model(mask(k)).probabilities = probabilities;
                % figure('Position',[0 0 2560 900]);topoplot(tmp.icawinv(:,k),tmp.chanlocs); title([hlp_tostring(structures) 10 hlp_tostring(probabilities)]); pop_dipplot(tmp,k);
            end
    end
end
result = tmp.dipfit;

repo: REST


text:
%CLASSD Return labels of classified dataset, outdated, use LABELD instead

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

function labels = classd(a,w)

		global CLASSD_REPLACED_BY_LABELD

	if isempty(CLASSD_REPLACED_BY_LABELD)
		disp([newline 'CLASSD has been replaced by LABELD, please use it'])
		CLASSD_REPLACED_BY_LABELD = 1;
	end

	if (nargin == 0)

		labels = labeld;

	elseif (nargin == 1)

		labels = labeld(a);

	elseif (nargin == 2)

		labels = labeld(a,w);

	else
		error ('too many arguments');
	end

return

author: marianux

repo: ecg-kit

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