text:
function [data] = ft_math(cfg, varargin)

% FT_MATH performs mathematical operations on FieldTrip data structures,
% such as addition, subtraction, division, etc.
%
% Use as
%   data = ft_math(cfg, data1, data2, ...)
% with one or multiple FieldTrip data structures as the input and the configuration
% structure cfg in which you specify the mathematical operation that is to be
% executed on the desired parameter from the data
%   cfg.parameter = string, field from the input data on which the operation is
%                   performed, e.g. 'pow' or 'avg'
%   cfg.operation = string, for example '(x1-x2)/(x1+x2)' or 'x1/6'
%
% In the specification of the mathematical operation, x1 is the parameter obtained
% from the first input data structure, x2 from the second, etc.
%
% Rather than specifying the operation as a string that is evaluated, you can also
% specify it as a single operation. The advantage is that it is computed faster.
%    cfg.operation = string, can be 'add', 'subtract', 'divide', 'multiply', 'log10', 'abs'
% If you specify only a single input data structure and the operation is 'add',
% 'subtract', 'divide' or 'multiply', the configuration should also contain:
%   cfg.scalar    = scalar value to be used in the operation
%   cfg.matrix    = matrix with identical size as the data, it will be element-wise be applied
%
% The operation 'add' is implemented as follows
%   y = x1 + x2 + ....
% if you specify multiple input arguments, or as
%   y = x1 + s
% if you specify one input argument and a scalar value.
%
% The operation 'subtract' is implemented as follows
%   y = x1 - x2 - ....
% if you specify multiple input arguments, or as
%   y = x1 - s
% if you specify one input argument and a scalar value.
%
% The operation 'divide' is implemented as follows
%   y = x1 ./ x2
% if you specify two input arguments, or as
%   y = x1 / s
% if you specify one input argument and a scalar value.
%
% The operation 'multiply' is implemented as follows
%   y = x1 .* x2
% if you specify two input arguments, or as
%   y = x1 * s
% if you specify one input argument and a scalar value.
%
% To facilitate data-handling and distributed computing you can use
%   cfg.inputfile   =  ...
%   cfg.outputfile  =  ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_DATATYPE

% Copyright (C) 2012-2019, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the initial part deals with parsing the input options and data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% these are used by the ft_preamble/ft_postamble function and scripts
ft_revision = '$Id$';
ft_nargin   = nargin;
ft_nargout  = nargout;

% do the general setup of the function
ft_defaults
ft_preamble init
ft_preamble debug
ft_preamble loadvar varargin
ft_preamble provenance varargin
ft_preamble trackconfig

% the ft_abort variable is set to true or false in ft_preamble_init
if ft_abort
  return
end

type = ft_datatype(varargin{1});
for i=1:length(varargin)
  % check if the input data is valid for this function, that all data types are equal and update old data structures
  varargin{i} = ft_checkdata(varargin{i}, 'datatype', type);
end

% ensure that the required options are present
cfg = ft_checkconfig(cfg, 'required', {'operation', 'parameter'});
cfg = ft_checkconfig(cfg, 'renamed', {'value', 'scalar'});
cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.pow', 'pow'});
cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.coh', 'coh'});
cfg = ft_checkconfig(cfg, 'renamedval', {'funparameter', 'avg.mom', 'mom'});

if ~iscell(cfg.parameter)
  cfg.parameter = {cfg.parameter};
end

if ft_datatype(varargin{1}, 'raw+comp')
    if length(varargin)>1
        ft_error('ft_math does not support more than one input argument if the input data is of type "raw" or "comp"')
    end
end

% this function only works for the upcoming (not yet standard) source representation without sub-structures
if ft_datatype(varargin{1}, 'source')
  % update the old-style beamformer source reconstruction
  for i=1:length(varargin)
    varargin{i} = ft_datatype_source(varargin{i}, 'version', 'upcoming');
  end
  for p = 1:length(cfg.parameter)
    if strncmp(cfg.parameter{p}, 'avg.', 4)
      cfg.parameter{p} = cfg.parameter{p}(5:end); % remove the 'avg.' part
    end
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the actual computation is done in the middle part
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for p=1:length(cfg.parameter)
  if ~issubfield(varargin{1}, cfg.parameter{p})
    ft_error('the requested parameter is not present in the data');
  end
end

% ensure that the data in all inputs has the same channels, time-axis, etc.
tmpcfg = [];
tmpcfg.parameter = cfg.parameter;
[varargin{:}] = ft_selectdata(tmpcfg, varargin{:});
% restore the provenance information
[cfg, varargin{:}] = rollback_provenance(cfg, varargin{:});
% restore the user-specified parameter option
cfg.parameter = tmpcfg.parameter;

for p = 1:length(cfg.parameter)
  dimordtmp{p} = getdimord(varargin{1}, cfg.parameter{p});
  if p>1 && ~strcmp(dimordtmp{1}, dimordtmp{p})
    ft_error('the dimord of multiple parameters must be the same');
  end
end
clear dimordtmp

% construct the output data structure; make sure descriptive fields will get copied over
% some ugly things need to be done in order to get the correct xxxdimord
% fields in the output
fn  = fieldnames(varargin{1});
dimordfields = fn(~cellfun(@isempty, strfind(fn, 'dimord')))';
if numel(dimordfields)==1 && strcmp(dimordfields{1},'dimord')
    % this is OK and counts for most data structures
else
    % this is in the case of one or more xxxdimord fields, in which case
    % only the requested parameters' xxxdimord fields should be returned in
    % the output
    ok = false(1,numel(dimordfields));
    for p = 1:length(cfg.parameter)
        ok(p) = any(~cellfun(@isempty, strfind(dimordfields, cfg.parameter{p})));
    end
    dimordfields = dimordfields(ok);
end
data = keepfields(varargin{1}, [dimordfields {'label', 'labelcmb', 'freq', 'time', 'pos', 'dim', 'transform'}]);

for p = 1:length(cfg.parameter)
  fprintf('selecting %s from the first input argument\n', cfg.parameter{p});
  % create the local variables x1, x2, ...
  for i=1:length(varargin)
    assign_var(sprintf('x%i', i), getsubfield(varargin{i}, cfg.parameter{p}));
  end

  % create the local variables s and m
  s = ft_getopt(cfg, 'scalar');
  m = ft_getopt(cfg, 'matrix');

  % check the dimensionality of m against the input data
  if ~isempty(m)
    for i=1:length(varargin)
      ok = isequal(size(getsubfield(varargin{i}, cfg.parameter{p})),size(m));
      if ~ok, break; end
    end
    if ~ok
      ft_error('the dimensions of cfg.matrix do not allow for element-wise operations');
    end
  end

  % only one of these can be defined at the moment (i.e. not allowing for
  % operations such as (x1+m)^s for now
  if ~isempty(m) && ~isempty(s)
    ft_error('you can either specify a cfg.matrix or a cfg.scalar, not both');
  end

  % touch it to keep track of it in the output cfg
  if ~isempty(s), cfg.scalar; end
  if ~isempty(m), cfg.matrix; end

  % replace s with m, so that the code below is more transparent
  if ~isempty(m)
    s = m; clear m;
  end

  if length(varargin)==1
    switch cfg.operation
      case 'add'
        if isscalar(s)
          fprintf('adding %f to the %s\n', s, cfg.parameter{p});
        else
          fprintf('adding the contents of cfg.matrix to the %s\n', cfg.parameter{p});
        end
        if iscell(x1)
          y = cellplus(x1, s);
        else
          y = x1 + s;
        end

      case 'subtract'
        if isscalar(s)
          fprintf('subtracting %f from the %s\n', s, cfg.parameter{p});
        else
          fprintf('subtracting the contents of cfg.matrix from the %s\n', cfg.parameter{p});
        end
        if iscell(x1)
          y = cellminus(x1, s);
        else
          y = x1 - s;
        end

      case 'multiply'
        if isscalar(s)
          fprintf('multiplying %s with %f\n', cfg.parameter{p}, s);
        else
          fprintf('multiplying %s with the content of cfg.matrix\n', cfg.parameter{p});
        end
        fprintf('multiplying %s with %f\n', cfg.parameter{p}, s);
        if iscell(x1)
          y = celltimes(x1, s);
        else
          y = x1 .* s;
        end

      case 'divide'
        if isscalar(s)
          fprintf('dividing %s by %f\n', cfg.parameter{p}, s);
        else
          fprintf('dividing %s by the content of cfg.matrix\n', cfg.parameter{p});
        end
        if iscell(x1)
          y = cellrdivide(x1, s);
        else
          y = x1 ./ s;
        end

      case 'log10'
        assert(isempty(s), sprintf('cfg.scalar or cfg.matrix are not supported for %s', cfg.operation));
        fprintf('taking the log10 of %s\n', cfg.parameter{p});
        if iscell(x1)
          y = celllog10(x1);
        else
          y = log10(x1);
        end

      case 'abs'
        assert(isempty(s), sprintf('cfg.scalar or cfg.matrix are not supported for %s', cfg.operation));
        fprintf('taking the abs of %s\n', cfg.parameter{p});
        if iscell(x1)
          y = cellabs(x1);
        else
          y = abs(x1);
        end

      otherwise
        % assume that the operation is descibed as a string, e.g. x1^s
        % where x1 is the first argument and s is obtained from cfg.scalar

        arginstr = sprintf('x%i,', 1:length(varargin));
        arginstr = arginstr(1:end-1); % remove the trailing ','
        eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation));

        if ~iscell(varargin{1}.(cfg.parameter{p}))
          % gather x1, x2, ... into a cell-array
          arginval = eval(sprintf('{%s}', arginstr));
          eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation));
          if numel(s)<=1
            y = arrayfun(operation, arginval{:});
          elseif size(s)==size(arginval{1})
            y = feval(operation, arginval{:});
          end
        else
          y = cell(size(x1));
          % do the same thing, but now for each element of the cell-array
          for i=1:numel(y)
            for j=1:length(varargin)
              % rather than working with x1 and x2, we need to work on its elements
              % xx1 is one element of the x1 cell-array
              assign_var(sprintf('xx%d', j), eval(sprintf('x%d{%d}', j, i)))
            end

            % gather xx1, xx2, ... into a cell-array
            arginstr = sprintf('xx%i,', 1:length(varargin));
            arginstr = arginstr(1:end-1); % remove the trailing ','
            arginval = eval(sprintf('{%s}', arginstr));
            if numel(s)<=1
              y{i} = arrayfun(operation, arginval{:});
            else
              y{i} = feval(operation, arginval{:});
            end
          end % for each element
        end % iscell or not

    end % switch

  else

    switch cfg.operation
      case 'add'
        for i=2:length(varargin)
          fprintf('adding the %s input argument\n', nth(i));
          if iscell(x1)
            y = cellplus(x1, varargin{i}.(cfg.parameter{p}));
          else
            y = x1 + varargin{i}.(cfg.parameter{p});
          end
        end

      case 'multiply'
        for i=2:length(varargin)
          fprintf('multiplying with the %s input argument\n', nth(i));
          if iscell(x1)
            y = celltimes(x1, varargin{i}.(cfg.parameter{p}));
          else
            y = x1 .* varargin{i}.(cfg.parameter{p});
          end
        end

      case 'subtract'
        if length(varargin)>2
          ft_error('the operation "%s" requires exactly 2 input arguments', cfg.operation);
        end
        fprintf('subtracting the 2nd input argument from the 1st\n');
        if iscell(x1)
          y = cellminus(x1, varargin{2}.(cfg.parameter{p}));
        else
          y = x1 - varargin{2}.(cfg.parameter{p});
        end

      case 'divide'
        if length(varargin)>2
          ft_error('the operation "%s" requires exactly 2 input arguments', cfg.operation);
        end
        fprintf('dividing the 1st input argument by the 2nd\n');
        if iscell(x1)
          y = cellrdivide(x1, varargin{2}.(cfg.parameter{p}));
        else
          y = x1 ./ varargin{2}.(cfg.parameter{p});
        end

      case 'log10'
        if length(varargin)>2
          ft_error('the operation "%s" requires exactly 2 input arguments', cfg.operation);
        end
        fprintf('taking the log difference between the 2nd input argument and the 1st\n');
        y = log10(x1 ./ varargin{2}.(cfg.parameter{p}));

      otherwise
        % assume that the operation is descibed as a string, e.g. (x1-x2)/(x1+x2)

        % ensure that all input arguments are being used
        for i=1:length(varargin)
          assert(~isempty(regexp(cfg.operation, sprintf('x%i', i), 'once')), 'not all input arguments are assigned in the operation')
        end

        arginstr = sprintf('x%i,', 1:length(varargin));
        arginstr = arginstr(1:end-1); % remove the trailing ','
        eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation));

        if ~iscell(varargin{1}.(cfg.parameter{p}))
          % gather x1, x2, ... into a cell-array
          arginval = eval(sprintf('{%s}', arginstr));
          eval(sprintf('operation = @(%s) %s;', arginstr, cfg.operation));
          if numel(s)<=1
            y = arrayfun(operation, arginval{:});
          else
            y = feval(operation, arginval{:});
          end
        else
          y = cell(size(x1));
          % do the same thing, but now for each element of the cell-array
          for i=1:numel(y)
            for j=1:length(varargin)
              % rather than working with x1 and x2, we need to work on its elements
              % xx1 is one element of the x1 cell-array
              assign_var(sprintf('xx%d', j), eval(sprintf('x%d{%d}', j, i)))
            end

            % gather xx1, xx2, ... into a cell-array
            arginstr = sprintf('xx%i,', 1:length(varargin));
            arginstr = arginstr(1:end-1); % remove the trailing ','
            arginval = eval(sprintf('{%s}', arginstr));
            if numel(s)<=1
              y{i} = arrayfun(operation, arginval{:});
            else
              y{i} = feval(operation, arginval{:});
            end
          end % for each element
        end % iscell or not

    end % switch
  end % one or multiple input data structures

  % store the result of the operation in the output structure
  data = setsubfield(data, cfg.parameter{p}, y);
end % p over length(cfg.parameter)

% certain fields should remain in the output, but only if they are identical in all inputs
keepfield = {'grad', 'elec', 'opto', 'inside', 'trialinfo', 'sampleinfo', 'tri'};
for j=1:numel(keepfield)
  if isfield(varargin{1}, keepfield{j})
    tmp  = varargin{1}.(keepfield{j});
    keep = true;
  else
    keep = false;
  end
  for i=1:numel(varargin)
    if ~isfield(varargin{i}, keepfield{j}) || ~isequal(varargin{i}.(keepfield{j}), tmp)
      keep = false;
      break
    end
  end
  if keep
    data.(keepfield{j}) = tmp;
  end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% deal with the output
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ft_postamble debug
ft_postamble trackconfig
ft_postamble previous   varargin
ft_postamble provenance data
ft_postamble history    data
ft_postamble savevar    data

function assign_var(var, val)
% Note: using an anonymous function as follows does not work in Octave:
%
% **    assign_var = @(var, val) assignin('caller', var, val);
%
% Also using the name 'assign' does not seem to work, hence 'assign_var'

   assignin('caller', var, val);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = nth(n)
if rem(n,10)==1 && rem(n,100)~=11
  s = sprintf('%dst', n);
elseif rem(n,10)==2 && rem(n,100)~=12
  s = sprintf('%dnd', n);
elseif rem(n,10)==3 && rem(n,100)~=13
  s = sprintf('%drd', n);
else
  s = sprintf('%dth', n);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONS for doing math on each element of a cell-array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function z = cellplus(x, y)
if ~iscell(y)
  y = repmat({y}, size(x));
end
z = cellfun(@plus, x, y, 'UniformOutput', false);

function z = cellminus(x, y)
if ~iscell(y)
  y = repmat({y}, size(x));
end
z = cellfun(@minus, x, y, 'UniformOutput', false);

function z = celltimes(x, y)
if ~iscell(y)
  y = repmat({y}, size(x));
end
z = cellfun(@times, x, y, 'UniformOutput', false);

function z = cellrdivide(x, y)
if ~iscell(y)
  y = repmat({y}, size(x));
end
z = cellfun(@rdivide, x, y, 'UniformOutput', false);

function z = celllog10(x)
z = cellfun(@log10, x, 'UniformOutput', false);

function z = cellabs(x)
z = cellfun(@abs, x, 'UniformOutput', false);


text:
classdef SettingsConstitutiveTensorFromVademecum < AbstractSettings

    properties (Access = protected)
        defaultParamsName = 'paramsConstitutiveTensorFromVademecum'
    end

    properties (Access = public)
        fileName
    end

    methods (Access = public)
        function obj = SettingsConstitutiveTensorFromVademecum(varargin)
            switch nargin
                case 1
                    obj.loadParams(varargin{1});
            end
        end
    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function amsg = append_crc(message)
% Appends the crc (Low byte, high byte) to message for modbus
% communication. Message is an array of bytes. Developed for (but not
% limmited to) use with a Watlow 96 controller.
%{
Copyright (c) 2009, Brian Keats All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. * Redistributions in
binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
%}
%
% W. R. Ashurst appended comments:  Usage - the argument 'message' contains
% decimal representation of hex values that comprise the message.  For
% Omega CN7800 at address '004', modbus mode 03 (read 1 register) starting
% address 1000 the message is '040310000001' in hex.  In decimal, it is '4,
% 3, 16, 0, 0, 1'.  The decimal form is passed to this function
% (append_crc) as an array of doubles which gives the result '4 3 16 0 0 1
% 128 159' Thus the MODBUS RTU message to send out via 'fwrite' would be
% [4, 3, 16, 0, 0, 1 128, 159]   I have verified this crc calculation with
% other Omega documentation.  Jan 13, 2012.

N = length(message);
crc = hex2dec('ffff');
polynomial = hex2dec('a001');

for i = 1:N
    crc = bitxor(crc,message(i));
    for j = 1:8
        if bitand(crc,1)
            crc = bitshift(crc,-1);
            crc = bitxor(crc,polynomial);
        else
            crc = bitshift(crc,-1);
        end
    end
end

lowByte = bitand(crc,hex2dec('ff'));
highByte = bitshift(bitand(crc,hex2dec('ff00')),-8);

amsg = message;
amsg(N+1) = lowByte;
amsg(N+2) = highByte;

author: Sable

repo: mcbench-benchmarks


text:
function tfc_data = readBESAtfcs(filename)

% readBESAtfcs reads single trial TFC data exported from BESA Research.
%
% Use as
%   tfc = readBESAtfcs(filename)
%
% The output is a structure containing a 3D matrix with complex numbers
% for every trial. The size of the matrix is
% [NChannels x NFreqSamples x NTimeSamples].
%
% Created June 28, 2012 Todor Jordanov

if isempty(findstr(filename,'.'))

  filename = [filename,'.tfcs'];

end

fp = fopen(filename, 'r');

if (fp)

    tfc_data.trials = {};

    n_trials = 0;
    n_channels = 0;
    n_freqs = 0;

    tline = fgetl(fp);
    tline = strtrim(tline);

    while ischar(tline)

        if(strncmpi(tline, 'Trial', 5))

            n_trials = n_trials + 1;
            n_channels = 0;
            n_freqs = 0;

        elseif(strncmpi(tline, 'Channel', 7))

            n_channels = n_channels + 1;
            n_freqs = 0;

        else

            tline = strtrim(tline);
            tmp = regexp(tline, '\t', 'split');
            n_samples = size(tmp, 2);
            n_freqs = n_freqs + 1;

            for i=1:n_samples

                two_reals = sscanf(tmp{i}, '%f +i* %f');
                tfc_data.trials{n_trials}(n_channels, n_freqs, i) = ...
                    complex(two_reals(1), two_reals(2));

            end

        end

        tline = fgetl(fp);

    end

    fclose(fp);

end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
% icadefs() - function to read in a set of EEGLAB system-wide (i.e. lab-wide)
%             or working directory-wide constants and preferences. Change the
%             way these are defined in the master icadefs.m file (usually
%             in dir eeglab/functions/sigprocfunc) or make a custom copy of
%             the icadefs.m file in a project directory. Then, calling functions
%             that call icadefs from an EEGLAB session in that working directory
%             will read the local copy, which may set preferences different from
%             the system-wide copy.
%
% Author: Arnaud Delorme, Scott Makeig, SCCN/INC/UCSD, La Jolla, 05-20-97

% Copyright (C) 05-20-97 Scott Makeig, SCCN/INC/UCSD, scott@sccn.ucsd.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% ----------------------------------------------------------------------
% ------ EEGLAB DEFINITION - YOU MAY CHANGE THE TEXT BELOW -------------
% ----------------------------------------------------------------------

EEGOPTION_PATH = ''; % if empty, the home folder of the current user is used
                     % Note that this may create problems under Windows
                     % when unicode characters are part of the user name
                     % In this case, enter the path name manually here.

YDIR  = 1;                  % positive potential up = 1; negative up = -1
                            % for most ERP plots

HZDIR = 'up';               % ascending freqs = 'up'; descending = 'down'
                            % (e.g., timef/newtimef frequency direction)

% Checking MATLAB version
tmpvers = version;
indp = find(tmpvers == '.');
if str2num(tmpvers(indp(1)+1)) >= 1, tmpvers = [ tmpvers(1:indp(1)) '0' tmpvers(indp(1)+1:end) ]; end
indp = find(tmpvers == '.');
VERS = str2num(tmpvers(1:indp(2)-1));

% font size
tmpComputer   = computer;
tmpScreenSize = get(0, 'ScreenSize');

% Graph Definitions
DEFAULT_COLORMAP = 'jet';

if VERS < 8.04
    PLOT_LINEWIDTH   = 2;
    PLOT_LINEWIDTH_S = 1;

    % AXES FONTSIZE
    AXES_FONTSIZE   = 10;                % Axis labels and legend font size
    AXES_FONTSIZE_S = AXES_FONTSIZE - 2; % Axis labels and legend font size Small
    AXES_FONTSIZE_L = 16;                % Axis labels and legend font size Large

    % GUI FONTSIZE
    GUI_FONTSIZE    = 10;               % graphic interface font size
    GUI_FONTSIZE_S  = GUI_FONTSIZE - 2; % graphic interface font size Small
    GUI_FONTSIZE_L  = GUI_FONTSIZE + 2; % graphic interface font size Large

    % TEXT FONTSIZE
    TEXT_FONTSIZE = 10;                  % Miscellaneous font sizes
    TEXT_FONTSIZE_S = TEXT_FONTSIZE - 2; % Miscellaneous font sizes Small
    TEXT_FONTSIZE_L = TEXT_FONTSIZE + 2; % Miscellaneous font sizes Large

elseif VERS >= 8.04

    if strcmpi(tmpComputer(1:3), 'MAC')

        PLOT_LINEWIDTH   = 1;
        PLOT_LINEWIDTH_S = 0.5;

        %scale up fontsizes on higher resolution mac screens
        retinaDisplay = false;
        if tmpScreenSize(3) >= 1920 % bump fontsize only for the highest retina res settings
            retinaDisplay = true; %comment this out if you don't want fontsizes increased at high display resolutions
            %disp('Mac OSX retina display detected. If this is not desired comment out line 83 of icadefs.m');
        end

        % AXES FONTSIZE
        if retinaDisplay
          AXES_FONTSIZE   = 12;                 % Axis labels and legend font size
        else
          AXES_FONTSIZE   = 9;                 % Axis labels and legend font size
        end
        AXES_FONTSIZE_S = AXES_FONTSIZE - 2; % Axis labels and legend font size Small
        AXES_FONTSIZE_L = 12.5;              % Axis labels and legend font size Large

        % GUI FONTSIZE
        if retinaDisplay
          GUI_FONTSIZE    = 14;                % graphic interface font size
        else
          GUI_FONTSIZE    = 12;                % graphic interface font size
        end
        GUI_FONTSIZE_S  = GUI_FONTSIZE - 2; % graphic interface font size Small
        GUI_FONTSIZE_L  = GUI_FONTSIZE + 2; % graphic interface font size Large

        % TEXT FONTSIZE
        if retinaDisplay
          TEXT_FONTSIZE   = 14;                 % Miscellaneous font sizes
        else
          TEXT_FONTSIZE   = 12;                 % Miscellaneous font sizes
        end
        TEXT_FONTSIZE_S = TEXT_FONTSIZE - 2; % Miscellaneous font sizes Small
        TEXT_FONTSIZE_L = TEXT_FONTSIZE + 4; % Miscellaneous font sizes Large
    else
        PLOT_LINEWIDTH   = 1;
        PLOT_LINEWIDTH_S = 0.5;

        % AXES FONTSIZE
        AXES_FONTSIZE   = 9;                 % Axis labels and legend font size
        AXES_FONTSIZE_S = AXES_FONTSIZE - 2; % Axis labels and legend font size Small
        AXES_FONTSIZE_L = 12.5;              % Axis labels and legend font size Large

        % GUI FONTSIZE
        GUI_FONTSIZE    = 10;                % graphic interface font size
        GUI_FONTSIZE_S  = GUI_FONTSIZE - 2; % graphic interface font size Small
        GUI_FONTSIZE_L  = GUI_FONTSIZE + 2; % graphic interface font size Large

        % TEXT FONTSIZE
        TEXT_FONTSIZE   = 10;                 % Miscellaneous font sizes
        TEXT_FONTSIZE_S = TEXT_FONTSIZE - 2; % Miscellaneous font sizes Small
        TEXT_FONTSIZE_L = TEXT_FONTSIZE + 4; % Miscellaneous font sizes Large
    end
end

clear retinaDisplay tmpScreenSize tmpComputer tmpvers indp;

% the eeg_options.m file also countains additional options

% ----------------------------------------------------------------------
% ------------------------ END OF DEFINITIONS --------------------------
% ----------------------------------------------------------------------

% INSERT location of ica executable (UNIX ONLY) for binica.m below
if ~isdeployed
    eeglab_p = fileparts(which('eeglab'));
    ICABINARY = fullfile(eeglab_p, 'functions', 'resources', 'ica_linux');
    tmpComputer = computer;
    if strcmpi(tmpComputer(1:3), 'MAC')
        ICABINARY = fullfile(eeglab_p, 'functions', 'resources', 'ica_osx_intel_64');
        clear tmpComputer
    end
else
    ICABINARY = fullfile(ctfroot, 'ica_linux');
end

try
    set(0,'defaultaxesfontsize',AXES_FONTSIZE);
    set(0,'defaulttextfontsize',TEXT_FONTSIZE);
    set(0,'DefaultUicontrolFontSize',GUI_FONTSIZE);
catch
    % most likely Octave here
end

TUTORIAL_URL = 'http://sccn.ucsd.edu/wiki/EEGLAB'; % online version
DEFAULT_SRATE = 256.0175;      % default local sampling rate (rarely used)
DEFAULT_TIMLIM = [-1000 2000]; % default local epoch limits (ms)

% Set EEGLAB figure and GUI colors
% --------------------------------
lowscreendepth = 0;
if ~exist('OCTAVE_VERSION')
    if get(0, 'screendepth') <=8 % if mono or 8-bit color
	lowscreendepth = 1;
    end
end
if lowscreendepth
    %fprintf('icadefs(): Setting display parameters for mono or 8-bit color\n');
    BACKCOLOR           = [1 1 1];    % Background figure color
    BACKEEGLABCOLOR     = [1 1 1];    % EEGLAB main window background
    GUIBUTTONCOLOR      = [1 1 1];    % Buttons colors in figures
    GUIPOPBUTTONCOLOR   = [1 1 1];    % Buttons colors in GUI windows
    GUIBACKCOLOR        = [1 1 1];    % GUI background color
    GUITEXTCOLOR        = [0 0 0];      % GUI foreground color for text
    PLUGINMENUCOLOR     = [.5 0 .5];  % plugin menu color

else % if full color screen
    BACKCOLOR           = [.93 .96 1];    % EEGLAB Background figure color
    BACKEEGLABCOLOR     = [.66 .76 1];    % EEGLAB main window background
    GUIBUTTONCOLOR      = BACKEEGLABCOLOR;% Buttons colors in figures
    GUIPOPBUTTONCOLOR   = BACKCOLOR;      % Buttons colors in GUI windows
    GUIBACKCOLOR        = BACKEEGLABCOLOR;% EEGLAB GUI background color <---------
    GUITEXTCOLOR        = [0 0 0.4];      % GUI foreground color for text
    PLUGINMENUCOLOR     = [.5 0 .5];      % plugin menu color
end

% THE FOLLOWING PARAMETERS WILL BE DEPRECATED IN LATER VERSIONS
% -------------------------------------------------------------

SHRINKWARNING = 1;          % Warn user about the shrink factor in topoplot() (1/0)

MAXENVPLOTCHANS   = 264;  % maximum number of channels to plot in envproj.m
MAXPLOTDATACHANS  = 264;  % maximum number of channels to plot in dataplot.m
MAXPLOTDATAEPOCHS = 264;  % maximum number of epochs to plot in dataplot.m
MAXEEGPLOTCHANS   = 264;  % maximum number of channels to plot in eegplot.m
MAXTOPOPLOTCHANS  = 264;  % maximum number of channels to plot in topoplot.m

DEFAULT_ELOC  = 'chan.locs'; % default electrode location file for topoplot.m
DEFAULT_EPOCH = 10;       % default epoch width to plot in eegplot(s) (in sec)

SC  =  ['binica.sc'];           % Master .sc script file for binica.m
                                % MATLAB will use first such file found
                                % in its path of script directories.
                                % Copy to pwd to alter ICA defaults


text:
function Ic = adjacency2incidence(A)

% adjacency2incidence - convert an adjacency matrix to an incidence matrix
%
%   Ic = adjacency2incidence(A);
%
%   A(i,j) = 1 iff (i,j) is an edge of the graph.
%   For each edge number k of the graph linking (i,j)
%       Ic(i,k)=1 and Ic(j,k)=-1
%
%   Ic is a sparse matrix.
%   Ic is also known as the graph gradient.
%
%   Copyright (c) 2006 Gabriel Peyre

%% compute list of edges
[i,j,s] = find(sparse(A));
I = find(i<=j);
i = i(I);
j = j(I);
% number of edges
n = length(i);
% number of vertices
nverts = size(A,1);

%% build sparse matrix
s = [ones(n,1); -ones(n,1)];
is = [(1:n)'; (1:n)'];
js = [i(:); j(:)];
Ic = sparse(is,js,s,n,nverts);
Ic = Ic';

% fix self-linking problem (0)
a = find(i==j);
if not(isempty(a))
    for t=a'
        Ic(i(t),t) = 1;
    end
end

author: gpeyre

repo: matlab-toolboxes


text:
function [vertex,face,edge,mesh] = mesh_emse2matlab(file,options)

% mesh_emse2matlab - Convert EMSE mesh (.wfr) to matlab format
%
% USEAGE: [vertices,faces,edges,meshtype] = mesh_emse2matlab(file,[options])
%
% All values returned are in meters.  With the returned structures,
% create a vertex & face matrix:
%
%   vertex_matrix = [vertices.x; vertices.y; vertices.z]';
%   face_matrix = [faces.vertex1;faces.vertex2;faces.vertex3]';
%
% These can be input to the patch command:
%
%    Hpatch = patch('Vertices',vertex_matrix,'Faces',face_matrix,...
%                   'EdgeColor',[.6 .6 .6],'FaceColor',[0.9 0.9 0.9]);
%
% See the patch and light commands to colour this object.
%
% 'options' ... a cell array of strings.  By default it contains
% options = {'vertex','face','edge'}.  By default, this routine
% reads all available data from the emse file.  If 'options' is given
% and it doesn't contain one of these strings, that data will not be
% read or returned.
%
% meshtype is: 'unknown','scalp','outer skull','inner skull', or 'cortex'
%

% $Revision: 1.1 $ $Date: 2009-04-28 22:13:57 $

% Licence:  GNU GPL, no implied or express warranties
% History:  10/98 Abbas Kouzani (egazk@flinders.edu.au)
%           09/01 Darren.Weber_at_radiology.ucsf.edu
%                 - created function, rather than script
%                 - added functionality to handle different
%                   minor revisions.
%           03/02 Darren.Weber_at_radiology.ucsf.edu
%                 - optimised fscanf processes for matlab, the
%                   function now operates in less than 1/2 time,
%                   especially for revision 3 data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if ~exist('options','var'),
    options = {'vertex','face','edge'};
end

[path,name,ext] = fileparts(file);
file = fullfile(path,[name ext]);

[fid,msg] = fopen(file,'r');
if ~isempty(msg), error(msg); end

tic;

% Read prolog
version   =fscanf(fid,'%f',1);
file_type =fscanf(fid,'%f',1);
minor_rev =fscanf(fid,'%f',1);

fprintf('...WFR Version = %d, Minor_Revision = %d, File-Type = %d\n',...
    version,minor_rev,file_type);

if ~(file_type==8000 | file_type==4000)
    S=sprintf('Could not convert WFR file type: %d',file_type);
    error(S);
end

% Read header (format depends on minor revision)
if(minor_rev==3)
    type      =fscanf(fid,'%f',1);
else
	radius    =fscanf(fid,'%f',1);
	vertex_no =fscanf(fid,'%d',1);
	face_no   =fscanf(fid,'%d',1);
	edge_no   =fscanf(fid,'%d',1);

    fprintf('...Radius = %f meters\n',radius);
    %...Vertices = %d\n...Patches = %d\n...Edges = %d\n',...
    %    vertex_no,face_no,edge_no);

    if(minor_rev==1), type = 0;
    else,             type = fscanf(fid,'%f',1);
    end
end

if(minor_rev==1)
    mesh = 'unknown';
else
	switch type
        case 0,             mesh = 'unknown';
        case { 64,  40},    mesh = 'scalp';
        case {128,  80},    mesh = 'outer skull';
        case {256, 100},    mesh = 'inner skull';
        case {512, 200},    mesh = 'cortex';
        otherwise,          mesh = 'unknown';
	end
end

fprintf('...Mesh type: %s\n',mesh);

% Read data (format depends on minor revision)
vertex = struct([]);
face = struct([]);
edge = struct([]);

if(minor_rev==3)

    % Read the whole file
    fprintf('...Reading Minor Revision 3 Data File');
    Tmp = fscanf(fid,'%s%f%f%f',[4,inf]);
    fprintf('...done\n');

    % Vertices
    if(max(strcmp('vertex',options)) > 0),
        fprintf('...Creating Vertices Struct');
        % first get the numeric code for 'v'
        vcode = Tmp(1,1);
        % now find all columns of Tmp with vcode in 1st row
        vindex = find(Tmp(1,:) == vcode);

        tmp = Tmp(2:4,vindex);
        tmp = num2cell(tmp);
        vertex = struct(...
            'index', [1:length(vindex)],...
            'x',     tmp( 1,:),...
            'y',     tmp( 2,:),...
            'z',     tmp( 3,:));
        clear tmp;
        fprintf('...done\n');
    else
        fprintf('...Skipping Vertices Struct\n');
    end

    % Faces
    if(max(strcmp('face',options)) > 0),
        fprintf('...Creating Faces Struct');
        % first get the numeric code for 't'
        tcode = Tmp(1,length(vindex)+1);
        % now find all columns of Tmp with tcode in 1st row
        tindex = find(Tmp(1,:) == tcode);

        % matlab vertex indices start at one,
        % not zero, so we add one to these emse values
        tmp = Tmp(2:4,tindex) + 1;

        tmp = num2cell(tmp);
        face = struct(...
            'index',   [1:length(tindex)],...
            'vertex1', tmp( 1,:),...
            'vertex2', tmp( 2,:),...
            'vertex3', tmp( 3,:));
        clear tmp;
        fprintf('...done\n');
    else
        fprintf('...Skipping Faces Struct\n');
    end

    % Edges
    fprintf('...No edges for minor revision 3\n');
    clear Tmp;

elseif(minor_rev~=4)
    % minor revision 1 & 2 format
    disp('...Reading Minor Revision 1 or 2 Data');
    if(max(strcmp('vertex',options)) > 0),
        fprintf('...Reading %d Vertices',vertex_no);

        tmp = zeros(13,vertex_no);
        tmp = fscanf(fid,'%d%x%d%d%g%g%g%g%g%g%g%g%g',[13,vertex_no]);

        tmp(1,:) = tmp(1,:) + 1;
        tmp      = num2cell(tmp);
        vertex   = struct(...
            'index',        tmp( 1,:),...
            'address',      tmp( 2,:),...
            'channel_index',tmp( 3,:),...
            'x',            tmp( 5,:),...
            'y',            tmp( 6,:),...
            'z',            tmp( 7,:),...
            'xnormal',      tmp( 9,:),...
            'ynormal',      tmp(10,:),...
            'znormal',      tmp(11,:),...
            'potential',    tmp(12,:),...
            'curvature',    tmp(13,:));
        clear tmp;
        fprintf('...done\n');
    else
        fprintf('...Skipping %d Vertices\n',vertex_no);
        tmp = zeros(13,vertex_no);
        tmp = fscanf(fid,'%d%x%d%d%g%g%g%g%g%g%g%g%g',[13,vertex_no]);
        clear tmp;
    end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if(max(strcmp('face',options)) > 0),
        fprintf('...Reading %d Faces',face_no);

        tmp = zeros(18,face_no);
        tmp = fscanf(fid,'%d%x%g%g%g%g%g%g%g%g%g%g%x%x%x%x%x%x',[18,face_no]);
        tmp(1,:) = tmp(1,:) + 1;
        tmp      = num2cell(tmp);
        face     = struct(...
            'index',        tmp( 1,:),...
            'address',      tmp( 2,:),...
            'solid_angle',  tmp( 3,:),...
            'magnitude',    tmp( 4,:),...
            'potential',    tmp( 5,:),...
            'area',         tmp( 6,:),...
            'center_x',     tmp( 7,:),...
            'center_y',     tmp( 8,:),...
            'center_z',     tmp( 9,:),...
            'normal_x',     tmp(10,:),...
            'normal_y',     tmp(11,:),...
            'normal_z',     tmp(12,:),...
            'vertex1',      tmp(13,:),...
            'vertex2',      tmp(14,:),...
            'vertex3',      tmp(15,:),...
            'edge1',        tmp(16,:),...
            'edge2',        tmp(17,:),...
            'edge3',        tmp(18,:));
        clear tmp;
        fprintf('...done\n');

        % In minor rev4, the face vertex and edges
        % refer to the vertex.address field, so this
        % is corrected here.  Not sure how to avoid 'for'
        fprintf('...Converting Face vertices from address to index (this takes a while)');
        for i=1:face_no,
            face(i).vertex1 = find([vertex.address] == face(i).vertex1);
            face(i).vertex2 = find([vertex.address] == face(i).vertex2);
            face(i).vertex3 = find([vertex.address] == face(i).vertex3);
        end
        fprintf('...done\n');
        if(max(strcmp('edge',options)) > 0),
            fprintf('...Converting Face edges from address to index (this takes a while)');
            for i=1:face_no,
                face(i).edge1 = find([vertex.address] == face(i).edge1);
                face(i).edge2 = find([vertex.address] == face(i).edge2);
                face(i).edge3 = find([vertex.address] == face(i).edge3);
            end
            fprintf('...done\n');
        end
    else
        disp('...Skipping Faces');
        tmp = zeros(18,face_no);
        tmp = fscanf(fid,'%d%x%g%g%g%g%g%g%g%g%g%g%x%x%x%x%x%x',[18,face_no]);
        clear tmp;
    end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if(max(strcmp('edge',options)) > 0),
        fprintf('...Reading %d Edges',edge_no);

        tmp = zeros(4,edge_no);
        tmp = fscanf(fid,'%d%x%x%x',[4,edge_no]);

        tmp(1,:) = tmp(1,:) + 1;
        tmp      = num2cell(tmp);
        edge     = struct(...
            'index',        tmp(1,:),...
            'address',      tmp(2,:),...
            'vertex1',      tmp(3,:),...
            'vertex2',      tmp(4,:));
        clear tmp;
        fprintf('...done\n');
        fprintf('...Converting Edge vertices from address to index (this takes a while)');
        for i=1:edge_no,
            edge(i).vertex1 = find([vertex.address] == edge(i).vertex1);
            edge(i).vertex2 = find([vertex.address] == edge(i).vertex2);
        end
        fprintf('...done\n');
    else
        disp('...Skipping Edges');
        %for i=1:edge_no,
        %    tmp=fscanf(fid,'%*d',1);
        %    tmp=fscanf(fid,'%*x',3);
        %end
    end
else
    % minor revision 4 format
    disp('...Reading Minor Revision 4 Data');
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if(max(strcmp('vertex',options)) > 0),
        fprintf('...Reading %d Vertices',vertex_no);

        index = meshgrid(1:1:vertex_no,1);
        index = num2cell(index);

        tmp = zeros(11,vertex_no);
        tmp = fscanf(fid,'%d%d%g%g%g%d%g%g%g%g%g',[11,vertex_no]);

        tmp      = num2cell(tmp);
        vertex   = struct(...
            'index',        index,...
            'channel_index',tmp( 1,:),...
            'x',            tmp( 3,:),...
            'y',            tmp( 4,:),...
            'z',            tmp( 5,:),...
            'xnormal',      tmp( 7,:),...
            'ynormal',      tmp( 8,:),...
            'znormal',      tmp( 9,:),...
            'potential',    tmp(10,:),...
            'curvature',    tmp(11,:));
        clear tmp index;
        fprintf('...done\n');
    else
        disp('...Skipping Vertices');
        tmp = zeros(11,vertex_no);
        tmp = fscanf(fid,'%d%d%g%g%g%d%g%g%g%g%g',[11,vertex_no]);
    end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if(max(strcmp('face',options)) > 0),
        fprintf('...Reading %d Faces',face_no);

        index = meshgrid(1:1:face_no,1);
        index = num2cell(index);

        tmp = zeros(16,face_no);
        tmp = fscanf(fid,'%g%g%g%g%g%g%g%g%g%g%d%d%d%d%d%d',[16,face_no]);

        tmp(11:16,:) = tmp(11:16,:) + 1;

        tmp      = num2cell(tmp);
        face     = struct(...
            'index',        index,...
            'solid_angle',  tmp( 1,:),...
            'magnitude',    tmp( 2,:),...
            'potential',    tmp( 3,:),...
            'area',         tmp( 4,:),...
            'center_x',     tmp( 5,:),...
            'center_y',     tmp( 6,:),...
            'center_z',     tmp( 7,:),...
            'normal_x',     tmp( 8,:),...
            'normal_y',     tmp( 9,:),...
            'normal_z',     tmp(10,:),...
            'vertex1',      tmp(11,:),...
            'vertex2',      tmp(12,:),...
            'vertex3',      tmp(13,:),...
            'edge1',        tmp(14,:),...
            'edge2',        tmp(15,:),...
            'edge3',        tmp(16,:));
        clear tmp index;
        fprintf('...done\n');
    else
        disp('...Skipping Faces');
        tmp = zeros(16,face_no);
        tmp = fscanf(fid,'%g%g%g%g%g%g%g%g%g%g%d%d%d%d%d%d',[16,face_no]);
    end
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    if(max(strcmp('edge',options)) > 0),
        fprintf('...Reading %d Edges',edge_no);

        index = meshgrid(1:1:edge_no,1);
        address = num2cell(index * 0);
        index = num2cell(index);

        tmp = zeros(2,edge_no);
        tmp = fscanf(fid,'%d%d',[2,edge_no]);
        tmp = tmp + 1;
        tmp = num2cell(tmp);

        edge = struct(...
            'index',   index,...
            'address', address,...
            'vertex1', tmp(1,:),...
            'vertex2', tmp(2,:));
        clear tmp index address;
        fprintf('...done\n');
    else
        fprintf('...Skipping Edges\n');
        %tmp=fscanf(fid,'%*d',2*edge_no);
    end
end

fclose(fid);
t=toc;
fprintf('...done (%5.2f sec)\n',t);

return

author: PatternRecognition

repo: OpenBMI


text:
function [S,m,psi,chi,del] = ComputeStokesDual(HH,HV,SmoothSize)
%COMPUTESTOKESDUAL Computes Stokes parameters for dual pol complex data

%can be VV/VH as well
[ny,nx] = size(HH);

%Stokes is defines as:
% S(1): Span: HH^2+HV^2
% S(2): Difference: HH^2-HV^2
% S(3): Cov (real): 2*real(HH*HV)
% S(4): Cov (imag): -2*imag(HH*HV)
S = zeros(ny,nx,4);
S(:,:,1) = fastrunmean(abs(HH.*HH)+abs(HV.*HV),[SmoothSize SmoothSize],'mean');
S(:,:,2) = fastrunmean(abs(HH.*HH)-abs(HV.*HV),[SmoothSize SmoothSize],'mean');
S(:,:,3) = fastrunmean(2*real(HH.*conj(HV)),[SmoothSize SmoothSize],'mean');
S(:,:,4) = fastrunmean(-2*imag(HH.*conj(HV)),[SmoothSize SmoothSize],'mean');

%sum of Stokes 2-4 divided by span
m = sqrt(S(:,:,2).^2 + S(:,:,3).^2 + S(:,:,4).^2)./S(:,:,1);

%psi is the orientation angle between 2/3
psi = atan2d(S(:,:,3),S(:,:,2))/2;

chi = asind(S(:,:,4)./(m.*S(:,:,1)))/2;

%del is the phase angle between H & V
del = atan2d(S(:,:,4),S(:,:,3));

end

author: ngageoint


text:
function [FxT_N, FyT_N] = TireModel(lambda_perc, alpha_rad, Fz_N, PacFrontLat, PacRearLat, PacFrontLong, PacRearLong)
  % Pacjeka tire model based on a four coefficient approach
  % evaluates the lateral and longitudinal tire forces using the specified
  % pacjeka models for front and rear

  % initialize
  FxT_N = zeros(4, 1);
  FyT_N = zeros(4, 1);

  FxT_N(1:2) = PacModel(lambda_perc(1:2)./100, PacFrontLong, Fz_N(1:2));
  FxT_N(3:4) = PacModel(lambda_perc(3:4)./100, PacRearLong, Fz_N(3:4));
  FyT_N(1:2) = PacModel(alpha_rad(1:2), PacFrontLat, Fz_N(1:2));
  FyT_N(3:4) = PacModel(alpha_rad(3:4), PacRearLat, Fz_N(3:4));
end

function F = PacModel(x, Pac, Fz_N)
% evaluate the pacejka model for a given slip quantity x and pacejka coefficients Pac
% http://www.edy.es/dev/docs/pacejka-94-parameters-explained-a-comprehensive-guide/

% in addition, Pac(6) provides a factor load degressivity: eps_load <= 0

  F = Fz_N.*(Pac(3)+Pac(6)*((Fz_N-Pac(5))/Pac(5))).*sin(Pac(2).*atan(Pac(1).*x - Pac(4).*(Pac(1).*x - atan(Pac(1).*x))));

end

author: TUMFTM


text:
function t = chanhandle(varargin)
% T = CHANHANDLE; Constructor for class CHANHANDLE
% Chanhandle class contains channel-specific information only.
% An object belonging to chanhandle has the following properties:
%   ChannelNumber
%   Sensitivity
%   SensorInfo
% Usage:
% t = chanhandle; Default values
% t = chanhandle(t1); where t1 is a chanhandle
% t = chanhandle(fname,channelnum); where fname is name of the sqd file
% See also,
% @chanhandle/get.m,set.m,writechanloc.m

% Note:
% Object structure:
% Chanhandle can be a handle to only one channel, or several channels.
% To accomodate an object array, the object is structured as follows:
% Chanhandle_obj has only one field - "handle". Subfields of "handle" are
% the above named properties. ie
% ChanHandle_Obj ->
%       handle   ->
%           ChannelNumber
%           Sensitivity
%           SensorInfo
% When the ChanHandle_obj contains several channels, "handle" is an array of
% structures.
%
% Also, note that:
% The ChannelNumber subfield indicates the hardware channel number. Whereas, the
% index of handle is software index to it. The index of handle is monotonically
% increasing from 1. So Chanhandle_obj contains HwChannels = 0,1,3
% then  handle(1) -> HwChannel = 0
%       handle(2) -> HwChannel = 1
%       handle(3) -> HwChannel = 3
% ChanHandle_obj is be indexed as the "handle" substructure.
%
% For internal use only, an additional way of initialising object:
%   t = chanhandle(handle); where "handle" is a structure with the channel's info
%       Fields for "handle": ChannelNumber,Sensitivity,SensorInfo

% initialize the fields of the object to default values
t.handle.ChannelNumber             = 0; % hardware channel number (0-191)
t.handle.Sensitivity               = []; % Sensitivity Gain/Offset
t.handle.SensorInfo                = []; % type,position,size,etc. of sensor

% Define class definition
t = class(t,'chanhandle');
switch nargin
case 0
    % Default object, return
case 1
    if isa(varargin{1},'chanhandle'), % if argin = chanhandle_obj
        t = varargin{1};
    elseif ischar(varargin{1})        % if argin = sqd-filename
        fname = varargin{1};
        t.handle = readsqdinfo(t.handle,varargin{1});
    elseif isstruct(varargin{1})      % if argin = "handle" substructure
        t.handle = varargin{1};
    else
        error('Incorrect input to chanhandle.m');
    end;
case 2                                  % if argin = sqd-filename,channelnumber
    if ischar(varargin{1})&isnumeric(varargin{2})
        for i = 1:length(varargin{2})
            t.handle(i).ChannelNumber = varargin{2}(i);
            if ~isempty(varargin{1})    % In case no file name is passed - default values
                t.handle(i) = readsqdinfo(t.handle(i),varargin{1});
            end;
        end;
    else
        error('Incorrect inputs to chanhandle.m');
    end;
otherwise
    error('Incorrect inputs to chanhandle.m');
end;

function t = readsqdinfo(t,fname)
% T = READSQDINFO(T,FNAME); Update values of CHANHANDLE object 'T'
% to those given in sqd-file FNAME

seekset=-1; % Start point for fseek: -1 => beginning of the file

if nargin<2|~ischar(fname),error('Incorrect arguments');end;

% open file as binary and little endian
fid = fopen(fname,'rb','l');
if fid==-1,
    disp('File not found');
    [f,p] = uigetfile('*.sqd','MEG160 files');
    if ((~isstr(f)) | ~min(size(f))),
        t = [];
        return;
    end;
    fname = [p f];
    t.FileName = [p f];
    fid = fopen(fname,'rb','l');
end;

%Read in info regarding sensitivity of sensors
t.Sensitivity   = sensitivityinfo(fid,seekset,t.ChannelNumber);
% Read in sensor location
t.SensorInfo    = sensorinfo(fid,seekset,t.ChannelNumber);

% Close file
fclose(fid);


text:
function T = vertcat(varargin)
% overloads [T1,T2,T3..]

T = cat(1,varargin{:});

author: mtex-toolbox

repo: mtex

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


text:
function fiff_write_dig_file(filename,lpa,nas,rpa,hpi,eeg,eegref,extra)
%
% function fiff_write_dig_file(filename,lpa,nas,rpa,hpi,eeg,eegref,extra)
%
% Create a fif file containing the Polhemus data
%
% filename      Output file name
%
% The following need to be specified in the Neuromag MEG
% coordinate system in meters
%
% lpa           Left auricular point
% nas           Nasion
% rpa           Right auricular point
% hpi           HPI coil locations               (optional)
% eeg           EEG electrode locations          (optional)
% eegref        EEG reference electrode location (optional)
% extra         Additional head surface points   (optional)
%

%
%   Author : Matti Hamalainen, MGH Martinos Center
%   License : BSD 3-clause
%
%   Revision 1.1  2008/06/04 16:23:24  msh
%   Added fiff_write_dig_file.m
%
%

%
me   = 'MNE:mne_create_dig_file';
%
global FIFF;
if isempty(FIFF)
   FIFF = fiff_define_constants();
end
%
%   Start writing...
%
fid  = fiff_start_file(filename);
%
% Make the transform to bring LPA and RPA to the x axis and nasion
% to the y axis
%
d1 = nas - lpa;
d2 = rpa - lpa;

alpha = d1*d2'/(d2*d2');
r0 = (1-alpha)*lpa + alpha*rpa;     % Origin is where nasion projects on the LPA - RPA line
ex = d2/sqrt(d2*d2');               % x axis through the auricular points, positive from left to right
ey = (nas-r0);                      % y axis points from the origin to the nasion
ey = ey/sqrt(ey*ey');               % Normalize
ez = cross(ex,ey);                  % Use cross product to get a right-handed coordinate system

T = inv([ ex 0 ; ey 0 ; ez 0 ; r0 1 ]);
% The above gives the coordinate transform from the Neuromag coordinates to the
% Polhemus data coordinates; inverse is needed to go the other way
T = T(:,1:3);   % We just need the first three columns because the result is not an augmented vector

%
% Ready to start
%
fiff_start_block(fid,FIFF.FIFFB_ISOTRAK);

fiff_write_int(fid,FIFF.FIFF_MNE_COORD_FRAME,FIFF.FIFFV_COORD_HEAD);

d.kind  = FIFF.FIFFV_POINT_CARDINAL;
d.ident = FIFF.FIFFV_POINT_LPA;
d.r     = [lpa 1]*T;
fiff_write_dig_point(fid,d);

d.kind  = FIFF.FIFFV_POINT_CARDINAL;
d.ident = FIFF.FIFFV_POINT_NASION;
d.r     = [nas 1]*T;
fiff_write_dig_point(fid,d);

d.kind  = FIFF.FIFFV_POINT_CARDINAL;
d.ident = FIFF.FIFFV_POINT_RPA;
d.r     = [rpa 1]*T;
fiff_write_dig_point(fid,d);

fprintf(1,'Wrote the fiducial locations\n');

if exist('hpi','var')
   for k = 1:size(hpi,1)
      d.kind  = FIFF.FIFFV_POINT_HPI;
      d.ident = k;
      d.r     = [hpi(k,:) 1]*T;
      fiff_write_dig_point(fid,d);
   end
   if (size(hpi,1) > 0)
      fprintf(1,'Wrote %d HPI coil locations\n',size(hpi,1));
   end
end

if exist('eeg','var')
   if exist('eegref','var') && ~isempty(eegref)
      d.kind  = FIFF.FIFFV_POINT_EEG;
      d.ident = 0;
      d.r     = [eegref 1]*T;
      fiff_write_dig_point(fid,d);
      fprintf(1,'Wrote EEG reference electrode location\n');
   end
   for k = 1:size(eeg,1)
      d.kind  = FIFF.FIFFV_POINT_EEG;
      d.ident = k;
      d.r     = [eeg(k,:) 1]*T;
      fiff_write_dig_point(fid,d);
   end
   if (size(eeg,1) > 0)
      fprintf(1,'Wrote %d EEG electrode locations\n',size(eeg,1));
   end
end

if exist('extra','var')
   for k = 1:size(extra,1)
      d.kind  = FIFF.FIFFV_POINT_EXTRA;
      d.ident = k;
      d.r     = [extra(k,:) 1]*T;
      fiff_write_dig_point(fid,d);
   end
   if (size(extra,1) > 0)
      fprintf(1,'Wrote %d extra points\n',size(extra,1));
   end
end

fiff_end_block(fid,FIFF.FIFFB_ISOTRAK);

fiff_end_file(fid);


text:
function lineArray = read_mixed_csv(fileName,delimiter)
  fid = fopen(fileName,'r');   %# Open the file
  lineArray = cell(100,1);     %# Preallocate a cell array (ideally slightly
                               %#   larger than is needed)
  lineIndex = 1;               %# Index of cell to place the next line in
  nextLine = fgetl(fid);       %# Read the first line from the file
  while ~isequal(nextLine,-1)         %# Loop while not at the end of the file
    lineArray{lineIndex} = nextLine;  %# Add the line to the cell array
    lineIndex = lineIndex+1;          %# Increment the line index
    nextLine = fgetl(fid);            %# Read the next line from the file
  end
  fclose(fid);                 %# Close the file
  lineArray = lineArray(1:lineIndex-1);  %# Remove empty cells, if needed
  for iLine = 1:lineIndex-1              %# Loop over lines
    lineData = textscan(lineArray{iLine},'%s',...  %# Read strings
                        'Delimiter',delimiter);
    lineData = lineData{1};              %# Remove cell encapsulation
    if strcmp(lineArray{iLine}(end),delimiter)  %# Account for when the line
      lineData{end+1} = '';                     %#   ends with a delimiter
    end
    lineArray(iLine,1:numel(lineData)) = lineData;  %# Overwrite line data
  end
end

author: zhouyuanzxcv

repo: Hyperspectral