diff --git a/.github/workflows/linkcheck.yml b/.github/workflows/linkcheck.yml index 040a81c..68332d8 100644 --- a/.github/workflows/linkcheck.yml +++ b/.github/workflows/linkcheck.yml @@ -11,8 +11,9 @@ jobs: check-links: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: gaurav-nelson/github-action-markdown-link-check@v1 + - uses: actions/checkout@v4 + - uses: tcort/github-action-markdown-link-check@v1 + # This step does not check doi.org links with: use-quiet-mode: 'yes' use-verbose-mode: 'no' @@ -20,3 +21,19 @@ jobs: folder-path: 'docs/installation, docs/tutorials' file-path: './README.md, ./docs/index.md' base-branch: main + - uses: tcort/github-action-markdown-link-check@v1 + # This step only checks doi.org links + # -> for doi.org links, if the doi does not exist, 404 is returned + # otherwise, it redirects to the publisher website, so any + # code that is not 404 is a "success". + # We do this because some publisher websites (e.g. wiley) are + # peaky and return 403 when the website is not accessed from a + # proper browser. + if: always() + with: + use-quiet-mode: 'yes' + use-verbose-mode: 'no' + config-file: '.markdown-link-check-doi.json' + folder-path: 'docs/installation, docs/tutorials' + file-path: './README.md, ./docs/index.md' + base-branch: main diff --git a/.markdown-link-check-doi.json b/.markdown-link-check-doi.json new file mode 100644 index 0000000..aa2e2b2 --- /dev/null +++ b/.markdown-link-check-doi.json @@ -0,0 +1,8 @@ +{ + "ignorePatterns": [ + { + "pattern": "^(?!https?://doi.org)" + } + ], + "aliveStatusCodes": [200,206,403,503] +} diff --git a/.markdown-link-check.json b/.markdown-link-check.json index 3d00221..03ae8ab 100644 --- a/.markdown-link-check.json +++ b/.markdown-link-check.json @@ -2,6 +2,9 @@ "ignorePatterns": [ { "pattern": "^(?!http)" + }, + { + "pattern": "^https?://doi.org" } ], "aliveStatusCodes": [200,206,503], diff --git a/docs/assets/css/extra.css b/docs/assets/css/extra.css index 037b7fa..92e4c11 100644 --- a/docs/assets/css/extra.css +++ b/docs/assets/css/extra.css @@ -1,7 +1,45 @@ .md-typese__table { min-width: 100%; } - + .md-typeset table:not([class]) { display: table; -} \ No newline at end of file +} + +/* Admonition Matlab */ +:root { + --md-admonition-icon--matlab: url('data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%3C!--%20Uploaded%20to%3A%20SVG%20Repo%2C%20www.svgrepo.com%2C%20Generator%3A%20SVG%20Repo%20Mixer%20Tools%20--%3E%3Csvg%20width%3D%22800px%22%20height%3D%22800px%22%20viewBox%3D%220%200%2032%2032%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22a%22%20x1%3D%2216.803%22%20y1%3D%2216.631%22%20x2%3D%2215.013%22%20y2%3D%2222.411%22%20gradientTransform%3D%22matrix(1%2C%200%2C%200%2C%20-1%2C%200%2C%2032)%22%20gradientUnits%3D%22userSpaceOnUse%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%23512%22%2F%3E%3Cstop%20offset%3D%220.23%22%20stop-color%3D%22%23523%22%2F%3E%3Cstop%20offset%3D%220.36%22%20stop-color%3D%22%23534%22%2F%3E%3Cstop%20offset%3D%220.51%22%20stop-color%3D%22%23645%22%2F%3E%3Cstop%20offset%3D%220.66%22%20stop-color%3D%22%23568%22%2F%3E%3Cstop%20offset%3D%220.84%22%20stop-color%3D%22%2329d%22%2F%3E%3C%2FlinearGradient%3E%3ClinearGradient%20id%3D%22b%22%20x1%3D%2229.71%22%20y1%3D%2218.983%22%20x2%3D%2211.71%22%20y2%3D%2214.563%22%20gradientUnits%3D%22userSpaceOnUse%22%3E%3Cstop%20offset%3D%220.081%22%20stop-color%3D%22%23c33%22%2F%3E%3Cstop%20offset%3D%220.189%22%20stop-color%3D%22%23de5239%22%2F%3E%3Cstop%20offset%3D%220.313%22%20stop-color%3D%22%23f06e3e%22%2F%3E%3Cstop%20offset%3D%220.421%22%20stop-color%3D%22%23fa8042%22%2F%3E%3Cstop%20offset%3D%220.5%22%20stop-color%3D%22%23fe8643%22%2F%3E%3Cstop%20offset%3D%220.58%22%20stop-color%3D%22%23fa7f42%22%2F%3E%3Cstop%20offset%3D%220.696%22%20stop-color%3D%22%23ef6c3e%22%2F%3E%3Cstop%20offset%3D%220.833%22%20stop-color%3D%22%23dc4c37%22%2F%3E%3Cstop%20offset%3D%220.916%22%20stop-color%3D%22%23cf3633%22%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Ctitle%3Efile_type_matlab%3C%2Ftitle%3E%3Cpath%20d%3D%22M2%2C17.55l7.97-3.22a20.7%2C20.7%2C0%2C0%2C1%2C2.72-2.95c.66-.35%2C1.9-.16%2C4.17-2.98%2C2.2-2.75%2C2.9-5.1%2C3.93-5.1%2C1.63%2C0%2C2.83%2C3.52%2C4.65%2C8.85A115.629%2C115.629%2C0%2C0%2C0%2C30%2C24.12c-1.9-1.77-3.52-3.68-5.37-3.63-1.72.04-3.63%2C2.08-5.72%2C4.7-1.66%2C2.1-3.86%2C3.54-4.72%2C3.51%2C0%2C0-2.22-6.28-4.08-7.3a2.641%2C2.641%2C0%2C0%2C0-2.39.2L2%2C17.54Z%22%20style%3D%22fill%3A%2349d%22%2F%3E%3Cpath%20d%3D%22M19.8%2C4.02c-.67.9-1.48%2C2.55-2.94%2C4.38-2.27%2C2.82-3.5%2C2.63-4.17%2C2.98a19.674%2C19.674%2C0%2C0%2C0-2.72%2C2.95l3.3%2C2.41c2.8-3.82%2C4.3-7.96%2C5.47-10.64A13.579%2C13.579%2C0%2C0%2C1%2C19.8%2C4.02Z%22%20style%3D%22fill%3Aurl(%23a)%22%2F%3E%3Cpath%20d%3D%22M20.8%2C3.3c-2.18%2C0-3.67%2C11.48-11.72%2C17.89%2C2.26-.37%2C4.22%2C5.24%2C5.12%2C7.51%2C4-.68%2C7.2-8.33%2C10.43-8.21%2C1.85.07%2C3.47%2C1.86%2C5.37%2C3.63C25.66%2C15%2C23.63%2C3.3%2C20.8%2C3.3Z%22%20style%3D%22fill%3Aurl(%23b)%22%2F%3E%3C%2Fsvg%3E') +} +.md-typeset .admonition.matlab, +.md-typeset details.matlab { + border-color: rgb(255, 165, 0); +} +.md-typeset .matlab > .admonition-title, +.md-typeset .matlab > summary { + background-color: rgba(255, 165, 0, 0.1); +} +.md-typeset .matlab > .admonition-title::before, +.md-typeset .matlab > summary::before { + background-color: rgb(255, 165, 0); + -webkit-mask-image: var(--md-admonition-icon--matlab); + mask-image: var(--md-admonition-icon--matlab); +} + +/* Admonition Python */ +:root { + --md-admonition-icon--python: url('https://upload.wikimedia.org/wikipedia/commons/c/c3/Python-logo-notext.svg') +} +.md-typeset .admonition.python, +.md-typeset details.python { + border-color: rgb(84, 129, 176); +} +.md-typeset .python > .admonition-title, +.md-typeset .python > summary { + background-color: rgba(84, 129, 176, 0.1); +} +.md-typeset .python > .admonition-title::before, +.md-typeset .python > summary::before { + background-color: rgb(84, 129, 176); + -webkit-mask-image: var(--md-admonition-icon--python); + mask-image: var(--md-admonition-icon--python); +} diff --git a/docs/python/api/spm/index.md b/docs/python/api/spm/index.md new file mode 100644 index 0000000..0eab6d8 --- /dev/null +++ b/docs/python/api/spm/index.md @@ -0,0 +1,97211 @@ +Module spm +========== + +Sub-modules +----------- +* spm.spm_logo +* spm.utils + +Functions +--------- + +### `ADEM_SHC_demo` + +```{text} + This demo illustrates the use of Lotka-Volterra form SHCs (Stable + heteroclinic channel) to prescribe active sampling (inference). In this + example each (unstable) fixed point in the SHC attracts the agent to + points on the circumference of a circle. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_SHC_demo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_cost_SHC` + +```{text} + This demo illustrates the use of priors on the motion of hidden states as + polices. It simulates exploration and exploitation using radial basis + function attractors and auto-vitiative (self-destroying) attractors + as the basis of the prior. These dynamics enforce exploration, under + active inference. In turn, this exploration enables perceptual learning + to associate attractors with changes in physiological states (cf, + rewards). This can be exploited to by formal priors to ensure regions of + physiological state-space are avoided. + We look at this scheme using simulated pathology; first, we simulate a + (neurodegenerative) reduction in log-precision (cf Parkinson's disease) on + the motion of physical states. This results in active inference with + a loss of precise volitional movement and subsequent failure to optimise + physiological states. Second, we look at the effects of precision on + learning by increasing log-precision (cf, Addition) on the motion of + physiological states. This results in a failure to learn and, again, + subsequent failure to optimise physiological states. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_cost_SHC.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_cued_response` + +```{text} + Cued responses under active inference: + __________________________________________________________________________ + This demo illustrates cued sequential movements. It uses active inference + under a hierarchal generative model of sequential cues and consequent + movements. The agent has a (second level) model of (two) contingencies or + contexts; these correspond to the sequential appearance of targets in a + clockwise direction. The other context has no sequential aspect. The + first level model is contextually modulated to produce the appropriate + sequence of (location - specific) affordances, which predict both + visual and proprioceptive consequences. This is sufficient to engender + cued reaching movements, which are slightly anticipatory if the agent + infers the correct probabilistic context. However, if we reverse the + order of the stimuli there is an accuracy and reaction time cost, due to + the fact that the sequence is unpredictable. Furthermore, there is a + set switching cost as the hidden states at the second (contextual) level + are inferred. This provides a simple but very rich model of cued reaching + movements and set switching that is consistent with notions of salience + and affordance. Furthermore, we can simulate Parkinsonism by + reducing the precision of affordance - based cues. These are the visual + attributes that confer saliency on the current target. Reducing this + precision (for example, dopamine) delays and can even preclude set + switching, with associated costs in pointing accuracy. By completely + removing the precision of the salience or affordance cues, we obtain + autonomous behaviour that is prescribed by the itinerant expectations of + the agent. This can be regarded as perseveration in a pathological + setting or the emission of autonomous behaviour in the absence of any + precise sensory information + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_cued_response.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_eyeblink` + +```{text} + Simulation of eyeblink conditioning + FORMAT DEM = ADEM_eyeblink(OPTION) + + OPTION: + case{'EYEBLINK'} : spontaneous eye blinking + case{'AIRPUFF'} : unconditioned eyeblink response to air puff + case{'STARTLE'} : unconditioned startle response to a sound + case{'TRACE'} : trace conditioning to the sound + case{'DELAY'} : delay conditioning to the sound + case{'EXTINCTION'} : extinction of trace conditioning to sound + + __________________________________________________________________________ + + This demonstration routine illustrates Pavlovian learning under active + inference. It uses the eyeblink conditioning paradigm to model startle + responses and the subsequent acquisition of an eyeblink - under delay and + trace learning. The various options above determine the nature of the + simulation (or edit the OPTION below). The generative model, in this + example, starts with a heteroclinic cycle with an inset. The cycle per se + generates autonomous eyeblinks periodically, while the inset is + activated by a conditioned stimulus (CS). The subsequent unstable fixed + points play the role of an echo-state and enables the learning or + association of a high-level hidden cause with subsequent unconditioned + responses (UR). + + In active inference, an unconditioned response corresponds to a prior + belief that a hidden state will generate action and the unconditioned + stimulus (US). Pavlovian conditioning is the learning of the Association + between a conditioned stimulus (CS) and the unconditioned response. The + dynamics entailed by the heteroclinic cycle enable trace conditioning, + which may be related to hippocampal function. + + In this example, there are two levels with the hidden states at the first + level modelling beliefs about eyeblinks, unconditioned responses and + unconditioned stimuli. Proprioceptive predictions are generated by + beliefs about ensuing eyeblinks and unconditioned responses (which + also predict the conditioned stimulus. Hidden states at the second level + embody a sense of time through Lotka-Volterra dynamics. Successive epochs + of time are passed to the first level via a softmax transform. Learning + corresponds to Hebbian plasticity (that minimises free energy) in the + connections between the state unit encoding expectations about a UR and + expectations about the CS (for delay conditioning) and heteroclinic + states (for trace conditioning): see the functions at the end of this + routine. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_eyeblink.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_learning` + +```{text} + Value learning demo using the mountain car problem. This demo questions + the need for reinforcement learning and related paradigms from + machine-learning, when trying to optimise the behaviour of an agent. We + show that it is fairly simple to teach an agent complicated and adaptive + behaviours under the free-energy principle. This principle suggests that + agents adjust their internal states and sampling of the environment to + minimize their free-energy. In this context, free-energy represents a + bound on the probability of being in a particular state, given the nature + of the agent, or more specifically the model of the environment an agent + entails. We show that such agents learn causal structure in the + environment and sample it in an adaptive and self-supervised fashion. + The result is a behavioural policy that reproduces exactly the policies + that are optimised by reinforcement learning and dynamic programming. + Critically, at no point do we need to invoke the notion of reward, value + or utility. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_learning.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_lorenz` + +```{text} + Action-DEM demo specifying an attractor (in terms of the parameters of + desired equations of motion) This demo first exposes an agent to a Lorenz + attractor world such that it can learn the three parameters of the Lorenz + system. It is then placed in a test world with a fixed point attractor to + see if it has remembered the chaotic dynamics it learnt in the training + environment + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_lorenz.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_lorenz_entropy` + +```{text} + This demo shows how structure can be instilled from an environment. It + uses an agent that optimises its recognition density over successive + epochs of exposure to an environment. This environment causes the agent + to flow on a Lorenz attractor with random perturbations. As the agent + learns the causal regularities in its environment, it is better able to + predict them and act to oppose the random effect. The result is that it + is more robust to random forces and therefore exhibits states with lower + entropy. This routine takes several minutes to run. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_lorenz_entropy.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_lorenz_surprise` + +```{text} + This demo computes the cost-function (negative reward) for a Lorenz + system; to show cost can be computed easily from value (negative + surprise or sojourn time). However, value is not a Lyapunov function + because the flow is not curl-free (i.e., is not irrotational). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_lorenz_surprise.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_motor` + +```{text} + This demo illustrates how action can fulfil prior expectations by + explaining away sensory prediction errors prescribed by desired movement + trajectory. It is based on the same linear convolution model of the + motor plant considered in the visual tracking example. Here, we induce + prediction errors; not through exogenous perturbation to sensory input + but through tight priors encoding a desired or expected trajectory. We + then show how the movement is robust to changes in the true motor + dynamics and other exogenous perturbations, late in movement execution + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_motor.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_mountaincar_loss` + +```{text} + This demo re-visits the mountain car problem to show that adaptive + (desired) behaviour can be prescribed in terms of loss-functions (i.e. + reward functions of state-space). + It exploits the fact that under the free-energy formulation, loss is + divergence. This means that priors can be used to make certain parts of + state-space costly (i.e. with high divergence) and others rewarding (low + divergence). Active inference under these priors will lead to sampling of + low cost states and (apparent) attractiveness of those states. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_mountaincar_loss.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_observe` + +```{text} + This demo illustrates action-observation using synthetic writing under + active inference. It shows how expectations about hidden states can be + both cause and consequence of observed action (of self and others + respectively). We first illustrate the generation of behaviour using a + Lotka-Volterra form stable heteroclinic orbit. We then reproduce the + same forces on the agent's arm but switching off the precision of + proprioceptive inputs. This can be seen as attending selectively to + visual inputs. The resulting inference calls upon the same hidden-states + and implicit predictions (in a generalised or dynamic sense). These + simulations can be regarded as simulations of mirror neuron responses. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_observe.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_occlusion` + +```{text} + Slow pursuit and occlusion under active inference: + __________________________________________________________________________ + This demo illustrates slow pursuit in the context of visual occlusion. We + start with a simulation of canonical slow pursuit of a visual target + with sine wave motion. Crucially, the generative model is equipped with + a simple empirical prior encoding the hidden motion of the target (using + a linear oscillator, whose frequency is determined by a hidden cause). + We then examine failures of tracking and anticipation during occlusion + and when the target re-emerges from behind the occluder. We look at a + simulation in which the precision of the oscillator dynamics modelling + long-term behaviour of the target is reduced (cf., neuromodulatory + deficits in cortical areas encoding biological motion). This has a + an effect of producing a failure of pursuit, resulting in a catch-up + saccade on target reappearance. The suppression of prior precision can + however have beneficial effects when motion is itself unpredicted + (as shown with differential pursuit performance under a reversal of + the trajectory towards the end of motion). Finally, we look at how prior + beliefs are acquired during exposure to the target - in terms of + cumulative inference on the hidden causes encoding the frequency of + periodic motion. This can be regarded as a high order form of evidence + accumulation. Importantly, this (experience-dependent) inference is + markedly impaired by the simulated lesion to precision above. In other + words, a single failure of inference in modelling the motion of hidden + states can have secondary consequences - such as a failure to even + register and remember regularities. All these simulations are based upon + active inference; with the prior belief that the centre of gaze is + attracted to the same point responsible for target motion. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_occlusion.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_occulomotor_delays` + +```{text} + Oculomotor following and delays under active inference: + __________________________________________________________________________ + This demo illustrates oculomotor following and slow pursuit. The focus + here is on oculomotor delays and their compensation in generalised + coordinates of motion. This is illustrates using a 'sweep' of motion to + examine the effects of motor delays, sensory delays and their interaction + under active inference. We then move on to oculomotor following of sine + wave motion, in which the trajectory entrains following under compensated + dynamics. This entrainment can be destroyed by rectifying the sine wave + which calls for a more realistic (hierarchical) model of motion that + registers its phase and anticipates the next onset of motion (cf + movement behind an occluder). These simulations depend delicately on + delays and precisions (gains) that are chosen to make oculomotor following + under uncertainty relatively slow. The dependency on visual uncertainty + (contrast) is illustrated by changing the precision of the generalised + motion of the sensory target. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_occulomotor_delays.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_plaid` + +```{text} + creates a Gaussian modulated n x n visual plaid stimulus + FORMAT [y,n] = ADEM_plaid(x,[n]) + x(1) - horizontal displacement + x(2) - vertical displacement + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_plaid.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_pursuit` + +```{text} + Slow pursuit under active inference: + __________________________________________________________________________ + This demo illustrates slow pursuit eye movements under active inference. + Its focus is on frames of references and the entrainment of gaze- + direction by the motion of a visual target. The generative process (and + model) is based upon the itinerant trajectory of a target (in Cartesian + coordinates) produced by Lotka-Volterra dynamics. The agent expects its + sampling (in polar coordinates) to be centred on the target. Here, the + agent is equipped with a model of the trajectory and the oculomotor + plant. This means it represents both the location of the target and the + mapping from target location (in relation to a fixation point) to + egocentric polar coordinates. We simulate behavioural (saccadic) and + electrophysiological (ERP) responses to expected and unexpected changes + in the direction of a target moving on the unit circle. The agent expects + the target to reverse its direction during the trajectory but when this + reversal is omitted (and the target) persists in a clockwise direction) + violation responses are emitted. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_pursuit.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_reaching` + +```{text} + This demo illustrates how action can fulfil prior expectations by + explaining away sensory prediction errors prescribed by desired movement + trajectories. In this example a two-joint arm is trained to touch a target + so that spontaneous reaching occurs after training. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_reaching.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_salience` + +```{text} + Saccadic eye movements under active inference + __________________________________________________________________________ + This demo illustrates exploration or visual search in terms of optimality + principles based on straightforward ergodic or allostatic principles. + In other words, to maintain the constancy of our external milieu, it is + sufficient to expose ourselves to predicted and predictable stimuli. + Being able to predict what is currently seen also enables us to predict + fictive sensations that we will experience from another viewpoint. This + provides a principled way in which to explore and sample the world for + example with visual searches using saccadic eye movements. These + theoretical considerations are remarkably consistent with a number + of compelling heuristics; most notably the Infomax principle or the + principle of minimum redundancy, signal detection theory and recent + formulations of salience in terms of Bayesian surprise. The example + here uses saliency (the posterior precision associated with fictive + sampling of sensory data) to simulate saccadic eye movements under + active inference. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_salience.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_sample_image` + +```{text} + samples a (memory mapped) image at displacement o + FORMAT [s] = ADEM_sample_image(V,o,R) + FORMAT [s] = ADEM_sample_image(o,h) + + V - a structure array containing image volume information + o - coordinates of foveal sampling: + o(1) - oculomotor angle + o(2) - oculomotor angle + R - retinal modulation (n x n) + + or + + o - coordinates of foveal sampling + h - vector of coefficients weighting images in STIM.H{:} + + s - sensory sample (n x n) + + requires a global variable with the following fields: + STIM.R = contrast modulation matrix that defines resolution + STIM.W = width of foveal sampling of an image (default: 1/6) + STIM.P = image position in retinal coordinates (default: [0;0]) + STIM.B = basis functions or receptive fields (default: 1) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_sample_image.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_visual` + +```{text} + DEM demo for active inference (i.e. action-perception optimisation of free + energy). This simulation calls on spm_ADEM to simulate visual sampling of + the world and demonstrate retinal stabilisation or visual tracking. We + simulate a simple 2-D plaid stimulus and subject it to an exogenous + perturbations. By employing tight and broad priors on the location of the + stimulus, we can show that action does and does not explain away the visual + consequences of the perturbation (i.e., the movement is seen or not). This + illustrates how one can reframe stabilisation or tracking in terms of + sampling sensory input to ensure conditional expectations are met; and + how these expectations are shaped by prior expectations. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_visual.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ADEM_writing` + +```{text} + This demo illustrates how action can fulfill prior expectations by + explaining away sensory prediction errors prescribed by desired movement + trajectories. In this example a two-joint arm follows a stable + heteroclinic channel, prescribed by a set of fixed point attractors. The + locations of the successive (autovitiated) attractors are defined by + parameters. The ensuing trajectories are illustrated here in terms of + synthetic writing. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ADEM_writing.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ALAP_demo_attenuation` + +```{text} + This demonstration illustrates context or state-dependent precision (i.e. + attention), which is necessary to disambiguate between sensations + caused exogenously and self-generated sensations. In brief, it is + necessary to attend away from the sensory consequences of action to + preclude sensory evidence overriding the prior beliefs that cause + movement. This necessarily reduced the confidence in self-generated + sensations and provides a simple (Bayes-optimal) explanation for sensory + attenuation - in terms of the attention of sensory precision. We + illustrate this in the setting of the force matching illusion and go on + to show that increasing the conviction in (precision of) prior beliefs + abolishes sensory attenuation at the expense of false (delusional) + posterior beliefs about antagonistic external forces. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ALAP_demo_attenuation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DATA_COVID_JHU` + +```{text} + Data retrieval function for COVID modelling + FORMAT data = DATA_COVID_JHU(n) + + n - number of countries to retain [default: n] + + This auxiliary routine retrieves data from comma separated data files + that can be downloaded from: + https://github.com/CSSEGISandData/COVID-19/ + + time_series_covid19_confirmed_global.csv + time_series_covid19_deaths_global.csv + time_series_covid19_recovered_global.csv + + It augments these data with population sizes from the United Nations, + returning the following data structure: + + Data(k).country - country + Data(k).pop - population size + Data(k).lat - latitude + Data(k).long - longitude + Data(k).date - date when more than one case was reported + Data(k).cases - number of cases, from eight days prior to first cases + Data(k).death - number of deaths, from eight days prior to first cases + Data(k).recov - number recovered, from eight days prior to first cases + Data(k).days - number of days in timeseries + Data(k).cum - cumulative number of deaths + + Population data from (cite as): + United Nations, Department of Economic and Social Affairs, Population + Division (2019). World Population Prospects 2019, Online Edition. Rev. 1. + + Please see the main body of the script for a description of the graphical + outputs provided when the routine is called with at an output argument. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DATA_COVID_JHU.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DATA_COVID_UK` + +```{text} + Data retrieval function for COVID modelling (UK) + FORMAT [Y,R] = DATA_COVID_UK(country) + + Y - daily deaths and confirmed cases + R - daily test rates for the UK + + country - optional country + + This auxiliary routine retrieves data from comma separated data files + that can be downloaded from: + https://github.com/CSSEGISandData/COVID-19/ + https://github.com/tomwhite/covid-19-uk-data + + time_series_covid19_confirmed_global.csv + time_series_covid19_deaths_global.csv + time_series_covid19_recovered_global.csv + covid-19-tests-uk + + It augments these data with population sizes from the United Nations, + returning the following data structure: + + Data(k).country - country + Data(k).pop - population size + Data(k).lat - latitude + Data(k).long - longitude + Data(k).date - date when more than one case was reported + Data(k).cases - number of cases, from eight days prior to first cases + Data(k).death - number of deaths, from eight days prior to first cases + Data(k).recov - number recovered, from eight days prior to first cases + Data(k).days - number of days in timeseries + Data(k).cum - cumulative number of deaths + + Population data from (cite as): + United Nations, Department of Economic and Social Affairs, Population + Division (2019). World Population Prospects 2019, Online Edition. Rev. 1. + + Please see the main body of the script for a description of the graphical + outputs provided when the routine is called with at an output argument. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DATA_COVID_UK.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DATA_COVID_US` + +```{text} + Data retrieval function for COVID modelling + FORMAT [Y,Data] = DATA_COVID_US + + Y(:,i,1) = Data(i).death; + Y(:,i,2) = Data(i).cases; + + This auxiliary routine retrieves data from comma separated data files + that can be downloaded from: + https://github.com/CSSEGISandData/COVID-19/ + + time_series_covid19_confirmed_US.csv + time_series_covid19_deaths_US.csv + + Data(k).state - State + Data(k).pop - population size + Data(k).lat - latitude + Data(k).long - longitude + Data(k).date - date of 8th day + Data(k).cases - number of cases + Data(k).death - number of deaths + Data(k).cum - cumulative number of deaths + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DATA_COVID_US.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DATA_WID_data` + +```{text} + Data retrieval function for COVID modelling + FORMAT D = DATA_WID_data + + n - number of countries to retain [default: n] + + This auxiliary routine retrieves data from comma separated data files + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DATA_WID_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_AI_NLSI` + +```{text} + Demo of active inference for trust games + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_AI_NLSI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_BAYES_FACTORS` + +```{text} + FORMAT DEMO_BAYES_FACTORS(pC,hE,hC,N) + Demonstration Bayes factors and classical p-values + -------------------------------------------------------------------------- + pC - prior covariance (e.g., 4) + hE - expectation of log precision (e.g., 1) + hC - covariance of log precision (e.g., 1/8) + N - number of observations (e.g., 16) + b - relative variance under alternate and null (e.g., 1/32) + + This demonstration routine uses a simple linear model to examine the + relationship between free energy differences or log Bayes factors and + classical F statistics. Using re-randomisation of a design matrix, it + computes the null distribution over both statistics and plots them + against each other. There is a linear relationship, which allows one to + evaluate the false-positive rate for any threshold on the Bayes factor. + Ideally, one would like to see a positive log Bayes factor map to a + classical threshold of p=0.05. The offset and slope of the linear + relationship between the two statistics depends upon prior beliefs about + the covariance of the parameters and the log precision. These can be + changed by editing the code below (or supplying input arguments). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_BAYES_FACTORS.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_BMR_PEB` + +```{text} + Demonstration routine for empirical Bayes and Bayesian model reduction + -------------------------------------------------------------------------- + This routine illustrates the use of Bayesian model reduction when + inverting hierarchical (linear) models - it is essentially a software + validation demo and proof of concept. It uses a parametric empirical + Bayesian model (i.e., nested linear models) to eschew local minima issues + and to assure the Laplace assumption is correct. In brief, the data are + generated for multiple subjects, under a linear model with subject + specific parameters at the first level and group specific parameters at + the second. These model a group effect common to all subjects in a subset + of parameters and differences in a further subset. The objective of + empirical Bayesian inversion is to recover the group effects in terms of + posteriors and perform Bayesian model comparison at the second (between + subject) level. + + This provides empirical shrinkage priors at the first level, which can be + used to compute the predictive posterior for any subject. In turn, the + predictive posterior can be used for leave-one-out cross validation. + + The key aspect of this approach to empirical Bayesian modelling is that + we use Bayesian model reduction throughout. In other words, after the + subject-specific models have been inverted the data are discarded and we + deal only with the free energies and posteriors for subsequent + hierarchical analysis. This can be computationally very efficient when + dealing with large first-level or complicated models: as in DCM. + + The parameterisation of the models uses the format of DCM. This means + parameters are specified as a structure with key parameters being in the + fields A, B and C. + + See also: spm_dcm_bmr, spm_dcm_peb and spm_dcm_peb_bma + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_BMR_PEB.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_CVA_RSA` + +```{text} + Canonical Variate Analysis and representational similarity analysis + FORMAT RSA = DEMO_CVA_RSA + + output structure + -------------------------------------------------------------------------- + RSA.C - hypotheses matrices + RSA.c - (orthogonalised) contrasts + RSA.W - (second-order) canonical weights + RSA.X - design matrix + RSA.Y - data + RSA.X0 - confounds + RSA.F - (BIC) log evidence + __________________________________________________________________________ + + This demonstration routine starts with a canonical covariates analysis in + which hypotheses are specified in terms of second-order matrices (of the + sort used in representational similarity analysis). This part + illustrates the inversion of a multivariate linear model over multiple + subjects, testing for the expression of multivariate responses under each + of three hypotheses. Furthermore, it illustrates the (Bayesian) model + comparison under the assumption that only one hypothesisis true. + + The three hypotheses correspond to a main effect of a parametric variable + (e.g., the degree to which something is judged valuable), the main + effect of a categorical variable (e.g., big or small) and their + interaction. Note that this requires a specification in terms of + second-order hypothesis matrices that are not expressed in terms of + similarities per se. In other words, the second-order hypotheses are + assumed to be in the form of covariance matrices; as opposed to + correlation matrices. + + This routine demonstrates the testing of hypothesis matrices with a rank + of one (corresponding to a T-contrast). However, the code has been + written to handle arbitrary hypothesis matrices (corresponding to F- + contrasts) that test a subspace of two or more dimensions. + + To the extent that this reproduces the hypothesis testing of + representational similarity analysis, there is an important observation: + this analysis works for a single voxel. In other words, representational + similarity analysis is not an inherently multivariate approach. + + This illustration deliberately mixes two (main) effects in equal measure, + within the same region of interest. This is to highlight the + inappropriate application of hypothesis selection; here demonstrated via + Bayesian model comparison using the Bayesian information criteria. In + other words, several hypotheses about a particular region could be true + at the same time. + + We then revisit exactly the same problem (i.e., Bayesian model comparison + of covariance components of second-order responses) using variational + Laplace to estimate the contributions of each component of pattern + explicitly. This has the advantage of enabling parametric empirical Bayes + at the between subject level - and subsequent Bayesian model reduction. + + References: + + Characterizing dynamic brain responses with fMRI: a multivariate + approach. Friston KJ, Frith CD, Frackowiak RS, Turner R. NeuroImage. 1995 + Jun;2(2):166-72. + + A multivariate analysis of evoked responses in EEG and MEG data. Friston + KJ, Stephan KM, Heather JD, Frith CD, Ioannides AA, Liu LC, Rugg MD, + Vieth J, Keber H, Hunter K, Frackowiak RS. NeuroImage. 1996 Jun; + 3(3):167-174. + + Population level inference for multivariate MEG analysis. Jafarpour A, + Barnes G, Fuentemilla Lluis, Duzel E, Penny WD. PLoS One. 2013. + 8(8): e71305 + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_CVA_RSA.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_DCM_MB` + +```{text} + This demo uses the notion of Markov blankets and the renormalisation + group to evaluate the coupling among neuronal systems at increasing + spatial scales. The underlying generative model is based upon the + renormalisation group: a working definition of renormalization involves + three elements: vectors of random variables, a course-graining operation + and a requirement that the operation does not change the functional form + of the Lagrangian. In our case, the random variables are neuronal states; + the course graining operation corresponds to the grouping (G) into a + particular partition and adiabatic reduction (R) - that leaves the + functional form of the dynamics unchanged. + + Here, the grouping operator (G) is based upon coupling among states as + measured by the Jacobian. In brief, the sparsity structure of the + Jacobian is used to recursively identify Markov blankets around internal + states to create a partition of states - at any level - into particles; + where each particle comprises external and blanket states. The ensuing + reduction operator (R) eliminates the internal states and retains the slow + eigenmodes of the blanket states. These then constitute the (vector) + states at the next level and the process begins again. + + This routine starts using a simple form of dynamic causal modelling + applied to the principal eigenvariate of local parcels (i.e., particles) + of voxels with compact support. The Jacobian is estimated using a + linearised dynamic causal (state space) model, where observations are + generated by applying a (e.g., haemodynamic) convolution operator to + hidden (e.g., neuronal) states. This estimation uses parametric empirical + Bayes (PEB: spm_PEB). The ensuing estimates of the Jacobian (i.e., + effective connectivity) are reduced using Bayesian model reduction (BMR: + spm_dcm_BMR_all) within a bespoke routine (spm_dcm_J). + + The Jacobian is then partitioned using the course graining operator into + particles or parcels (using spm_markov blanket). The resulting partition + is then reduced by eliminating internal states and retaining slow + eigenmodes with the largest (real) eigenvalues (spm_A_reduce). The + Jacobian of the reduced states is then used to repeat the process - + recording the locations of recursively coarse-grained particles - until + there is a single particle. + + The result of this recursive decomposition (i.e., renormalisation) + affords a characterisation of directed coupling, as characterised by a + complex Jacobian; namely, a multivariate coupling matrix, describing the + coupling between eigenmodes of Markov blankets at successive scales. This + can be regarded as a recursive parcellation scheme based upon effective + connectivity and a generative (dynamic causal) model of multivariate + (neuronal) timeseries. + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_DCM_MB.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_DCM_PEB` + +```{text} + Test routine to check group DCM for electrophysiology + -------------------------------------------------------------------------- + This routine illustrates the use of Bayesian model reduction when + inverting hierarchical (dynamical) models; for example, multisubject DCM + models. In this context, we have hierarchical models that are formally + similar to parametric empirical Bayesian models - with the exception + that the model of the first level can be nonlinear and dynamic. In brief, + this routine shows how to finesse the brittleness of Bayesian model + comparison at the single subject level by equipping the model with an + extra (between subject) level. It illustrates the recovery of group + effects on modulatory changes in effective connectivity (in the mismatch + negativity paradigm) - based upon real data. + + First, an EEG DCM (using empirical grand mean data) is inverted to + find plausible group mean parameters. Single subject data are + then generated using typical within and between subject variance (here, + group differences in the modulation of intrinsic connectivity. We then + illustrate a variety of Bayesian model averaging and reduction procedures + to recover the underlying group effects. + + See also: spm_dcm_bmr, spm_dcm_peb and spm_dcm_peb_bma + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_DCM_PEB.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_DCM_PEB_FIT` + +```{text} + Test routine to check group DCM for electrophysiology + -------------------------------------------------------------------------- + This routine illustrates the use of Bayesian model reduction when + inverting hierarchical (dynamical) models; for example, multisubject DCM + models. In this demonstration empirical Bayesian model reduction is + applied recursively in an attempt to finesse the local minimum problem + with a nonlinear DCMs. The estimates are compared against standard + Bayesian model reduction, in terms of the subject specific estimates and + Bayesian model comparison (and averages) at the between subject level. + + This demo considers a single goup (e.g., of normal subjects) and the + differences between the group average using emprical Bayesian reduction + and the Bayesian reduction of the (grand) average response. + + See also: DEMO_DCM_PEB_REC.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_DCM_PEB_FIT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_GROUP_PEB` + +```{text} + Demonstration routine for empirical Bayes and Bayesian model reduction + -------------------------------------------------------------------------- + This routine illustrates the use of Bayesian model reduction when + inverting hierarchical (linear) models - it is essentially a software + validation demo and proof of concept. It uses a parametric empirical + Bayesian model (i.e., nested linear models) to eschew local minima issues + and to assure the Laplace assumption is correct. In brief, the data are + generated for multiple subjects, under a linear model with subject + specific parameters at the first level and group specific parameters at + the second. These model a group effect common to all subjects in a subset + of parameters and differences in a further subset. In this demo, we + consider the full hierarchical inversion of a multisubject study by + updating the priors at the first level, using the empirical priors from + the second level. Crucially, this is done during the optimisation at the + first level (i.e., after every iteration - or small number of iterations + - at the first level. + + This provides a generic scheme for the hierarchical inversion of + nonlinear and possibly dynamic models in which the first level + optimisation is informed by the sufficient statistics of the second level + (namely the empirical priors). This should be contrasted with the summary + statistic approach, in which the second level optimisation, based upon + the sufficient statistics of the first level (posteriors and priors) are + computed after convergence of the first level. The results of inversion + are compared in terms of the second level posteriors (and the second + level free energy over iterations). Specifically, we compare a gold + standard (PEB) inversion, with the summary statistic approach to + empirical Bayes and the hierarchical inversion demonstrated in this + routine. + + The parameterisation of the models uses the format of DCM. This means + parameters are specified as a structure with key parameters being in the + fields A, B and C. + + See also: spm_dcm_bmr, spm_dcm_peb and spm_dcm_peb_bma + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_GROUP_PEB.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_Lindley_paradox` + +```{text} + FORMAT DEMO_BAYES_FACTORS(pC,hE,hC) + Demonstration Bayes factors and classical p-values + -------------------------------------------------------------------------- + pC - prior covariance (e.g., 4) + hE - expectation of log precision (e.g., 1) + hC - covariance of log precision (e.g., 1/8) + + This demonstration routine uses a simple linear model to examine the + relationship between free energy differences or log Bayes factors and + classical F statistics. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_Lindley_paradox.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_MDP_Stroop` + +```{text} + This demo uses a deep temporal partially observed Markov decision + process to simulate performance of a Stroop task. This task is used to + illustrate a formulation of cognitive or mental effort. The synthetic + participants must overcome a prior belief that the normal action on + being presented with text is to read that word, and instead state the + colour the text is presented in. In addition, this routine demonstrates + the fitting of choice and reaction time data to the model, and the + recovery of parameters that summarise behaviour. + + see also: spm_MDP_VB_X.m, DEM_demo_MDP_reading.m, DEMO_MDP_questions.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_MDP_Stroop.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_MDP_Understanding` + +```{text} + This demo uses a hierarchical version of the ubiquitous T-maze demo, in + which the agent is equipped with a space of hypotheses about why it chose + to act in a certain way. This means that, when queried, it is able to + communicate an explanation for its actions. + + see also: DEM_demo_MDP_X.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_MDP_Understanding.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_MDP_maze` + +```{text} + Demo of mixed continuous and discrete state space modelling + __________________________________________________________________________ + + This demonstration of active inference focuses on navigation and planning + in a fairly complicated maze. The idea is to demonstrate how epistemic + foraging and goal (target) directed behaviour are integrated in the + minimisation of expected free energy. In this illustration, and 8 x 8 + maze is learned through novelty driven evidence accumulation - to learn + the likelihood mapping between hidden states (locations in the maze) and + outcomes (whether the current location is open or closed). This + accumulated experience is then used to plan a path from a start to an end + (target location) under a task set specified by prior preferences over + locations. These priors are based upon a simple diffusion (CF backwards + induction) heuristic that specifies subgoals. The subgoals (i.e., + locations) contain the most paths from the target within the horizon of + the current policy. + + We will first illustrate the novelty driven epistemic foraging that + efficiently scans the maze to learn its structure. We then simulate + planning of (shortest path) trajectory to the target under the assumption + the maze has been previously learned. Finally, we consider exploration + under prior preferences to simulate behaviour when both epistemic and + goal directed imperatives are in play. The focus on this demo is on + behavioural and electrophysiological responses over moves. + + A key aspect of this formulation is the hierarchical decomposition of + goal directed behaviour into subgoals that are within the horizon of a + limited policy - here, to moves that correspond to a trial. The prior + preferences then contextualise each policy or trial to ensure that the + ultimate goal is achieved. + + Empirically, this sort of construction suggests the existence of Path + cells; namely, cells who report the initial location of any subsequence + and continue firing until the end of the local path. This is illustrated + by plotting simulated activity as a function of trajectories during + exploration. + + see also: spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_MDP_maze.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_MDP_maze_X` + +```{text} + Demo of sophisticated inference and novelty (i.e.,planning to learn) + __________________________________________________________________________ + + This demonstration of active inference focuses on navigation and + planning. The idea is to demonstrate how epistemic foraging and goal + (target) directed behaviour are integrated in the minimisation of + expected free energy. In this illustration, and 8 x 8 maze is learned + through novelty driven evidence accumulation - to learn the likelihood + mapping between hidden states (locations in the maze) and outcomes + (whether the current location is aversive or not). This accumulated + experience is then used to plan a path from a start to an end (target + location) under a task set specified by prior preferences over locations. + These priors are based upon the distance between the current location and + a target location. + + This version uses a belief propagation scheme (with deep policy searches) + to illustrate prospective behaviour; namely, selecting policies or + trajectories that transiently increased Bayesian risk. The code below can + be edited to demonstrate different kinds of behaviour, under different + preferences, policy depth and precisions. + + see also: DEM_MDP_maze.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_MDP_maze_X.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_MDP_questions` + +```{text} + Demo of active inference for visual salience + __________________________________________________________________________ + + This routine provide simulations of reading to demonstrate deep temporal + generative models. It builds upon the scene construction simulations to + equip the generative model with a second hierarchical level. In effect, + this creates an agent that can accumulate evidence at the second level + based upon epistemic foraging at the first. In brief, the agent has to + categorise a sentence or narrative into one of two categories (happy or + sad), where it entertains six possible sentences. Each sentence comprises + four words, which are themselves constituted by two pictures or graphemes + These are the same visual outcomes used in previous illustrations of + scene construction and saccadic searches. + + Here, the agent has policies at two levels. The second level policy (with + just one step into the future) allows it to either look at the next word + or stay on the current page and make a decision. Concurrently, a first + level policy entails one of four saccadic eye movements to each quadrant + of the current page, where it will sample a particular grapheme. + + This provides a rough simulation of reading - that can be made more + realistic by terminating first level active inference, when there can be + no further increase in expected free energy (i.e., all uncertainty about + the current word has been resolved). The subsequent inferred hidden + states then become the outcome for the level above. + + To illustrate the schemes biological plausibility, one can change the + agent's prior beliefs and repeat the reading sequence under violations of + either local (whether the graphemes are flipped vertically) or globally + (whether the sentence is surprising) expectations. This produces a + mismatch negativity (MMN) under local violations) and a MMN with a + P300 with global violations. + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_MDP_questions.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_MDP_voice` + +```{text} + Active inference in conversation + __________________________________________________________________________ + + This routine provide simulations of reading to demonstrate deep temporal + generative models. It builds upon the scene construction simulations to + equip the generative model with a second hierarchical level. In effect, + this creates an agent that can accumulate evidence at the second level + based upon epistemic foraging at the first. In brief, the agent has to + categorise a sentence or narrative into one of two categories (happy or + sad), where it entertains six possible sentences. Each sentence comprises + four words, which are themselves constituted by two pictures or graphemes + These are the same visual outcomes used in previous illustrations of + scene construction and saccadic searches. + + Here, the agent has policies at two levels. The second level policy (with + just one step into the future) allows it to either look at the next word + or stay on the current page and make a decision. Concurrently, a first + level policy entails one of four saccadic eye movements to each quadrant + of the current page, where it will sample a particular grapheme. + + This provides a rough simulation of reading - that can be made more + realistic by terminating first level active inference, when there can be + no further increase in expected free energy (i.e., all uncertainty about + the current word has been resolved). The subsequent inferred hidden + states then become the outcome for the level above. + + To illustrate the schemes biological plausibility, one can change the + agent's prior beliefs and repeat the reading sequence under violations of + either local (whether the graphemes are flipped vertically) or globally + (whether the sentence is surprising) expectations. This produces a + mismatch negativity (MMN) under local violations) and a MMN with a + P300 with global violations. + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_MDP_voice.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_SLR` + +```{text} + Demo of sparse logistic regression. This demonstration routines + illustrates the use of sparse acoustic regression (as implemented in + spm_sparse_regression.m) to recover a small number of causes that best + explain some dependent variable. For example, imagine we thought that a + small number (e.g., four) of SNPs or copy number variants a generic study + had sufficiently large effect sizes on some phenotypic measure to be + worth pursuing. We might treat these (rare variants) as being expressed + in the context of random effects (e.g., common variants and phenotypic + measurement noise); however, we have many more potential causes than + observations. This problem is addressed using (logistic) regression + under sparsity constraints specified in terms of hyper priors over the + precision (i.e. inverse variance) of model parameters. This provides the + Bayesian shrinkage estimators of the regression coefficients that, + crucially, can then be subject to Bayesian model reduction. Bayesian + model reduction effectively eliminates redundant parameters that provided + the optimal balance between accuracy and complexity. + + in the example below, we assume that we have 32 subjects with 128 + independent variables (e.g., following some initial dimension reduction). + The simulated data is generated with just four of the independent to see + whether these can be identified using sparse logistic regression and + Bayesian model reduction. + + If the dependent variables are classes or probabilities a logistic + transform is automatically applied. However, one can also use this + routine for continuous (i.e., parametric phenotypes). the graphics + produced by this demo report the results of sparse logistic regression + using variational Laplace (i.e., approximate Bayesian inference and hyper + priors). In addition, it reports the results and summary of the + subsequent Bayesian model reduction. + + see also: spm_sparse_regression.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_SLR.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_dcm_fmri_nnm` + +```{text} + This demonstration routine illustrates the dynamic causal modelling of + fMRI timeseries using neural mass models. We first specify a simple DCM + for the attentional dataset. Following inversion, the posterior densities + are used to characterise the haemodynamic correlates of induced + responses. + + This experiment involved attention to visual motion. We then use Bayesian + model reduction to ask whether attention was mediated through the + modulation of deep or superficial pyramidal cells in the visual motion + sensitive area (V5 or MST). in this setup, there are three regions and + three inputs (visual stimulation, visual motion and attention to + motion). We treat the latter two inputs as modulatory; namely, increasing + extrinsic or intrinsic connectivity in particular parts of the network. + Intrinsic connectivity corresponds to the self-inhibition of the (four) + neuronal populations constituting each region. + + Finally, we address the contribution of extrinsic and intrinsic + pre-synaptic activity, laminar-specific contributions and the + contributions of inhibitory interneurons to the BOLD signal. This + assessment uses Bayesian Model Reduction. + + + ========================================================================== + + Options + -------------------------------------------------------------------------- + DCM.options.two_state % two regional populations (E and I) + DCM.options.stochastic % fluctuations on hidden states + DCM.options.nonlinear % interactions among hidden states + DCM.options.nograph % graphical display + DCM.options.centre % mean-centre inputs + DCM.options.P % starting estimates for parameters + DCM.options.hidden % indices of hidden regions + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Neural_Models/DEMO_dcm_fmri_nnm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_model_reduction_ERP` + +```{text} + Illustration of (post hoc) neuronal mass model optimisation + __________________________________________________________________________ + This demonstration routine illustrates the post-hoc optimisation of + dynamic causal models for event related responses. To assess performance + in relation to ground truth, it uses simulated data. We will simulate a + simple two source model with exogenous input to the first source and + reciprocal (extrinsic) connections between the two sources. the ERPs are + simulated and two conditions, where the second condition induces a change + in the intrinsic coupling of the first source and the forward extrinsic + coupling. We then explore a simple model space; created by increasing the + precision of shrinkage priors on the intrinsic condition specific effect. + Because this effect was responsible for generating the data, we expect + the free energy (log evidence) to fall as the shrinkage covariance falls + to 0). Crucially, we compare and contrast the estimates of the free + energy (and parameter estimates) using an explicit inversion of the + reduced models (with tighter shrinkage priors) and a post-hoc model + reduction procedure - that is computationally more efficient and + robust to local minima. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Neural_Models/DEMO_model_reduction_ERP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_niche_construction` + +```{text} + Demo of niche construction using active inference + __________________________________________________________________________ + + The free-energy principle is an attempt to explain the structure of the + agent and its brain, starting from the fact that an agent exists (Friston + and Stephan, 2007; Friston et al., 2010). More specifically, it can be + regarded as a systematic attempt to understand the 'fit' between an + embodied agent and its niche, where the quantity of free-energy is a + measure for the 'misfit' or disattunement (Bruineberg and Rietveld, 2014) + between agent and environment. This paper offers a proof-of-principle + simulation of niche construction under the free-energy principle. The key + point of this paper is that the minimum of free-energy is not at a point + in which the agent is maximally adapted to the statistics of a static + environment, but can better be conceptualized an attracting manifold + within the joint agent-environment state-space as a whole, which the + system tends toward through mutual interaction. We will provide a general + introduction to active inference and the free-energy principle. Using + Markov Decision Processes (MDPs), we then describe a canonical generative + model and the ensuing update equations that minimize free-energy. We then + apply these equations to simulations of foraging in an environment; in + which an agent learns the most efficient path to a pre-specified + location. In some of those simulations, unbeknownst to the agent, the + environment changes as a function of the activity of the agent (i.e. + unintentional niche construction occurs). We will show how, depending on + the relative inertia of the environment and agent, the joint + agent-environment system moves to different attracting sets of jointly + minimized free-energy. + + see also: spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEMO_niche_construction.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_tvec_csd_sim` + +```{text} + DEMO_tvec_csd_sim - Demo script for modelling time-varying effective + connectivity in a DCM for CSD. + + This script demonstrates key aspects of the modelling approach + described in the paper. Specifically, it simulates and recovers + a dynamic causal model (DCM) with time-varying connectivity, + showcasing the use of temporal basis functions to model slow + fluctuations in synaptic efficacy. + + Overview of this script: + 1. **Model Setup:** + - Defines a simple two-region DCM with forward and backward connections. + - Uses a cosine basis set to represent time-varying connectivity modulations. + + 2. **Data Simulation:** + - Generates synthetic neural responses based on predefined modulations. + - Adds noise to simulate observed data. + + 3. **Parameter Recovery:** + - Implements Bayesian model inversion to estimate connectivity changes. + + 4. **Visualization:** + - Plots the true and recovered connectivity modulations. + - Compares simulated, observed, and recovered neuronal responses. + + + Outputs: + - Visualization of true vs. recovered connectivity modulations. + - Signal-to-noise ratio (SNR) of synthetic data. + - Simulated, observed, and recovered neuronal responses. + + For further details, refer to the paper: + Medrano, J., Friston, K. J., & Zeidman, P. (2024). + Dynamic Causal Models of Time-Varying Connectivity. + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Neural_Models/DEMO_tvec_csd_sim.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_tvec_erp_mmn` + +```{text} + DEMO_tvec_erp_mmn: Analyse modulatory dynamics in EEG Mismatch Negativity + using Dynamic Causal Modeling of Time-Varying Connectivity. + + This script analyzes EEG mismatch negativity (MMN) data using dynamic + causal modeling (DCM) in SPM. It includes data preparation, + preprocessing, and both initial and advanced DCM analyses to + explore neural connectivity and modulatory effects over time. + + The script assumes you have access to SPM and the necessary data files. + If the data is unavailable, it will download the sample dataset. + Customize file paths and parameters as needed. + + Key Steps: + 1. Data Preparation: Prepares directories and checks for necessary files. + 2. Data Preprocessing: Converts raw EEG data into SPM-compatible format, + filters, and epochs the data. + 3. Initial DCM Analysis: Fits a basic DCM model to analyze ERP responses + and estimate neural connections. + 4. Advanced Analysis: Refines the DCM model to assess synaptic plasticity + and time-varying connectivity. + 5. Visualization: Projects connectivity changes over time and compares + observed vs. modeled ERPs. + + Requirements: + - MATLAB with SPM12 installed. + - Access to raw EEG data or an internet connection for dataset download. + + For further details, refer to the paper: + Medrano, J., Friston, K. J., & Zeidman, P. (2024). + Dynamic Causal Models of Time-Varying Connectivity. + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Neural_Models/DEMO_tvec_erp_mmn.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEMO_tvec_erp_sim` + +```{text} + DEMO_tvec_erp_sim - Demo script for modelling time-varying effective + connectivity in a DCM for ERP. + + This script demonstrates key aspects of the modelling approach + described in the paper. Specifically, it simulates and recovers + a dynamic causal model (DCM) with time-varying connectivity, + showcasing the use of temporal basis functions to model slow + fluctuations in synaptic efficacy. + + Overview of this script: + 1. **Model Setup:** + - Defines a simple two-region DCM with forward and backward connections. + - Uses a cosine basis set to represent time-varying connectivity modulations. + + 2. **Data Simulation:** + - Generates synthetic neural responses based on predefined modulations. + - Adds noise to simulate observed data. + + 3. **Parameter Recovery:** + - Implements Bayesian model inversion to estimate connectivity changes. + + 4. **Visualization:** + - Plots the true and recovered connectivity modulations. + - Compares simulated, observed, and recovered neuronal responses. + + + Outputs: + - Visualization of true vs. recovered connectivity modulations. + - Signal-to-noise ratio (SNR) of synthetic data. + - Simulated, observed, and recovered neuronal responses. + + For further details, refer to the paper: + Medrano, J., Friston, K. J., & Zeidman, P. (2024). + Dynamic Causal Models of Time-Varying Connectivity. + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Neural_Models/DEMO_tvec_erp_sim.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_CLIMATE_India` + +```{text} + FORMAT DCM = DEM_CLIMATE_India + + Demonstration of climate and sustainability modelling + __________________________________________________________________________ + + This demonstration routine illustrates the use of dynamic causal + modelling to test hypotheses about the causal architecture that couples + economic activity to meteorological (and climate) variables. This example + uses various timeseries from different regions (states) in India + quantified in terms of temperature, rainfall, drought, irrigation, + economic activity, measures of malnutrition et cetera. + + The dynamic causal model in this instance is a nonlinear deterministic + (mean field) approximation to the expected (i.e., average) evolution of + various latent states that generate observable data. Crucially, these + data can be sparse and discontinuous in time. This means that the unknown + variables of the implicit forward or generative model are the model + parameters; namely, the rate or time constants coupling latent + (unobservable) states and the parameters of a likelihood mapping from + latent states to (observable) outcomes. In other words, because the model + is deterministic, the latent states are fully determined by the + parameters of the generative model, where these parameters can include + the initial states. + + The structure and functional form of the model is described in the + annotated routines that generates timeseries from latent states, where + the latent states are the solution to ordinary differential equations + that describe the influence of one latent state on another. For example, + there is a latent state called 'anthropomorphic activity' (c.f., + population size) that drives a slow meteorological variable, which + increases the amplitude of annual fluctuations in two (fast) + meteorological variables. The meteorological variables determine the + natural yield of agricultural activity, which in turn influences the use + of irrigation and fertilisers. This influences crop production that + contributes to food production and, ultimately, anthropomorphic activity, + via a latent state called 'malnutrition'. In short, we have a nonlinear + dynamical system in which anthropomorphic activity is coupled directly to + meteorological (i.e., climate-like) states that are vicariously coupled + back to anthropomorphic states. The implicit separation of timescales + within the meteorological states results in itinerant dynamics at a fast + (seasonal) and slow (decades) timescale. + + This routine first illustrates the way in which data are assembled and + sorted. Here, we average away random fluctuations by averaging over + regions and then log transform any non-negative data. This allows one to + use a simple likelihood model with additive Gaussian noise. We next + assemble the prior density over the parameters and hyperparameters + controlling the amplitude of observation noise. finally, we invert the + model to estimate the parameters in terms of a posterior density. The + posterior density over model parameters can then be used in a variety of + ways: + + First, one can ask whether any parameters are redundant. In other words, + is the model too expressive or over-parameterised. In the example + provided, we ask a slightly subtler question: did this parameter need to + be a free parameter or could we have fixed it to its prior expectation. + This question can be asked by comparing models with uninformative and + very precise shrinkage priors over each parameter or combinations of + parameters. The same kind of comparison can also be used to test + hypotheses by comparing the log evidence of a model with and without a + particular link or parameter. In Bayesian model reduction, different + models correspond to different shrinkage priors (i.e., a model with out a + particular parameter is specified with priors that shrink it towards a + small value). + + The posterior density can also be used to assess the role of different + parameters, in generating outcomes, using a straightforward sensitivity + analysis. This is based on the change in an outcome produced by a change + in the parameter, where the outcome is a function of time. Finally, one + can integrate (i.e., solve) the model using the posterior estimates of + the model parameters to predict what might happen in the future, under + different scenarios or plausible interventions. + + Details about the model structure and assumptions (i.e., priors) can + be found in the key routines that return the priors (i.e., + spm_CLIMATE_priors) and the routine that generates predicted outcomes, + as a function of the parameters (i.e., spm_CLIMATE_gen). The remaining + routines are part of the standard SPM software; including the model + inversion or deconvolution scheme which, in this deterministic setting, + rests on something called variational Laplace + + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_CLIMATE_India.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID` + +```{text} + FORMAT [DCM,GCM] = DEM_COVID(country,data) + data - data to model [default: data = DATA_COVID_JHU] + country - country to model [default: 'United Kingdom') + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates the Bayesian model inversion of a generative + model of coronavirus spread using variational techniques (variational + Laplace). It illustrates hierarchical Bayesian modelling by first + inverting a generative model of each country, and then combining the + posterior densities over the model parameters using parametric empirical + Bayes to leverage systematic differences between countries, as + characterised by their population, geographical location etc. + + Each subsection produces one or two figures that are described in the + annotated (Matlab) code. These subsections core various subroutines that + provide a more detailed description of things like the generative model, + its priors and the evaluation confidence intervals. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_AGE` + +```{text} + FORMAT [DCM] = DEM_COVID_AGE + LA - local authority + + Demonstration of COVID-19 modelling + __________________________________________________________________________ + + This demonstration routine fits multiple regional death by date and new + cases data and compiles estimates of latent states for local + authorities. + + Technical details about the dynamic causal model used here can be found + at https://www.fil.ion.ucl.ac.uk/spm/covid-19/. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_AGE.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_COUNTRY` + +```{text} + FORMAT DCM = DEM_COVID_COUNTRY(country) + country - country to model [default: 'United Kingdom') + T - prediction period (days) + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates Bayesian model comparison using a line search + over periods of imunity and pooling over countries. In brief,32 countries + are inverted and 16 with the most informative posterior over the period + of immunity are retained for Bayesian parameter averaging. The Christian + predictive densities are then provided in various formats for the average + country and (16) individual countries. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_COUNTRY.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_DASH` + +```{text} + FORMAT [DCM] = DEM_COVID_DASH + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + The estimates of the reproduction rate and associated prevalence of + infection in each region are based on a dynamic causal model of the + coronavirus outbreak. This kind of modelling is distinct from + conventional epidemiological modelling because the dynamic causal model + incorporates things like self-isolation, social distancing, the + probability of being tested and waiting for test results. This allows us + to use regional reports of COVID-19 related deaths and new cases to model + regional outbreaks. + + In brief, the model assumes each region experiences an epidemic with + similar characteristics but with different parameters, such as the number + of contacts at home or work. And different mixtures of people who are + more or less likely to catch (or transmit) the virus. These parameters + are estimated from regional data and are then used to nowcast and + forecast the evolution of the outbreak in terms of underlying or latent + causes (such as the prevalence of infection). The effective population + size is the number of people who are caught up in the outbreak, some of + whom will be resistant to catching the virus. Of those that are not, some + will become contagious and infect other people. From these estimates it + is possible to evaluate the effective reproduction ratio at any point in + time during the course of the outbreak, in addition to other quantitative + estimates, such as the number of people currently infected or new cases + of infection every day (that may or may not be identified). + + The ensuing predictions complement equivalent estimates from + epidemiological modelling based upon the history of outcomes observed so + far. See https://www.mrc-bsu.cam.ac.uk/now-casting/ for a + state-of-the-art transmission model. In principle, it is possible to + compare the quality of dynamic causal and epidemiological models in terms + of their model evidence or marginal likelihood. However, at the present + time, it is difficult to estimate the evidence for epidemiological + models; thereby precluding (Bayesian) model comparison. + + Technical details about the dynamic causal model used here can be found + at https://www.fil.ion.ucl.ac.uk/spm/covid-19/. + + The (annotated) open source code creating these graphics is + DEM_COVID_DASH.m + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_DASH.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_I` + +```{text} + FORMAT DEM_COVID_I + data - data to model [default: data = DATA_COVID_JHU] + country - country to model [default: 'United Kingdom') + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates Bayesian model comparison using a line search + over periods of imunity and pooling over countries. In brief,32 countries + are inverted and 16 with the most informative posterior over the period + of immunity are retained for Bayesian parameter averaging. The Christian + predictive densities are then provided in various formats for the average + country and (16) individual countries. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_I.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_LTLA` + +```{text} + FORMAT [DCM] = DEM_COVID_LTLA(LA) + LA - local authority + + Demonstration of COVID-19 modelling + __________________________________________________________________________ + + This demonstration routine fits multiple regional death by date and new + cases data and compiles estimates of latent states for local + authorities. + + Technical details about the dynamic causal model used here can be found + at https://www.fil.ion.ucl.ac.uk/spm/covid-19/. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_LTLA.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_S` + +```{text} + FORMAT [DCM] = DEM_COVID_S + + Demonstration of COVID-19 modelling with stratified populations + __________________________________________________________________________ + + This demonstration routine uses a stratified population by age to fit + death by date according to age bins. In brief, this uses the same kind of + DCM for each age group; and the accompanying population densities + are coupled via contact matrices; in other words, the number of people + from another group I expect to be in contact with perday. In addition, + some of the clinical and epidemiological parameters are group specific + using prespecified profiles encoded in R. the parameters of the contact + matrices are optimised and a reasonably uninformative priors. + + Technical details about the dynamic causal model used here can be found + at https://www.fil.ion.ucl.ac.uk/spm/covid-19/. + + The (annotated) open source code creating these graphics is + DEM_COVID_DASH.m + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_S.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_T` + +```{text} + FORMAT [DCM] = DEM_COVID_T + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This demo routine focuses on surveillance and mitigation strategies in + the UK. It first estimate the parameters of a dynamic causal model for + the epidemic in the United Kingdom. Crucially, in this inversion the data + are supplemented with the total number of cases (in addition to positive + cases and daily deaths). It rests upon an augmented DCM that includes a + state of self isolation. Moving from a state of isolation depends upon a + negative test. Tracing and tracking in this model is reflected as a small + percentage of being tested if infected and asymptomatic. Otherwise, the + baseline testing is in play. We will consider the effects of changing + baseline testing and tracing and tracking at various phases of the + outbreak. + + Finally, this routine performs a brief comparative analysis with Germany + to see if the differences with the UK can be explained in terms of + surveillance or clinical management. + + NB: annotated notes appended to this routine illustrate a number of + analyses simulations relevant to various containment, suppression and + mitigation strategies. For example, the effect of early lockdowns, the + effect of maintaining a tracking and tracing policy at the inception of + the pandemic. In addition, there are notes showing how to incorporate + serological data during inversion of the dynamic causal model. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_T.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_UK` + +```{text} + FORMAT DCM = DEM_COVID_UK + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates Bayesian model comparison using a line search + over periods of imunity and pooling over countries. In brief,32 countries + are inverted and 16 with the most informative posterior over the period + of immunity are retained for Bayesian parameter averaging. The Christian + predictive densities are then provided in various formats for the average + country and (16) individual countries. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_UK.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_UK4` + +```{text} + FORMAT DCM = DEM_COVID_UK4 + + Demonstration of COVID-19 modelling using variational Laplace (4 groups) + __________________________________________________________________________ + This routine illustrates the dynamic causal modelling of the epidemic in + the United Kingdom using four age groups that are coupled via (prevalence + -dependent) contact rates. It is the routine used to prepare the graphics + and report for the DCM COVID dashboard. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_UK4.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_UTLA` + +```{text} + FORMAT [DCM] = DEM_COVID_UTLA + + Demonstration of COVID-19 modelling with stratified populations + __________________________________________________________________________ + + This demonstration routine fixed multiple regional death by date and new + cases data and compiles estimates of latent states for local + authorities served by an NHS trust provider. + + Technical details about the dynamic causal model used here can be found + at https://www.fil.ion.ucl.ac.uk/spm/covid-19/. + + The (annotated) open source code creating these graphics is + DEM_COVID_DASH.m + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_UTLA.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_WID` + +```{text} + FORMAT DCM = DEM_COVID_WID + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine addresses the global factors that underwrite mortality and + morbidity (and economic cost) by comparing different countries in terms + of the epidemiological and sociobehavioural parameters that best explain + the trajectory of daily cases and deaths. a subset of countries with a + large population and a low vaccination rate are modelled by optimising a + subset of country specific (free) parameters that capture differences in + exposure to the virus and subsequent responses; in terms of quarantine, + containment, resistance to infection and so on. The remaining model + parameters are assumed to be conserved over countries and are based on + posterior estimates derived from comprehensive timeseries data from the + United Kingdom. The between country analyses are based upon available + timeseries from Our World in Data + + The predictive validity of this modelling is established in terms of the + accuracy of long-term forecasting up to 6 months - in countries that are + modelled with sufficient accuracy (at least 50% variance in death rates + explained). A canonical correlation analysis is then used to establish + the key parameters or factors that account for differences in fatalities + over countries. Finally, the model is used to assess the impact of an + equable vaccination programme starting over the next month using scenario + modelling. This scenario modelling considers the impact of equable + vaccination on cumulative deaths and gross domestic product. The + conclusions are based upon a subset of countries accounting for over 50% + of the world's population. + + Please see the annotations in this script for further details at each + section of the analysis. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_WID.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_COVID_X` + +```{text} + FORMAT [DCM] = DEM_COVID_X(Y,data) + data - data to model [default: data = DATA_COVID_US] + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates the Bayesian model inversion of a generative + model of coronavirus spread using variational techniques (variational + Laplace). This (pandemic) model is composed of regional (epidemic) + models. In brief, the model for a single region comprises four factors, + each with four states, giving 256 states or compartments per region. + These regional models are then assembled to model the coupling among + eight regions giving 256^8 compartments. However, due to certain + conditional independencies, this can be treated as a collection of 256 + compartmental models; providing one carefully links the state of one + region to the state of another. Here, this linking or connectivity is + parameterised in terms of a probability flux or exchange of people from + one regional population to another. Regional factors include location, + immune status, clinical status and testing status. The transitions among + states of any factor depends upon other factors. For example, the + probability that I will move from a state of being asymptomatic to being + symptomatic depends upon whether I am infected or not. Similarly, the + probability that I will move from one region to another depends upon + whether I am at work (i.e., not at home). In short, the exchange between + different regional populations is limited to the people who are not at + home and are consequently in a position to travel. The parameters of + interregional coupling correspond to rate constants or effective + connectivity that can be reciprocal and asymmetric. For example, the + probability of moving to New York from New Jersey does not have to be the + same as a probability of moving from New Jersey to New York. Note that + the movement between regions can be restricted to a chain. In other + words, to get from the first state to the last state, I have to go + through all other states. + + Each subsection produces one or two figures that are described in the + annotated (Matlab) code. These subsections call various subroutines that + provide a more detailed description of things like the generative model, + its priors and the evaluation of confidence intervals. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_COVID_X.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_Dispatches` + +```{text} + FORMAT DCM = DEM_COVID_UK + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates Bayesian model comparison using a line search + over periods of imunity and pooling over countries. In brief,32 countries + are inverted and 16 with the most informative posterior over the period + of immunity are retained for Bayesian parameter averaging. The Christian + predictive densities are then provided in various formats for the average + country and (16) individual countries. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_Dispatches.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_FEP_Least_Action` + +```{text} + -------------------------------------------------------------------------- + This routine uses a Lorenz system to show that the most likely autonomous + path (or deterministic path) is uniquely identified by its initial and + final states. In other words, if we knew the end state of an autonomous + trajectory, then we would implicitly know the path taken from the initial + particular state, even if we did not know the external states. This point + is demonstrated using numerical analyses of the Lorenz system; treating + the first state and an active state and the third as an external state. + In this example, 1024 solutions are obtained from the same initial + particular (i.e., sensory and active) states but sampling from a Gaussian + distribution over external states. The ensuing trajectories over 128 time + bins of 1/128 seconds are shown in the left panels. The sample + distribution over active states is shown as a (scaled) histogram along + the x-axis. Paths that end within 1/8 of an arbitrary active state (here, + ?? = -4) are shown in red. The corresponding autonomous (i.e., active) + paths are shown as a function of time in the right panels. one can repeat + this analysis for different levels of random fluctuations; e.g.,log + precisions of 2 and 16. The key thing to observe is that as the amplitude + of random fluctuations decreases (i.e., its precision increases) the + paths that begin and end in the same place collapse to a single + trajectory of least action. This is the most likely or deterministic + path. Clearly, this behaviour rests upon a diffeomorphic mapping between + the initial and final states: for example, a final active state of -8 has + the least two paths of least action (xT in the code below). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_FEP_Least_Action.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_FEP_Lorenz` + +```{text} + -------------------------------------------------------------------------- + This is a simple demonstration of deterministic convergence to + nonequilibrium steady-state, using the Lorenz system. Deterministic + solutions (with a Rayleigh parameter of 28) are obtained for 2048 initial + states, integrating over eight seconds (with a time step of 1/64 + seconds). Crucially, the initial autonomous states are the same for each + solution and yet the final density over the autonomous (i.e., active) + state converges to the non-equilibrium steady-state density over time. + This is apparent in the collapse of the divergence between the sample + densities (over all states) and the final (NESS) density - as evaluated + simply using a Gaussian approximation to the ensemble densities at each + point in time. The upper plots show the propagated states at four points + in time. As time progresses, this density comes to assume the familiar + butterfly form of the Lorenz attractor. However, these states are not + trajectories through state space, they are the endpoints of paths from an + ensemble of starting locations (shown in the right plot). In this + illustration, we treat the first state of the Lorenz system as the active + state, the second state as the sensory state and the third state plays + the role of an external or hidden state. This designation is based upon + the fact that the first state is not influenced by the first. In short, + this numerical example shows how uncertainty about external states is + propagated over time to induce uncertainty about a particle's state; even + when the initial (particular) state is known. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_FEP_Lorenz.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_HB_and_LE` + +```{text} + -------------------------------------------------------------------------- + This routine is a numerical examination of the relationship between + entropy, mutual information and the exponential divergence of + trajectories as the Rayleigh parameter of a Lorenz attractoris increased + - through a pitchfork bifurcation and subsequent (subcritical) Hopf + bifurcation. The (stochastic) Lorentz system is integrated for different + values of the Rayleigh parameter. The nonequilibrium steady-state density + is then estimated by embedding into a discrete state space; while the + bifurcations are characterised in terms of the maximal Lyapunov exponent. + The key thing to observe is the decrease in entropy of blanket states + prior to the Hopf bifurcation and implicit exponential divergence of + trajectories. This is scored by the maximal Lyapunov exponent crossing + zero. Here, the form of the Lorenz attractor defines the three states as + active, sensory and hidden. Note that there are no internal states in + this example and blanket states become the particular states (i.e., the + states of a particle). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_HB_and_LE.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_Immune` + +```{text} + This demo builds upon the results of the COVID modelling demos, which + found that the epidemic data could best be explained by appealing to the + idea that much of the population may not be susceptible and that of those + who are, some may be resistant and only experience a mild illness. + This means measures of immunity based upon antibody tests may + underestimate the effective herd immunity. This demo formalises several + alternative hypotheses as to the mechanisms of resistance. It + demonstrates the way in which the underlying model may be inverted to + test these hypotheses. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_Immune.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_MDP_decision` + +```{text} + Demo of active inference for visual salience + __________________________________________________________________________ + + This routine illustrates the treatment of signal detection paradigms in + the context of active inference and Markov decision processes. This is + probably one of the simplest paradigms to model; in which there are just + too hidden states generating ambiguous stimuli - and the agent move from + an undecided (hidden) state to a definitive choice. The A tensor in this + instanceen codes ambiguity (perceptual noise), while the B matrix encodes + the behaviour-dependent transitions among decision states. Finally, + the C matrix encodes prior costs or preferences. In this instance, the + agent does not want to be wrong - and prefers to be right. + + in what follows, we simulate a single trial to illustrate the underlying + Bayesian belief updating and associated behavioural and physiological + responses. We then consider multiple trials under different levels of + ambiguity and cost. The dependent measures in this instance include the + behavioural accuracy, reaction times (assuming 250 ms time bins) and the + uncertainty about the cause of sensory cues and control - as measured by + the entropy of posterior beliefs prior to making a choice. + + see also: DEM_demo_MDP_rule.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_MDP_decision.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_SARS` + +```{text} + FORMAT DEM_SARS + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates Bayesian model comparison using a line search + over periods of imunity and pooling over countries. In brief,32 countries + are inverted and 16 with the most informative posterior over the period + of immunity are retained for Bayesian parameter averaging. The Christian + predictive densities are then provided in various formats for the average + country and (16) individual countries. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_SARS.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_SARS_I` + +```{text} + FORMAT DEM_COVID_I + data - data to model [default: data = DATA_COVID_JHU] + country - country to model [default: 'United Kingdom') + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine illustrates Bayesian model comparison using a line search + over periods of imunity and pooling over countries. In brief,32 countries + are inverted and 16 with the most informative posterior over the period + of immunity are retained for Bayesian parameter averaging. The Christian + predictive densities are then provided in various formats for the average + country and (16) individual countries. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_SARS_I.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_Stephen` + +```{text} + FORMAT Tab = DEM_Stephen + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine evaluates outcomes under some intervention over a specified + set of dates. The outcomes are then tabulated and displayed in the MATLAB + window. specify the duration and (parametric) nature of the intervention + by editing the code below; namely, the non-pharmacological intervention + structure NPI. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_Stephen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_birdsong` + +```{text} + Create basis set for sounds + FORMAT [S] = DEM_birdsong(file) + + file - .wav file + + S.U - h x 3 basis functions (Hz) + S.V - 3 x n basis functions (seconds) + S.Hz - s x 1 frequencies (Hz) + + Bird Song demo: These simple loads a .wav file of a real bird-song; and + approximates the ensuing spectrogram with in terms of three + time-frequency modes. These modes are saved in BirdSong.mat (U) for + illustrating DEM_demo_sequences + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_birdsong.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_cells` + +```{text} + This demo illustrates self-organisation in an ensemble of (sixteen) cells + using the same principles described in DEM_morphogenesis, but using a + simpler generative model. Overall, the dynamics of these simulations show + how one can prescribe a point attractor for each constituent of an + ensemble that endows the ensemble with a point attractor to which it + converges. In this example, we consider the special case where the point + attractor is itself a Markov blanket. In other words, cells come to + acquire dependencies, in terms of intracellular signalling, that conform + to a simple Markov blanket with intrinsic or internal cells, surrounded + by active cells that are, in turn, surrounded by sensory cells. This + organisation rests upon intracellular signals and active inference using + generalised (second-order) variational filtering. In brief, the hidden + causes driving action (migration and signalling) are expectations about + cell type. These expectations are optimised using sensory signals; + namely, the signals generated by other cells. By equipping each cell with + prior beliefs about what it would sense if it was a particular cell type + (i.e., internal, active or sensory), they act (i.e., move and signal) to + behave and infer their role in an ensemble of cells that itself has a + Markov blanket. In a DEM_cells_cells.m, we use this first-order scheme to + simulate the hierarchical emergence of Markov blankets; i.e., ensembles + of cells that can be one of three types at the local level; independently + of their time at the global level. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_cells.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_cells_cells` + +```{text} + This demo is a hierarchical extension of DEM_cells.m, where we have 16 + ensembles comprising 16 cells. Each cell has a generative model (i.e., + prior beliefs) about its possible local and global cell types (i.e., + internal, active or sensory). Given posterior beliefs about what sort of + self it is at the local and global level, it can then predict the local + and global intracellular signals it would expect to receive. The ensemble + of ensembles then converges to a point attractor; where the ensemble has + a Markov blanket and each element of the ensemble comprises a cell - that + is itself a Markov blanket. The focus of this simulation is how the local + level couples to the global level and vice versa. For simplicity (and + computational expediency) we only model one ensemble at the local level + and assume that the remaining ensembles conform to the same (local) + dynamics. This is effectively a mean field approximation, where + expectations of a cell in the first ensemble about its global type are + coupled to the corresponding expectations and the ensemble level, and + vice versa. The results of this simulation are provided in the form of a + movie and graphs.The figure legend is included in the code below. + + In this example, we have used the same generative model at both levels to + exploit the self similar hierarchical structure that emerges. However, we + could have used different generative models at the global and local + levels to simulate the morphogenesis of particular organelles that have a + different form from their constituent cellular ensembles. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_cells_cells.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_coupled_oscillators` + +```{text} + Dual estimation of the Lorenz system: Cross-validation of Laplace schemes + __________________________________________________________________________ + This routine illustrates the inversion of a loosely coupled oscillator + model using generalised filtering. In this example, three regions are + coupled in terms of their amplitude and phase in a hierarchical fashion. + Data are generated under a particular set of parameters. The timeseries + are then transformed using a Hilbert transform into the corresponding + analytic signal. This then constitutes the data feature for subsequent + inversion using generalised filtering; here, in four generalised + coordinates of motion. By assuming fairly precise priors on the amplitude + of random fluctuations one can recover the parameters and use the + posterior density for subsequent Bayesian model comparison. In this + example, we used Bayesian model reduction to assess the evidence for + models with and without amplitude or phase coupling. + + The parameters and orders of this example have been optimised to provide + proof of principle this sort of model can be inverted using generalised + filtering. The sensitivity to these parameters and orders can be + assessed numerically by editing the code. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_coupled_oscillators.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_dSprites` + +```{text} + Demo of active inference and structure learning (i.e.,disentanglement) + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + inference to illustrate structure learning. Structure learning here is + read as optimising the structure of a generative model that, crucially, + includes dynamics. This foregrounds the sequential order and temporal + scheduling of various updates. In this example, we start with a simple + problem in which one or more objects can be removed around in a + two-dimensional space. The kind of structure learning considered here can + be likened to nonparametric Bayes; namely, the addition of a model + component if licensed in terms of model evidence or marginal likelihood. + Procedurally, this means that with each new stimulus (sequence of + observations) various models are compared that entail the addition of a + new latent state, path or factor. If the ELBO (i.e., negative variational + free energy) increases the addition is accepted but not otherwise. The + training sequences are carefully constructed to reflect the ordinal + structure of observations. In other words, structure learning is + predicated on both the content and dynamics of the generative process. + + This demonstration calls a belief propagation scheme with factorisation + of latent states into factors. Furthermore, the likelihood mapping is + factorised into conditionally independent outcome modalities. This means + that the size of any requisite tensor for belief updating is upper + bounded by the factorisation or mean field approximation). This mitigates + the van Neumann bottleneck; leading to increased efficiency at all three + levels of optimisation (inference, learning and model selection). + + A key aspect of this demonstration routine is that it deals with discrete + state space generative models (and observations). This means that belief + propagation and updating can be implemented using linear (tensor) + operators; without worrying about nonlinearities of the sort found in + continuous state space models. + + _________________________________________________________________________ + Copyright (C) 2019 Wellcome Trust Centre for Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_dSprites.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo` + +```{text} + DEM_DEMO M-file for DEM_demo.fig + DEM_DEMO, by itself, creates a new DEM_DEMO or raises the existing + singleton*. + + H = DEM_DEMO returns the handle to a new DEM_DEMO or the handle to + the existing singleton*. + + DEM_DEMO('CALLBACK',hObject,eventData,handles,...) calls the local + function named CALLBACK in DEM_DEMO.M with the given input arguments. + + DEM_DEMO('Property','Value',...) creates a new DEM_DEMO or raises the + existing singleton*. Starting from the left, property value pairs are + applied to the GUI before DEM_demo_OpeningFunction gets called. An + unrecognized property name or invalid value makes property application + stop. All inputs are passed to DEM_demo_OpeningFcn via varargin. + + *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one + instance to run (singleton)". + + See also: GUIDE, GUIDATA, GUIHANDLES + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_ALAP` + +```{text} + This demonstration is essentially the same as DEM_demo_LAP - however + here, we compare two generalised filtering schemes that are implemented + very differently: the first integrates the generative process in + parallel with the inversion, while the standard spm_LAP scheme inverts a + model given pre-generated data. The advantage of generating and modelling + data contemporaneously is that it allows the inversion scheme to couple + back to the generative process through action (see active inference + schemes): spm_ALAP. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_ALAP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_Bayesian_Model_Reduction` + +```{text} + This demonstration code illustrates the application of post hoc model + optimisation or Bayesian model reduction (BMR) in identifying gene and + gene-gene interaction effects in behavioural or physiological variables. + The basic idea is to replace conventional heuristics based on the + assumption that the contribution of any gene is sampled from a sparse + distribution (such that a small number contribute and a large number do + not) with an explicit search over a model space that includes all sparse + and non-sparse models. This exhaustive search rests upon recent + advances in model optimisation based upon variational Bayesian model + inversion. In short, it is possible to estimate the posterior + distribution of model parameters under a reduced model, given the + posterior and prior distributions under a full model. + In this context, a reduced model corresponds to a model in which some + parameters are removed (by shrinking their prior variance to zero). + This means that it is only necessary to invert the full model and then + perform automatic BMR (over all possible combinations of parameters) + using a greedy search based upon the free energy approximation to log + model evidence. With sufficient signal to noise, this scheme can + recover the small number of effects, even in under determined or + ill-posed problems (where the number of potential effects can vastly + exceed the number of samples). + + The illustration below uses 128 subjects who have been measured three + times (say in three brain regions) and we want to model these + measurements in terms of first and second order genetic contributions + given 8 (binary) genetic variables and all (unique) pair wise + interactions. This means that there are 36 unknown parameters + (excluding a constant and, say, age confounds over subjects). In the + scheme below, each measurement is inverted separately under a simple + (polynomial) model with uninformative priors on the parameters and + (precision) hyper-parameters describing beliefs about signal to noise. + A fixed effects Bayesian model averaging (BMA) scheme is used in + combination with BMR to identify the best model out of all possible + combinations of first and second order effects. With the signal to + noise and number of samples used in this simulation, the recovery is + generally perfect. This scheme also illustrates inference over a + partition of model space (or families of models). + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_Bayesian_Model_Reduction.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_Cornsweet` + +```{text} + The Cornsweet effect: This demo illustrates the inference underlying the + Cornsweet effect or illusion. It exploits formal priors on the spatial + contiguity of the illuminant and reflectance; where the illuminant does not + have edges, but the reflectance can. This is implemented using a + discrete cosine set (DCT) as the spatial basis for the illuminant and a + (Haar) Discrete Wavelet transform (DWT) for the reflectance. Appropriate + shrinkage priors on the (implicit) transform coefficients ensure that the + explanation for visual input (reflectance times illuminant) assigns edges + to the reflectance; thereby producing the Cornsweet effect. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_Cornsweet.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_DCM_LAP` + +```{text} + Demo applying the Laplace scheme to DCM with hidden states + __________________________________________________________________________ + This routine demonstrates Generalized filtering for a DCM (Dynamic Causal + Model) of fMRI responses using simulated data. This is an endogenous + DCM in that there are no exogenous inputs. The demonstration specifies + and inverts a full connectivity model and then illustrates post-hoc model + optimization to recover (discover) the true architecture. It concludes + with an automatic model optimization in terms of the prior variances over + coupling parameters. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_DCM_LAP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_DEM` + +```{text} + Triple estimation of states, parameters and hyperparameters: + This demo focuses estimating both the states and parameters to furnish a + complete system identification, given only the form of the system and its + responses to unknown input (c.f., DEM_demo_EM, which uses known inputs) + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_DEM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_DFP` + +```{text} + DEM demo for linear deconvolution: This demo considers the deconvolution + of the responses of a single-input-multiple output input-state-output + model (DCM) to disclose the input or causes. It starts by demonstrating + Variational filtering with spm_DFP; this is a stochastic filtering scheme + that propagates particles over a changing variational energy landscape + such that their sample density can be used to approximate the underlying + ensemble or conditional density. We then repeat the inversion using + spm_DEM (i.e., under a Laplace assumption) which involves integrating the + path of just one particle (i.e., the mode). + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_DFP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_EM` + +```{text} + Dual estimation of parameters and hyperparameters; under known causes: + This demo focuses on conditional parameter estimation with DEM and + provides a comparative evaluation using EM. This proceeds by removing + uncertainly about the input so that the D-step can be discounted. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_EM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_GF_and_KF` + +```{text} + A demonstration of generalised and Kalman filtering where the number + of hidden states exceeds the number of variables observed. The metrics of + performance are the mean sum of squared error and the SSE normalized by + the posterior precision (NESS). The results of a single time series + analysis are shown first and then the simulations are repeated under + linear and nonlinear observation models to compare the relative + performance of DEM and EKF. The superiority of DEM (generalised filtering) + over Kalman filtering rests on the optimisation of K - the rate of + generalised descent on free energy (see code after 'return'). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_GF_and_KF.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_GLM` + +```{text} + Demo comparing DEM and ReML (restricted maximum likelihood) under a simple + general linear model (GLM). Slight differences in the hyperpriors of both + schemes make this an interesting exercise. Note that ReML uses a + covariance hyper-parameterisation; whereas DEM uses precision + hyperparameters. This demo uses a non-hierarchical GLM and switches the + roles of parameters and causes to illustrate their equivalence under a + DEM inversion. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_GLM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_Gabor` + +```{text} + State-space demo routine simulating position invariant representations + in the visual system. The generative model predicts a one-dimensional + Gabor patch that moves in a (one-dimensional) visual field. The + inversion of this dynamic model can be viewed as deconvolving spatial and + category attributes from a moving stimulus (or selective re-sampling of + the input) to recover the stimulus that can be represented. The + prediction shown in the lower panels had position information removed. + ___________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_Gabor.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_LAP` + +```{text} + This demonstration compares Generalised filtering under the Laplace + assumption (spm_LAP) with variational filtering under the same fixed form + approximation (i.e. DEM). We use a simple linear convolution model to + illustrate the differences and similarities. The key difference between + the two schemes lies (in this example) lies in estimates of conditional + uncertainty. spm_LAP is must less over-confident because it eschews the + means-field approximation implicit in DEM. The demonstration addresses + quadruple estimation of hidden states, exogenous input, parameters and + log-precisions (and, for spm_LAP, log-smoothness) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_LAP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_Lagrangian` + +```{text} + Demo to illustrate divergence and curl free flow specified by a + Lagrangian and antisymmetric matrices. This example uses a double well + potential and Newtonian dynamics. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_Lagrangian.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_Lagrangian_flow` + +```{text} + Demo to illustrate divergence and curl free flow specified by a + Lagrangian and antisymmetric matrices. This example uses a double well + potential and Newtonian dynamics. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_Lagrangian_flow.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_Lorenz` + +```{text} + Demo for a Lorentz attractor: In this example we show that DEM and + Bayesian filtering can estimate the hidden states of an autonomous system + showing deterministic chaos. Although all schemes perform well given the + correct starting values of the hidden states; DEM is the only scheme that + can re-capture the true trajectory without them. this is because DEM + represents generalised coordinates, in which the dynamics unfold. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_Lorenz.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_DEM` + +```{text} + Demo of mixed continuous and discrete state space modelling + __________________________________________________________________________ + + This routine illustrates the combination of discrete and continuous + state space models for active inference. In this example, the lowest + level of a hierarchical Markov decision process (used to illustrate + evidence accumulation during reading in related simulations) is equipped + with a continuous time and state space dynamical model at the lowest + level. This allows one to model both the categorical belief updates + using belief propagation and the continuous belief updates using + Bayesian filtering within the same model and associated inversion + scheme. + + The key contribution of this scheme is the message passing or belief + propagation between the lowest discrete state (MDP) level and the + highest level of the continuous state (DCM) models. In brief, during + inversion, posterior beliefs about hidden causes of observable + (continuous) inputs provide (probabilistic or posterior) outcomes for the + (categorical) MDP scheme. In return, the posterior predictive density + over outcomes of the MDP scheme specify priors on the hidden causes. In + this example, these priors determine the salient locations to which the + synthetic agent saccades. These saccades sample discriminative visual + information that resolves uncertainty about the content of the local + visual scene. Posterior expectations about the content then play the role + of observations for higher (categorical) levels. + + Note that the priors from the MDP levels are time invariant (i.e., the + attracting location of the saccade does not change during each saccadic + epoch). Similarly, the posterior beliefs are over attributes that do + not change during the saccadic sampling (i.e., the hidden cause of + visual input at the attracting location). This underwrites a separation + of temporal scales that is recapitulated at higher levels of the + categorical model. The implementation of these schemes is as general as + we could make it. The code below illustrates how one links MDP schemes + to DPM schemes in a generic way through hidden causes. + + More details about each level of the model are provided in line as + annotated descriptions. + + see also: spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_DEM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_X` + +```{text} + Demo of active inference for trust games + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + inference (with variational Bayes) to model foraging for information in a + three arm maze. This demo illustrates variational free energy + minimisation in the context of Markov decision processes, where the agent + is equipped with prior beliefs that it will minimise expected free energy + in the future. This free energy is the free energy of future sensory + states expected under the posterior predictive distribution. It can be + regarded as a generalisation of the variational formulation of KL control + in which information gain or epistemic value is formulated explicitly. + + In this example, the agent starts at the centre of a three way maze which + is baited with a reward in one of the two upper arms. However, the + rewarded arm changes from trial to trial. Crucially, the agent can + identify where the reward (US) is located by accessing a cue (CS) in the + lower arm. This tells the agent whether the reward is on the left or the + right upper arm. This means the optimal policy would first involve + maximising information gain or epistemic value by moving to the lower arm + and then claiming the reward this signified. Here, there are eight hidden + states (four locations times right or left reward), four control states + (that take the agent to the four locations) and four exteroceptive + outcomes (that depend on the agents locations) plus three interoceptive + outcomes indicating reward (or not). + + This version focuses on factorising the hidden states causing + (factorised) outcomes. This factorisation is implicit in the tensor + production used in the companion demo. Here the factorisation is + explicit enabling us to model multiple modalities (outcome factors) and + distinct hidden causes of observation (hidden state factors like what and + where). The behaviour is formally similar to the vanilla scheme but + allows a much more intuitive (and possibly flexible) model specification. + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_X.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_XX` + +```{text} + Demo of active inference (T-maze): belief propagation scheme + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + inference (with belief propagation) to model foraging for information in + a three arm maze. This demo illustrates active inference in the context + of Markov decision processes, where the agent is equipped with prior + beliefs that it will minimise expected free energy in the future. This + free energy is the free energy of future sensory states expected under + the posterior predictive distribution. It can be regarded as a + generalisation of KL control that incorporates information gain or + epistemic value. + + In this example, the agent starts at the centre of a three way maze which + is baited with a reward in one of the two upper arms. However, the + rewarded arm changes from trial to trial. Crucially, the agent can + identify where the reward (US) is located by accessing a cue (CS) in the + lower arm. This tells the agent whether the reward is on the left or the + right upper arm. This means the optimal policy would first involve + maximising information gain or epistemic value by moving to the lower arm + and then claiming the reward this signified. Here, there are eight hidden + states (four locations times right or left reward), four control states + (that take the agent to the four locations) and four exteroceptive + outcomes (that depend on the agents locations) plus three interoceptive + outcomes indicating reward (or not). + + This version focuses on a sophisticated AI implementation that replaces + policies (i.e., ordered sequences of actions) with a deep tree search + over all combinations of actions. This deep search evaluates the expected + free energy under outcomes following an action and the ensuing hidden + state. The average over hidden states and future actions is then + accumulated to provide the free energy expected under a particular course + of action in the immediate future. Notice that the free energy expected + under the next action is not the expected free energy following that + action. In other words, there is a subtle distinction between taking an + expectation under the posterior predictive distribution over outcomes and + the expectation of free energy over outcomes. This scheme is + sophisticated in the sense that the consequences of action for posterior + beliefs enter into the evaluation of expected free energy. + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_XX.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_fit` + +```{text} + Demo of active inference for trust games + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + inference (with variational Bayes) to model foraging for information in a + three arm maze. This demo illustrates the inversion of single-subject + and group data to make inferences about subject-specific parameters - + such as their prior beliefs about precision and utility. We first + generate some synthetic data for a single subject and illustrate the + recovery of key parameters using variational Laplace. We then consider + the inversion of multiple trials from a group of subjects to illustrate + the use of empirical Bayes in making inferences at the between-subject + level. Finally, we demonstrate the use of Bayesian cross-validation to + retrieve out-of-sample estimates (and classification of new subjects). + + In this example, an agent starts at the centre of a three way maze that + is baited with a reward in one of the two upper arms. However, the + rewarded arm changes from trial to trial. Crucially, the agent can + identify where the reward (US) is located by accessing a cue (CS) in the + lower arm. This tells the agent whether the reward is on the left or the + right upper arm. This means the optimal policy would first involve + maximising information gain or epistemic value by moving to the lower arm + and then claiming the reward thus signified. Here, there are eight hidden + states (four locations times right or left reward), four control states + (that take the agent to the four locations) and seven outcomes (three + locations times two cues plus the centre). The central location has an + ambiguous or uninformative outcome, and the upper arms are rewarded + probabilistically. + + see also: spm_MPD_VB.m, spm_dcm_mdp.m and spm_nlsi_Newton.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_fit.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_fit_fields` + +```{text} + Demo of active inference for visual salience + __________________________________________________________________________ + + This routine uses active inference for Markov decision processes to + illustrate epistemic foraging in the context of visual searches. Here, + the agent has to categorise scenes on the basis of the relative position + of various cues. Crucially, the agent can only sample one cue or location + at a time and therefore has to accumulate evidence for competing + hypotheses. This rests upon resolving uncertainty about which scene or + hypothesis is in play through the minimisation of expected free energy. + + When the agent become sufficiently confident about the underlying scene, + it then makes a saccade to a choice location - to obtain feedback (right + or wrong). The agent prefers to be right and does not expect to be + wrong. We first illustrate a single trial in terms of behaviour and + electrophysiological responses. We then consider sequences of trials and + how one can recover prior preferences by inverting a model of observed + responses (and cues). + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_fit_fields.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_habits` + +```{text} + Demo of active inference for trust games + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + inference (with variational Bayes) to model foraging for information in a + three arm maze. This demo illustrates variational free energy + minimisation in the context of Markov decision processes, where the agent + is equipped with prior beliefs that it will minimise expected free energy + in the future. This free energy is the free energy of future sensory + states expected under the posterior predictive distribution. It can be + regarded as a generalisation of the variational formulation of KL control + in which information gain or epistemic value is formulated explicitly. + + In this example, the agent starts at the centre of a three way maze + which is baited with a reward in one of the two upper arms. However, the + rewarded arm changes from trial to trial. Crucially, the agent can + identify where the reward (US) is located by accessing a cue (CS) in the + lower arm. This tells the agent whether the reward is on the left or the + right upper arm. This means the optimal policy would first involve + maximising information gain or epistemic value by moving to the lower arm + and then claiming the reward this signified. Here, there are eight hidden + states (four locations times right or left reward), four control states + (that take the agent to the four locations) and five outcomes (two + locations times two cues plus the centre). The central location has an + ambiguous or uninformative cue outcome, while the upper arms are rewarded + probabilistically. + + This version focuses on learning by optimising the parameters of the + generative model. In particular, it looks at the acquisition of epistemic + habits - and how they relate to optimal policies under dynamic + programming. We start with a series of simulations to illustrate various + phenomena in electrophysiology and then move on to learning per se. + + see also: spm_MPD_game + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_habits.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_maze` + +```{text} + Demo of active inference for epistemic foraging + __________________________________________________________________________ + + This routine uses the Markov decision process formulation of active + inference (with variational Bayes) to model foraging for information in a + three arm maze. This demo illustrates variational free energy + minimisation in the context of Markov decision processes, where the agent + is equipped with prior beliefs that it will minimise expected free energy + in the future. This free energy is the free energy of future sensory + states expected under the posterior predictive distribution. It can be + regarded as a generalisation of the variational formulation of KL control + in which information gain or epistemic value is formulated explicitly. + + In this example, the agent starts at the centre of a three way maze + which is baited with a reward in one of the two upper arms. However, the + rewarded arm changes from trial to trial. Crucially, the agent can + identify where the reward (US) is located by accessing a cue (CS) in the + lower arm. This tells the agent whether the reward is on the left or the + right upper arm. This means the optimal policy would first involve + maximising information gain or epistemic value by moving to the lower arm + and then claiming the reward this signified. Here, there are eight hidden + states (four locations times right or left reward), four control states + (that take the agent to the four locations) and 16 outcomes (four + locations times two cues times two rewards). The central location has an + ambiguous or uninformative cue outcome, while the upper arms are rewarded + probabilistically with an 80% schedule. + + A single trial is simulated followed by an examination of dopaminergic + responses to conditioned and unconditioned stimuli (cues and rewards). A + hierarchical version is then implemented, in which the mapping between + locations in the generative model and the generative process is unknown + and has to be learned. + + see also: spm_MPD_game + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_maze.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_reading` + +```{text} + Demo of active inference for visual salience + __________________________________________________________________________ + + This routine provide simulations of reading to demonstrate deep temporal + generative models. It builds upon the scene construction simulations to + equip the generative model with a second hierarchical level. In effect, + this creates an agent that can accumulate evidence at the second level + based upon epistemic foraging at the first. In brief, the agent has to + categorise a sentence or narrative into one of two categories (happy or + sad), where it entertains six possible sentences. Each sentence comprises + four words, which are themselves constituted by two pictures or graphemes + These are the same visual outcomes used in previous illustrations of + scene construction and saccadic searches. + + Here, the agent has policies at two levels. The second level policy (with + just one step into the future) allows it to either look at the next word + or stay on the current page and make a decision. Concurrently, a first + level policy entails one of four saccadic eye movements to each quadrant + of the current page, where it will sample a particular grapheme. + + This provides a rough simulation of reading - that can be made more + realistic by terminating first level active inference, when there can be + no further increase in expected free energy (i.e., all uncertainty about + the current word has been resolved). The subsequent inferred hidden + states then become the outcome for the level above. + + To illustrate the schemes biological plausibility, one can change the + agent's prior beliefs and repeat the reading sequence under violations of + either local (whether the graphemes are flipped vertically) or globally + (whether the sentence is surprising) expectations. This produces a + mismatch negativity (MMN) under local violations) and a MMN with a + P300 with global violations. + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_reading.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_rule` + +```{text} + Demo of active inference for visual salience + __________________________________________________________________________ + + This routine simulates a crude form of consciousness using active + inference and structure learning to vitiate ignorance or nescience. This + entails learning the hyperparameters of causal structure generating + outcomes and then using Bayesian model reduction (during sleep) to + minimise complexity. + + We first set up an abstract problem in which an agent has to respond + according to rules (identify the correct colour depending upon one of + three rules that are specified by the colour of a cue in the centre of + vision). If the rule is centre, the colour is always green; however, if + the colour of the Centre cue is red, the correct colour is on the left + (and on the right if the queue is blue). Simulations are provided when + the agent knows the rules. This is then repeated in the absence + (nescience) of any knowledge about the rules to see if the agent can + learn causal structure through Bayesian belief updating of the likelihood + array (A). + + We then consider the improvement in performance (in terms of variational + free energy, its constituent parts and performance) following Bayesian + model reduction of the likelihood model (heuristically, like slow wave + sleep), followed by a restitution of posterior beliefs during fictive + active inference (as in REM sleep). Finally, we address the communication + of the implicit structure learning to a conspecific or child to + demonstrate the improvement under instruction. + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_rule.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MDP_search` + +```{text} + Demo of active inference for visual salience + __________________________________________________________________________ + + This routine uses active inference for Markov decision processes to + illustrate epistemic foraging in the context of visual searches. Here, + the agent has to categorise scenes on the basis of the relative position + of various cues. Crucially, the agent can only sample one cue or location + at a time and therefore has to accumulate evidence for competing + hypotheses. This rests upon resolving uncertainty about which scene or + hypothesis is in play through the minimisation of expected free energy. + + When the agent become sufficiently confident about the underlying scene, + it then makes a saccade to a choice location - to obtain feedback (right + or wrong). The agent prefers to be right and does not expect to be + wrong. We first illustrate a single trial in terms of behaviour and + electrophysiological responses. We then consider sequences of trials and + how average behaviour (accuracy, number of saccades and saccade duration) + depends upon prior preferences and prior precision. + + This demonstration uses a factorised version of the MDP scheme. In + other words, we assume a mean field approximation to the posterior over + different hidden states (context, location, scene reflection) - and over + multiple modalities (what versus where). This provides a parsimonious + representation of posterior beliefs over hidden states - but does induce + degree of overconfidence associated with approximate Bayesian inference. + + see also: DEM_demo_MDP_habits.m and spm_MPD_VB_X.m + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MDP_search.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MMN` + +```{text} + This Demo uses the linear convolution model of previous examples to + simulate chirps (c.f., the bird song demos). By presenting a train of + chirps and changing the stimulus after a couple of presentations, we can + simulate a roving oddball paradigm used in ERP research. Critically, we + hope to see a more exuberant response to the first presentation of a + novel chirp (oddball) relative to the same stimulus after learning + (standard). The simulation shows that although veridical percepts obtain + from variational de-convolution, the prediction error continues to fall + with repetition (as the parameters are optimised). This repetition + suppression subtends a mismatch response that has many of the + characteristics of the well-known mismatch negativity (MMN). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MMN.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MMN_deviance` + +```{text} + This Demo is a more refined illustration of the mismatch negativity that + uses a plausible (nonlinear) mapping from hidden states to sensory + samples; namely, a discrete spectral density (with a fixed frequency or + pitch tuning). This is modelled using a radial basis function over + frequencies, whose location parameter is a hidden state encoding pitch and + whose amplitude is modulated dynamically by hidden states encoding + amplitude modulation (the sum of two squared hidden states showing damped + linear oscillation when perturbed by a hidden cause). The recognition + dynamics illustrate a dissociation between the effects of changing the + (i) the level of deviancy of a stimulus (modelled here as a deviation of + the hidden state (cause) encoding pitch from zero) and (ii) the + probability of encountering a pitch deviant. This is modelled by changing + the precision on the hidden (pitch) state. Crucially, the nonlinearities + in this more plausible generative model of pure tone stimuli induce a + latency difference in the mismatch response and increase the amplitude + of the mismatch (i.e., MMN). Conversely, changing the precision only + affects the amplitude. In these simulations the MMN is modelled simply as + the difference between prediction errors evoked by an expected stimulus + (the standard) and a deviant stimulus. Prior expectations are encoded + in terms of hidden causes, where the onset of the stimulus is known. + This means the agent has correct prior expectations about amplitude + modulation (i.e., knows when to expect a stimulus) but can have + incorrect expectations about its pitch (of varying confidence or + precision). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MMN_deviance.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_MMN_gen` + +```{text} + generates hidden states for a MMN roving paradigm using spm_DEM + FORMAT [x,DEM] = DEM_demo_MMN_gen(P,G,U); + + P - parameters + G - generative (response) model + U - design + + x - hidden neuronal states {(ns x (nr x 8)}; ... } + DEM - stucture array of DEM structures + + see DEM_demo_MMN + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_MMN_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_OU` + +```{text} + DEM demo for linear deconvolution: This demo considers the deconvolution + of one of the simplest dynamical process; a random walk or Ornstein- + Uhlenbeck process. It shows how DEM can infer on the causes as stochastic + innovations (c.f., Bayesian filtering) by exploiting temporal + correlations. Strictly speaking this is not a Ornstein-Uhlenbeck process + because the innovations are themselves correlated and would normally be a + Wiener process + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_OU.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_PEB` + +```{text} + DEM demo for a hierarchical linear model (MFX). This inversion is + cross-validated with restricted maximum likelihood using and parametric + empirical Bayes (spm_PEB). It uses a simple two level model that embodies + empirical shrinkage priors on the first-level parameters (c.f., + DEM_demo_GLM, with no empirical priors) + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_PEB.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_Posner` + +```{text} + This demonstration routine simulates the Posner paradigm to show that + some of the characteristic speed-accuracy trade-offs associated with + valid and invalid cueing can be explained easily in terms of optimizing + precisions during hierarchical inference. This demonstration uses + generalised filtering and state-space model that includes state-dependent + noise. Here, this dependency is used to set the attentional gain or bias + using a cue, which modulates the prediction errors induced by subsequent + targets. The phenomena that emerge from this scheme include a competition + for attentional resources; given that only one context can exist at any + time and this probabilistic context is encoded by state-dependent + precisions on the causes of sensory input. Attended stimuli have greater + precision and greater penetration of their prediction errors in the + hierarchy. We will also see characteristic differences between perceptual + inference, under valid and invalid cues. This is illustrated using + simulated psychophysical and electrophysiological responses. Biased + competition is simulated by presenting both valid and invalid targets + simultaneously. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_Posner.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_SOC` + +```{text} + Demo for a bird songs: this routine illustrates self organised + criticality in terms of stimulus induced bifurcations and weak + synchronisation of recognition (neuronal) dynamics. It uses the birdsong + example, where stimuli are generated using a Lorentz attractor and + modelled with the same attractor, with state dependent parameters. + These control parameters are categorised in terms of a softmax function + of point attractors in a (two-dimensional) perceptual space. We examine + the self organised criticality in terms of Lyapunov exponents and the + free energy - as a function of precision of the motion of hidden states + (see code after return). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_SOC.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_connectivity_fMRI` + +```{text} + Demonstration of DCM for fMRI-CSD with hierarchical constraints + __________________________________________________________________________ + This demonstration routine illustrates the inversion of resting state + fMRI timeseries using a generative model of the adjacency matrix. This + model is based upon an embedding space of dimension ED in which the + (log) connectivity among nodes is a (radial basis) function of their + metric separation. This generative model of connectivity requires a + hierarchical constraint on the edges and therefore uses the expectation + and maximisation steps of dynamic expectation maximisation. Here, the + hidden causes at the first level are the effective connectivity and the + hidden causes at the second level are the Lyapunov exponents or + eigenvalues of a symmetrical Jacobian or effective connectivity matrix: + see DEM_demo_modes_fMRI.m + + Simulated timeseries are generated and inverted under typical priors. + This routine that performs a model space search over precisions on the + hierarchical constraints and the dimensionality of the embedding space. + This illustrates: (i) the increase in model evidence afforded by + hierarchical constraints (when they are true) and (ii) the optimal + prior precision that reflects the amplitude of random variations in + connectivity about the constraints. (iii) Finally,the search over model + dimension illustrates how Bayesian model comparison can identify the + dimensionality of the metric space generating hierarchical connectivity. + + see also: DEM_demo_modes_fMRI.m + spm_dcm_fmri_csd_DEM.m + spm_dcm_fmri_graph_gen.m + spm_dcm_fmri_mode_gen + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_connectivity_fMRI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_contact_lens` + +```{text} + This demo illustrates tracking under the contact lens problem: + The contact lens refers to the non-Gaussian uncertainty induced by + nonlinear measurements. Here it is illustrated in terms of tracking the + motion of a target in Cartesian coordinates, given the distance to target + (range) and direction as measurements. The problem is to accumulate + information over time about the target location under random fluctuations + on the velocity (technically this is a constant acceleration model). + Comparative evaluations are made with Extended Kalman filtering. + + See: X. Tian, Y. Bar-Shalom, Coordinate Conversion and Tracking for + Very Long Range Radars. IEEE Transactions on Aerospace and Electronic + Systems, AES-45(3):1073-1088, July 2009. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_contact_lens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_convolution` + +```{text} + DEM demo for linear deconvolution: This demo considers the deconvolution + of the responses of a single-input-multiple output input-state-output + model (DCM) to disclose the input or causes. It focuses on estimating the + causes and hidden states: The notes provide a comparative evaluation with + extended Kalman filtering (see script after return). + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_convolution.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_convolution_LAP` + +```{text} + Linear convolution revisited: A dual estimation problem + __________________________________________________________________________ + This demonstration compares generalised filtering and a state-of-the-art + Bayesian smoother (SCKS) in the context of dual estimation. Note that the + parameter estimates are smaller then the true values for generalised + schemes (LAP and DEM). This is largely due to the shrinkage priors and + optimisation of model evidence (marginal likelihood), as opposed to the + likelihood optimised by the Square-root Cubature Kalman Smoother (SCKS). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_convolution_LAP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_dendrite` + +```{text} + Free-energy and the single neuron: + __________________________________________________________________________ + This demo illustrates the use of Lotka-Volterra form SHCs (Stable + heteroclinic channels) to prescribe active sampling (inference). In this + example, we assume that neurons self-organise to minimise a free energy + bound on the informational surprise in the pre-synaptic inputs that are + sampled. We model this as a selective pruning of post-synaptic spines + that are expressed on the dendritic tree. This pruning occurs when the + (optimised) post-synaptic gain falls to small values. Crucially, post- + synaptic gain (encoding the precision of the neuron's prediction errors + about its pre-synaptic inputs) is itself optimised with respect to free- + energy. Furthermore, the pruning itself suppresses free-energy as the + neuron selects post-synaptic specialisations that conform to its + expectations. This provide a principled account of how neurons organise + and selectively sample the myriad of potential pre-synaptic inputs they + are exposed to, but it also connects elemental neuronal (dendritic) + processing to generic schemes in statistics and machine learning: + such as Bayesian model selection and automatic relevance determination. + The demonstration of this scheme simulates direction selectivity in post + synaptic transients and (see notes after 'return') spike-timing dependent + plasticity. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_dendrite.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_double_well` + +```{text} + DEMO comparing DEM with particle filtering in the context of a bimodal + conditional density. This demonstrates a shortcoming of DEM in that it + fails to represent the true density. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_double_well.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_doublewell_LAP` + +```{text} + The double-well revisited: + __________________________________________________________________________ + This demonstration compares generalised filtering and a state-of-the-art + Bayesian smoother (SCKS) in the context of a double-well system. Here the + Cubature filtering outperforms generalised schemes that are confounded by + the failure of the Laplace assumption. Note that generalised filtering + and DEM give the same conditional estimates of states because there are + no free parameters or hyperparameters and the mean-field assumption + implcit in DEM is irrelevant. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_doublewell_LAP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_duet` + +```{text} + This demonstration uses active inference (as implemented in spm_ALAP) to + illustrate birdsong and communication using predictive coding. In this + example, priors on high-level sensorimotor constructs (e.g., in the + avian higher vocal centre) are used to generate proprioceptive + predictions (i.e., motor commands) so that the bird can sing. However, in + the absence of sensory attenuation, the slight differences between + descending predictions and the sensory consequences of self-made songs + confound singing. This means that sensory attenuation is required so + that the bird can either sing or listen. By introducing a second bird + and alternating between singing and listening respectively, one can + simulate communication through birdsong. This is illustrated with one + cycle of singing and listening, where the high level expectations about + hidden states become synchronised; in effect, the two birds are singing + from the same 'hymn sheet' or narrative and can be regarded as + communicating in the sense of pragmatics. The first bird's expectations + are shown in red, while the second bird's are shown in cyan. + + To simulate learning of each other's (high-level) attractor, set LEARN to + one in the main script.. To separate the birds - and preclude + communication (or synchronisation chaos) set NULL to 1. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_duet.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_fMRI_HMM` + +```{text} + Demonstration of Hidden Markov models for fMRI + __________________________________________________________________________ + This demonstration routine illustrates the modelling of state + transitions generating resting state fMRI timeseries. The hidden states + are modelled as a hidden Markov model, where each state corresponds to a + particular point in the parameter space of effective connectivity. This + effective connectivity then generates complex cross spectral data + features of the observed timeseries. Model specification requires prior + constraints on the probability transition matrix among hidden states, + which implicitly specifies the number of hidden states. The user also + has to specify the number of windows for epochs to apply to the + timeseries, where each epoch places a lower bound on the duration of + each (discrete) state. + We first generate synthetic data using regular transitions among + three hidden states (C.F., a discrete version of a heteroclinic + cycle for orbit). The data are then converted by a routine that + combines a parametric empirical Bayesian model and a hidden Markov model + (as implemented as a special case of a Markov decision process). This + inversion is repeated for each model specified in terms of the + transition matrices (as prior Dirichlet concentration parameters). + Setting a prior transition parameter to 0 precludes that transition. In + this way, several different models of transitions and number of hidden + states can be scored in terms of the variational free energy. + Following inversion, the results are plotted in terms of expected + state transitions, fluctuations in connections that are allowed to + change (specified in the usual way by DCM.b), the deviations in + connectivity associated with each hidden state and the expected + probability transition matrix. + Finally, we consider Bayesian model comparison in terms of group + differences (here, simply the difference between the first and second + simulated subject). Bayesian model comparison is simple to do in this + context by comparing the free energy of a hidden Markov model in which + both groups share the same state dependent connections and transition + probabilities, with two independent models. These can be evaluated + efficiently using Bayesian model reduction implicit in PEB. in this + example, we did not introduce any differences between the two groups + (i.e., subjects) and therefore expected to infer no group effect. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_fMRI_HMM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_fMRI_PEB` + +```{text} + Demonstration of PEB for multisession spectral DCM studies + __________________________________________________________________________ + This demonstration routine illustrates the analysis of a multisession + fMRI study using spectral DCM. Crucially, the between session effects are + characterised using empirical Bayes and Bayesian model reduction. This + means that the original session data are only inverted once (at the + within session level). The resulting posterior estimates and then used to + make inferences about between session effects (e.g., time or drug + effects). The basic question addressed in this sort of analysis is where + between session effects are expressed in terms of connectivity or + parameters of neuronal fluctuations. These sorts of effects are specified + in a second level design matrix in the usual way and can be identified + using Bayesian model reduction. + + in this example, we analyse three sessions with a monotonic change in the + intrinsic (self) connectivity over three sessions. This involves + decreases in diagonal A parameters at the first two levels of a simple + three node hierarchy - and an increase at the highest (third) level. + Physiologically, this corresponds to a decrease in self-inhibition (or + increase in excitability) in the lower notes for regions, as time goes + on. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_fMRI_PEB.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_face_inference` + +```{text} + Recognising facial expressions: This demo uses the linear convolution + model with two hidden states and one cause to generate coefficients of + visual basis functions that produce a moving face. The basis functions are + images have been chosen so that the appropriate nonlinear mixture creates + a smile. The coefficients of the i-th basis image is + + cos((i - 1)*pi*g(x)) + + where g(x) is some none linear mixture of hidden sates that lies in the + range [0,1]. (neutral to smiling). Inversion of this model corresponds to + nonlinear Bayesian de-convolution of visual input to recognise the dynamic + expressions. The associated (roving MMN) demonstration uses this + generative model to illustrate perceptual learning and repetition suppression + when we repeat the stimulus. Clicking on the images will display the + movies entailed by the true and estimated causes. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_face_inference.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_factor_analysis` + +```{text} + Demo for Probabilistic Factor Analysis; This uses a hierarchical model + under the constraint that the causes have a deterministic and stochastic + components. The aim is to recover the true subspace of the real causes. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_factor_analysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_filtering` + +```{text} + State-space demo routine comparing Bayesian filtering and DEM: The + system here is chosen to highlight changes in conditional moments + (including precision) induced by nonlinearities in the model. A + comparative evaluation is provided using extended Kalman filtering and + particle filtering. Crucially, DEM and particle filtering deal gracefully + with nonlinearities, in relation to Kalman filtering. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_filtering.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_hdm` + +```{text} + demo for Hemodynamic deconvolution + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_hdm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_hdm_LAP` + +```{text} + Demo for Hemodynamic deconvolution: Cross-validation of Laplace scheme + __________________________________________________________________________ + This demonstration compares generalised filtering and DEM in the context + of a nonlinear convolution model using empirical data. These are the data + used to illustrate hemodynamic deconvolution. We have deliberately made + the problem difficult here to highlight the ability of Generalised + filtering to accumulate evidence to optimise in parameters and hyper- + parameters, which allows it to outperform DEM (although it does not + find visual motion effects with 90% confidence) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_hdm_LAP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_hdm_SCK` + +```{text} + Demo for Hemodynamic deconvolution: Cross-validation of Laplace scheme + __________________________________________________________________________ + This demonstration compares generalised filtering and SCKS in the context + of a nonlinear convolution model using synthetic data. Here, we look at + estimating three of the hemodynamic parameters. This is a particularly + difficult (almost impossible) problem, given their distance from the data + and the conditional dependencies with the hidden states. Furthermore, + this is an unrealistic simulation, because we assume the data are almost + noiseless. The key thing to focus on is the comparative performance in + recovering the hidden states and causes. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_hdm_SCK.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_hierarchical_optmisation` + +```{text} + This is the same as spm_nlsi_GH but tries to model the free energy as a + function of conditional expectations using a sparse mixture of scaled + Gaussians. The objective is to account for local maxima when optimising + free energy by recasting the problem in terms of a parameterised mapping + from conditional expectation to free energy explicitly. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_hierarchical_optmisation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_induced_fMRI` + +```{text} + Demonstration of DCM for CSD (fMRI) with simulated responses + __________________________________________________________________________ + This demonstration compares generalised filtering and deterministic DCM + (generating complex cross spectra) in the context of a nonlinear + convolution (fMRI) model using simulated data. Here, the dynamic + convolution model for fMRI responses is converted into a static + non-linear model by generating not the timeseries per se but their + second-order statistics - in the form of cross spectra and covariance + functions. This enables model parameters to the estimated using the + second order data features through minimisation of variational free + energy. For comparison, the same data are inverted (in timeseries form) + using generalised filtering. This example uses a particularly difficult + problem - with limited data - to emphasise the differences. + + NB - the generalised filtering trakes much longer than the deterministic + scheme + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_induced_fMRI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_large_fMRI` + +```{text} + Demonstration of DCM for CSD (fMRI) with simulated responses + __________________________________________________________________________ + This routine demonstrates Bayesian parameter averaging using the + variational inversion of spectral DCMs for fMRI. A random connectivity + matrix is generated and inverted. The posterior estimates are then used + to create new data, that are used to invert a series of DCMs. After each + inversion, basing parameter averaging is used to illustrate convergence + to the true values. In principle, this routine can handle large DCMs. + We illustrate (for time convenience) the inversion of eight nodes and 64 + connections. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_large_fMRI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_lorenz_LAP` + +```{text} + Dual estimation of the Lorenz system: Cross-validation of Laplace schemes + __________________________________________________________________________ + Inversion of the Lorenz attractor with DEM, LAP and SCKS schemes: This + demo tackles the difficult problem of deconvolving (chaotic) hidden states + from a single response variable, while estimating the parameters of the + underlying equations of motion. It calls generalised filtering, DEM and + a state-of-the-art Bayesian smoother (SCKS). This example is chosen to + show that it is, in principle, possible to perform dual estimation in the + context of chaotic dynamics (although small variations in this problem + will cause the schemes to fail due it its inherently nonlinear nature and + non-identifiability); however, the results are imperfect. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_lorenz_LAP.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_modes_fMRI` + +```{text} + Demonstration of spectral DCM for fMRI with eigenvector constraints + __________________________________________________________________________ + This demonstration routine illustrates the inversion of resting state + fMRI timeseries using a generative model of the adjacency matrix. This + model is based upon the eigenmodes of the functional connectivity matrix, + which are the eigenvectors of the effective connectivity matrix or + Jacobian - assuming the effective connectivity is symmetrical. This means + it is only necessary to estimate the eigenvalues; in other words, one + unknown parameter per node. + + Simulated timeseries are generated and inverted under typical priors. + This routine then performs a model space search over the decay rates of + stable (dissipative) modes and the number of unstable modes. + This illustrates: (i) the increase in model evidence afforded by + hierarchical constraints (when they are true) and (ii) the identification + of the principle modes underlying connectivity. + + NB: To see the model optimisation delete the 'return' at about line 200 + + see also: DEM_demo_connectivity_fMRI + spm_dcm_fmri_mode_gen + spm_dcm_fmri_mode + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_modes_fMRI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_ontology` + +```{text} + This demonstration routine illustrates how a generative model can be used + to furnish a computational nosology. In brief, it generates symptoms and + diagnostic profiles from hidden or latent exogenous causes (e.g., + therapeutic interventions) that are mediated by latent (pathophysiological + and psychopathological) states. Pathophysiological trajectories are + modelled with a Lorenz attractor that (with a linear mapping) + produces (two-dimensional) psychopathology. In turn, the + psychopathological states generate symptoms (with a non-linear function + of linear mixtures) and diagnostic outcomes (with a softmax function of + diagnostic potential). The psychopathological state of a subject is + associated with a diagnostic potential in terms of its Euclidean distance + from disease categories (locations in the associated state space). + + We start by simulating a relapsing-remitting disease process and then + infer the latent states and parameters of a particular subject. + This is then repeated in the setting of a therapeutic intervention. + The demonstration then briefly considers model identification and + selection by focusing on the mapping between pathophysiology and + psychopathology. Finally, We consider, prognosis and prediction by + estimating subject-specific parameters prior to therapy and then + predicting putative response in the future, based upon a posterior + predictive density. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_ontology.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_psychosis` + +```{text} + This demonstration routine illustrates the use of attractors in dynamical + systems theory to explain fluctuations in longitudinal data, such as + symptom scores. The generative model is based upon a Lorenz system that + features a number of attractors; namely, fixed point attractors + (modelling conditions that resolve), quasi-periodic attractors that can + model cyclothymic conditions, and chaotic attractors that show a more + itinerant time course. As with the model based upon stochastic chaos, the + Lorenz system generates fluctuations in a low dimensional space of + physiological variables that, in turn, generate psychological states, + which are then thresholded to generate symptom scores. In this example, + there are three physiological states, two psychological states and two + kinds of symptom score (generated by using a soft threshold function of + psychological states). The parameters of this model range from the + parameters of the dynamical attractor that determine the underlying time + course of some synthetic (e.g., schizoaffective) disorder through to the + parameters of the likelihood mapping to symptom scores – and the initial + states. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_psychosis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_song_inference` + +```{text} + Perceptual categorisation of bird songs: The generative model of + birdsong used in this simulation comprises a Lorenz attractor with two + control parameters (or hidden causes), which, in turn, delivers two + control parameters to a synthetic syrinx to produce 'chirps' that are + modulated in amplitude and frequency. The chirps were then presented + as a stimulus to a synthetic bird to see if it could infer the + underlying causal states and thereby categorise the song. This entails + minimising free energy by changing the internal representation of the + control parameters. Each simulated song comprises a series of chirps + whose frequency and number fall progressively from song a to song c, + as a causal state (known as the Raleigh number) is decreased. The + simulations show that the causes are identified after about 600 + milliseconds with high conditional precision (90% confidence intervals + are shown in grey). These simulations illustrate the nature of + perceptual categorisation under generalised predictive coding: Here, + recognition corresponds to mapping from a continuously changing and + chaotic sensory input to a fixed point in perceptual space. + + The various bird songs can be played by right clicking on the sonogram + images, after the routine has completed. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_song_inference.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_song_omission` + +```{text} + Demo for bird songs: In this example, we show that DEM can not only + estimate the hidden states of an autonomous system but can also + deconvolve dynamic changes in its control parameters. We illustrate + this using a slow Lorentz attractor to drive a fast one; both showing + deterministic chaos. We endow the simulations with a little ethological + validity by using the states of the fast Lorentz attractor as control + variables in the syrinx of a song bird (usually these would control a van + der Pol oscillator model). We will look at the true and inferred songs + with and without the last chirps missing. The sonograms displayed + can be played by a mouse click on the image. Subsequent plots show + simulated event-related potential to show that there is a marked + responses (prediction error) of the system when an expected 'syllable' is + omitted. This demonstrates the implicit sequence-decoding of input + streams, using generative models based upon attractors. + Having simulated normal omission-related responses, we then reduce the + precision at the second level (on both hidden causes and states) and + repeat the simulation. The result is an attenuation of the omission- + related response or mismatch negativity. If we try to compensate by + reducing the sensory precision, then the autonomous dynamics predicting + the sequence of chirps supervenes, producing false inference. This + can be thought of as a - crude - model of hallucinosis. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_song_omission.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_song_priors` + +```{text} + Demo for a bird songs: In this example, we simulate local field potential + using the prediction error from the song-bird example below. We look at + these responses under natural stimuli and after removing the second + level of the hierarchy to show it is necessary for veridical perception. + We then repeat but omitting dynamical priors by forsaking generalised + coordinates + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_song_priors.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_demo_texture` + +```{text} + This demonstration considers the figure-ground segregation problem where, + crucially, a figure is defined texturally - in terms of its second order + statistics; in other words, a visual object is manifest in terms of its + texture or spectral power density in the spatial domain. This definition + precludes any first-order attributes; such as increased luminance. This + sort of problem is common in the inverse literature and is usually solved + using a prior on the [co]variance of random fluctuations generating data. + Here, we simulate a contiguous object, whose texture is determined by the + variance of random fluctuations in luminance - and the variance (or + precision) is modulated by Gaussian basis functions. The resulting signal + is mixed with uniform Gaussian noise to produce sensory data. These + (one-dimensional) data are then subject to Bayesian inversion using + generalized predictive coding - (as implemented in spm_LAP) - to recover + the underlying object. + + Technically, this scheme optimizes expectations of the hidden causes of + the data, which are the amplitude of radial basis functions controlling + the precision of retinotopic signals. Heuristically, the figure is + recognized by selectively attending to sensory input from the figure. + This enables sensory noise to be suppressed in unattended parts of the + visual field. However, this form of attention is distinct from simply + boosting sensory precision (the precision of sensory prediction errors) + as in simulations of the Posner paradigm or biased competition. Here, + the hidden causes are optimized in a way that renders them less precise + and therefore more sensitive to ascending (prediction error) sensory + input. This illustrates the functional importance of the relative + precision of sensory and extrasensory prediction errors in modulating + the influence of ascending sensory information that competes to influence + posterior expectations. + + PS: for a 2-D simulation delete 'return' below. + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_demo_texture.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_evidence_accumulation` + +```{text} + Saccadic eye movements under active inference: + __________________________________________________________________________ + This demo illustrates evidence accumulation (and responses) using a very + simple generative model. In this model, there are three hidden states + corresponding to right motion, no motion and left motion - as registered + uniformly over 16 visual channels. Motion is slowly introduced, which + moves the hidden states to one of the unstable fixed points; thereby + inducing proprioceptive predictions that cause a motor response. The + generative model is as minimal as possible and is based on generalised + Lotka-Volterra dynamics to emulate a dynamic form of winner takes all. In + other words, the only prior beliefs of this generative model are that the + world can be in one of a number of (unstable) states. Evidence is + accumulated slowly because the input is noisy (and is assigned a low + precision). This reveals the evidence accumulation dynamics that drive + action, when inference is sufficiently confident. These dynamics are + formally equivalent to the race or drift diffusion dynamics in normative + (descriptive) formulations of evidence accumulation. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_evidence_accumulation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_get_faces` + +```{text} + Utility routine to load images and create basis functions using a + discrete cosine basis set (over a feature dimension). This is written + specifically for the images used in this demonstration and should be + tailored for any new images. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_get_faces.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_morphogenesis` + +```{text} + This routine illustrates self-assembly or more for genesis under active + inference (free energy minimisation). It exploits the fact that one can + express a systems (marginal) Lyapunov function in terms of a variational + free energy. This means that one can prescribe an attracting set in + terms of the generative model that defines variational free energy. In + this example, the attracting set is a point attractor in the phase space + of a multi-celled organism: where the states correspond to the location + and (chemotactic) signal expression of 16 cells. The generative model + and process are remarkably simple; however, the ensuing migration and + differentiation of the 16 cells illustrates self-assembly - in the sense + that each cell starts of in the same location and releasing the same + signals. In essence, the systems dynamics rest upon each cell inferring + its unique identity (in relation to all others) and behaving in accord + with those inferences; in other words, inferring its place in the + assembly and behaving accordingly. Note that in this example there are + no hidden states and everything is expressed in terms of hidden causes + (because the attracting set is a point attractor) Graphics are produced + illustrating the morphogenesis using colour codes to indicate the cell + type - that is interpreted in terms of genetic and epigenetic + processing. + _________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_morphogenesis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_path_integrals` + +```{text} + -------------------------------------------------------------------------- + Illustration of approximations to path integrals. This routine generates + a path from dynamics whose Fokker Planck solution corresponds to a + Gaussian with a given (diagonal) precision. It then samples random + segments (after scaling and smoothing) and evaluates their action. This + evaluation is in terms of the sum of squares residuals between realised + and predicted flow and path dependent and path-independent terms based + upon the surprisal associated with the solution of the Fokker Planck + equation. The point being made here is that the terms based upon the + surprisal (cyan dots) upper bound the action (blue dots). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_path_integrals.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_psychophysics` + +```{text} + FORMAT DCM = DEM_psychophysics + + Demonstration of psychometric curve fitting and model comparison + __________________________________________________________________________ + + This demonstration routine illustrates the fitting of psychometric + functions under different models or hypotheses. The models in question + are specified by various constraints on the model parameters; namely, + changes in bias and sensitivity. The generative model uses a binomial + likelihood function and a logistic function for the predicted + psychometric curves. + + A binomial likelihood model means that (under the assumption of a large + number of trials) following a (variance stabilising) square root + transform, the error variance of the number of correct responses is + unity. If we scale the number of correct responses to reflect the + proportion of correct responses, then the precision of the ensuing + (square root transform) data feature is the total number of responses. + This provides a simple and efficient way to specify the generative model + as a generalised linear model, based upon a standard logistic function, + whose parameters correspond to bias and sensitivity. + + In this example, data are loaded from a CSV file and converted into the + proportion of correct responses, under two levels or conditions of an + experimental factor (baseline and blindspot). The generative model is + equipped with parameters corresponding to changes in bias and + sensitivity. Crucially, these changes have parity; namely, increases and + decreases. This means that there are, potentially, eight models: + corresponding to the presence or absence of an increase or decrease in + bias and sensitivity. In the example below, three of these models are + compared, in terms of their marginal likelihood (as approximated by a + softmax function of the ensuing variational free energy). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_psychophysics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_self_entropy` + +```{text} + -------------------------------------------------------------------------- + Routine to produce graphics illustrating self organisation in terms of + the entropy of blanket states and associated trajectories. A low blanket + entropy induces anomalous diffusion and itinerancy with power law scaling + (i.e., self similar dynamics). This example uses a fixed form (quadratic) + likelihood and optimises the density over over hidden states to minimise + blanket (i.e., self) entropy explicitly. + + In this example, there is just one active and sensory state and one + hidden state to illustrate noise-phase symmetry breaking as the + probability density over action reduces the entropy of sensory states + under a fixed density of hidden or external states. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_self_entropy.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_sharing` + +```{text} + Demo of active (visual) scene-construction + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + inference (with belief propagation) to model active scene construction. + It focuses on a discrete state space representation of a dynamic scene; + generating visual snapshots at about the same frequency of saccadic eye + movements. The generative model starts with latent states that correspond + to natural kinds (e.g., objects) subject to natural laws (e.g., object + invariance, classical mechanics, occlusion, and so on). A second latent + factor (e.g., a 'where' stream) generates the fixation points in visual + space for saccadic eye movements. The factors corresponding to multiple + objects are themselves a Kronecker tensor product of attributes that + depend upon each other; for example, position, velocity, pose, and + non-spatial attributes that depend on spatial attributes. This + interdependence means that object-specific attributes cannot be + factorised; hence their combination as a tensor product (e.g., a 'what' + stream). + + In what follows, we build a generative model, starting from state + transitions that entail natural laws. Position refers to radial + coordinates in egocentric space, implying a distinction between angular + and radial (depth) states - and likewise for motion. This allows us to + incorporate head orientation; in the form of head movements that + reorientate the direction of gaze - that also depends upon the deployment + of saccades in a head-centred frame of reference. Head movements are + implemented, in the generative model, as moving objects in the egocentric + frame of reference. This means that head movement is implemented via + action-dependent transitions in location, while saccades are implemented + via transitions among the latent states representing where gaze is + deployed (in a head-centred frame of reference). + + Equipped with all of these hidden states, one can then complete a + relatively simple generative model by specifying the likelihood mapping + from hidden states to observations. This likelihood mapping is a high + dimensional tensor - encoding all the high order dependencies generating + visual input for the epoch in question. High order here refers to + dependencies such as the interaction between two objects in the same line + of sight that depends upon their relative depth to model occlusions. + + These outcomes are themselves discrete and multimodal. a high acuity + modality models the parvocellular stream, with a restricted (central) + field of view. This is complemented by two other modalities with a more + peripheral field of view reporting contrast and motion energy, that is + not spatially resolved (cf, the magnocellular stream). Note that in this + construction (designed to generate the outputs of a computer vision + scheme) motion is converted into a categorical (present versus absent) + variable over discrete epochs of time. Note that the kind of scene + construction and representation is implemented in egocentric and head + centric frames of reference throughout. There is no part of the + generative model that requires an allocentric representation - and yet, + the agent can skilfully navigate a relatively complicated moving + environment. in the example here, there are two inanimate objects (that + play the role of landmarks) and an inanimate object (namely, a person who + occasionally engages the agent with eye contact). This setup allows the + simulation of reciprocal gaze and a primitive form of dyadic interaction. + In other words, the prior preferences of this agent are to position + itself and its direction of gaze to find someone who is looking at her. + + The code below is briefly annotated to illustrate how to build a + generative model and then simulate active inference under that model, to + produce relatively realistic sampling of a visual scene; namely, active + scene construction. This inversion uses a sophisticated active inference + scheme based upon a recursive estimation of expected free energy. This + finesses the numerics because it uses belief propagation into the future + - as opposed to marginal (variational) message passing. The numerical + complexity of these models is a nontrivial issue: this is because most of + the heavy lifting in the generative model is in the connectivity encoding + dependencies that corresponds to high-dimensional tensors. In these + simulations, the connectivity tensors are represented in working memory; + whereas, in the brain or analogue (neuromorphic) implementations they + would be simpler to instantiate. + _________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_sharing.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_spatial_deconvolution` + +```{text} + FORMAT DEM_spatial_deconvolution + -------------------------------------------------------------------------- + This (toy) demonstration routine illustrates spatiotemporal + deconvolution of regional responses from imaging time-series. The + generative model assumes the data are generated by a small number of + anatomical parcels that are smoothly displaced. The resulting data are + then convolved spatially with a smoothly varying spatial kernel. The smooth + displacement and dispersion are modelled in the usual way using discrete + cosine basis set. The model operates on reduced data features, using + the eigenvariates of the original time-series - this supplements the + implicit deconvolution with eigen-de-noising. The ensuing estimates are + anatomically informed because the generative model stars with a parcellation + scheme. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_spatial_deconvolution.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_surveillance` + +```{text} + Demo of active (visual) scene-construction + __________________________________________________________________________ + + This routine uses a Markov decision process formulation of active + inference (with belief propagation) to model active scene construction. + It focuses on a discrete state space representation of a dynamic scene; + generating visual snapshots at about the same frequency of saccadic eye + movements. The generative model starts with latent states that correspond + to natural kinds (e.g., objects) subject to natural laws (e.g., object + invariance, classical mechanics, occlusion, and so on). A second latent + factor (e.g., a 'where' stream) generates the fixation points in visual + space for saccadic eye movements. The factors corresponding to multiple + objects are themselves a Kronecker tensor product of attributes that + depend upon each other; for example, position, velocity, pose, and + non-spatial attributes that depend on spatial attributes. This + interdependence means that object-specific attributes cannot be + factorised; hence their combination as a tensor product (e.g., a 'what' + stream). + + In what follows, we build a generative model, starting from state + transitions that entail natural laws. Position refers to radial + coordinates in egocentric space, implying a distinction between angular + and radial (depth) states - and likewise for motion. This allows us to + incorporate head orientation; in the form of head movements that + reorientate the direction of gaze - that also depends upon the deployment + of saccades in a head-centred frame of reference. Head movements are + implemented, in the generative model, as moving objects in the egocentric + frame of reference. This means that head movement is implemented via + action-dependent transitions in location, while saccades are implemented + via transitions among the latent states representing where gaze is + deployed (in a head-centred frame of reference). + + Equipped with all of these hidden states, one can then complete a + relatively simple generative model by specifying the likelihood mapping + from hidden states to observations. This likelihood mapping is a high + dimensional tensor - encoding all the high order dependencies generating + visual input for the epoch in question. High order here refers to + dependencies such as the interaction between two objects in the same line + of sight that depends upon their relative depth to model occlusions. + + These outcomes are themselves discrete and multimodal. a high acuity + modality models the parvocellular stream, with a restricted (central) + field of view. This is complemented by two other modalities with a more + peripheral field of view reporting contrast and motion energy, that is + not spatially resolved (cf, the magnocellular stream). Note that in this + construction (designed to generate the outputs of a computer vision + scheme) motion is converted into a categorical (present versus absent) + variable over discrete epochs of time. Note that the kind of scene + construction and representation is implemented in egocentric and head + centric frames of reference throughout. There is no part of the + generative model that requires an allocentric representation - and yet, + the agent can skilfully navigate a relatively complicated moving + environment. in the example here, there are two inanimate objects (that + play the role of landmarks) and an inanimate object (namely, a person who + occasionally engages the agent with eye contact). This setup allows the + simulation of reciprocal gaze and a primitive form of dyadic interaction. + In other words, the prior preferences of this agent are to position + itself and its direction of gaze to find someone who is looking at her. + + The code below is briefly annotated to illustrate how to build a + generative model and then simulate active inference under that model, to + produce relatively realistic sampling of a visual scene; namely, active + scene construction. This inversion uses a sophisticated active inference + scheme based upon a recursive estimation of expected free energy. This + finesses the numerics because it uses belief propagation into the future + - as opposed to marginal (variational) message passing. The numerical + complexity of these models is a nontrivial issue: this is because most of + the heavy lifting in the generative model is in the connectivity encoding + dependencies that corresponds to high-dimensional tensors. In these + simulations, the connectivity tensors are represented in working memory; + whereas, in the brain or analogue (neuromorphic) implementations they + would be simpler to instantiate. + _________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_surveillance.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DEM_vaccination` + +```{text} + FORMAT Tab = DEM_vaccination + + Demonstration of COVID-19 modelling using variational Laplace + __________________________________________________________________________ + + This routine evaluates outcomes under some intervention over a specified + set of dates. The outcomes are then tabulated and displayed in the MATLAB + window. specify the duration and (parametric) nature of the intervention + by editing the code below; namely, the non-pharmacological intervention + structure NPI. + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DEM_vaccination.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DFP_demo_double_well` + +```{text} + DEMO comparing Variational filtering with particle filtering in the + context of a bimodal conditional density. This demonstrates that the + variational filter can not only represent free-form densities on the + states but also the causes of responses. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DFP_demo_double_well.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `DFP_demo_hdm` + +```{text} + demo for Hemodynamic deconvolution usinf variational filtering + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/DFP_demo_hdm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FEP_MB_demo` + +```{text} + This routine illustrates a hierarchical decomposition of Markov blankets + (of Markov blankets). It rests upon the dual operators of finding a + partition (a Markov partition) and then using an adiabatic dimensional + reduction (using the eigensolution of the Markov blanket). In brief, this + means the states of particles at the next level become mixtures of the + Markov blanket of particles at the level below. + + The ensuing hierarchical decomposition is illustrated in terms of + Jacobians and locations in a scaling space (evaluated using the graph + Laplacian). This demonstration uses a fictive Jacobian that is created by + hand - or the equivalent Jacobian of a synthetic soup (i.e., active + matter) + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/FEP_MB_demo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FEP_Manifold` + +```{text} + This demonstration routine simulates the emergence of life - as defined + in terms of active inference - using a synthetic primordial soup. The key + aspect of this dynamics is that there is a separation between dynamical + states and structural states; where the dynamical states of the + microsystem are equipped with a Lorentz attractor and the structural + states correspond to position and velocity. The flow of structural + states conforms to classical Newtonian mechanics. Crucially, the physical + motion of each microsystem is coupled to its internal dynamics and vice + versa; where the coupling among dynamics rests upon short range + (electrochemical) forces. This means that the dependencies among the + dynamics of each microsystem dependent on their positions. This induces a + dependency of the systems structural integrity on its internal dynamics - + which leads to biological self-organisation. This biological self- + organisation is illustrated in terms of the following: + + i) the existence of a Markov blanket that separates internal and external + states, where the internal states are associated with a system that + engages in active or embodied inference. + + ii) emergent inference is demonstrated by showing that the internal + states can predict the extent states, despite their separation by the + Markov blanket. + + iii) this inference (encoded by the internal dynamics) is necessary to + maintain structural integrity, as illustrated by simulated lesion + experiments, in which the influence of various states are quenched. + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/FEP_Manifold.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FEP_fluctuations` + +```{text} + This demonstration uses an ensemble of particles with intrinsic (Lorentz + attractor) dynamics and (Newtonian) short-range coupling. The focus of + this routine is to unpack the Bayesian perspective. We first simulate + dynamics to nonequilibrium steady-state, identify the Markov blanket and + then examine the encoding of external states by internal states; in terms + of their expected values. + + The crucial aspect of this implicit inference (and the basis of the free + energy principle) is the existence of a conditional synchronisation + manifold, when conditioning internal and external states on the Markov + blanket. This provides the basis for a mapping between internal and + external states that can be interpreted in terms of a probabilistic + representation or inference. + + This Bayesian perspective is illustrated in terms of a mapping between + the canonical modes of internal and external states (as approximated + with a polynomial expansion). The canonical modes her are evaluated + using an estimate of the conditional expectations based upon the + Euclidean proximity of Markov blanket states. The ensuing posterior over + external states is than illustrated, in relation to the actual external + states. We also simulate event related potentials by identifying + several points in time when the Markov blankets revisit the same + neighbourhood. Finally, to illustrate the underlying dynamics, the + Jacobians or coupling among internal and external states are + presented; using different orders of coupling (i.e., degrees of + separation) + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/FEP_fluctuations.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FEP_information_length` + +```{text} + Demonstration of density dynamics and information length + FORMAT FEP_information_length(gi,qi,ci,fi) + -------------------------------------------------------------------------- + gi - scaling of (isotropic) random fluctuations; i.e., dissipative flow + qi - scaling of solenoidal flow; i.e., conservative flow + ci - colour index for plotting + fi - optional flag to print functional forms + ti - optional flag to reverse time halfway through the simulation + __________________________________________________________________________ + This demonstration routine illustrates the key role of solenoidal flow + (that breaks detailed balance) in optimisation and self-organisation. The + first section shows that increasing solenoid flow leads to mixing that + accelerates the convergence of a random dynamical system to its + (nonequilibrium) steady-state or free energy minimum. Heuristically, + solenoidal flow—on the level set of on objective function (here the log + density of the said steady state)—can be regarded as searching for + ‘points of entry’ in state space with 'steep' gradients. The key + observation here is that the rate of convergence, scored with the + divergence between the current and final density, increases with the + relative amount of solenoidal mixing. This is accompanied by an increase + in the information length from any initial density to the density in the + long-term future. + + The second section rehearses the same mechanics but in the context of + self-organisation. To talk about self organisation it is necessary to + separate the self from nonself by constructing a random dynamical system + with a Markov blanket. One can then associate the conditional density + over external states, conditioned on blanket states, with a Bayesian + belief encoded by internal states. This corresponds to the variational + density that underwrites the free energy principle (under some + simplifying assumptions). The marginal density over particular (i.e., + internal states and their blanket) states now plays the role of a + description of the dynamics of a particle, that shows the same + dependencies on solenoidal flow above. Namely, increasing solenoidal flow + decreases the path integral of divergence or the rate of convergence to + nonequilibrium steady-state. At the same time, the information length of + paths into the future increases. The accompanying information theoretic + measures—of the conditional density over external states and particular + states—can be read as unfolding in extrinsic and intrinsic information + geometries, respectively. These conjugate geometries can, in turn, be + associated with variational free energy and thermodynamic free energy. + + An increase in solenoidal flow, relative to dissipative flow, goes + hand-in-hand with the size of a particle, where random fluctuations are + averaged away. In other words, large particles are necessarily precise + particles that feature solenoidal flows. These flows underwrite a rapid + convergence to nonequilibrium steady-state from any initial conditions + that, necessarily, entail large information lengths. In short, large, + precise particles have an itinerant aspect to their dynamics and move + through many discernible probabilistic configurations from any initial + density. This itinerancy lends precise particles an elemental kind of + memory, in the sense that running the system backwards in time evinces a + greater number of discernible belief states. This number corresponds to + the information length, while the rate at which discernible belief states + emerge corresponds to the information rate. + + Note that we can run the system forwards and backwards in time with + impunity because the density dynamics are deterministic (as opposed to + any stochastic path). This behaviour can be demonstrated by calling the + current routine with an additional argument that reverses the direction + of time halfway through a simulation. + + Please see the annotated code below for further details. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/FEP_information_length.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FEP_lorenz_surprise` + +```{text} + __________________________________________________________________________ + This demo provides an elementary characterisation of stochastic chaos + using the Lorenz system. Effectively, it uses iterated least-squares to + solve the Helmholtz decomposition of nonequilibrium steady-state flow + (i.e., the solution to the Fokker Planck equation) using the Lorentz + system as an example. This furnishes a generative model for stochastic + chaos in terms of the underlying potential (log nonequilibrium + steady-state density) and flow operator, with symmetric and antisymmetric + (skew symmetric) components. The latter (solenoidal) part of the flow + operator breaks detailed balance and renders the solution a + nonequilibrium steady-state (NESS) density. + + In virtue of using a polynomial expansion for the nonequilibrium + potential (i.e., surprisal or self information) one can approximate the + expected flow with a second order polynomial. This can be regarded as a + Laplace approximation to the nonequilibrium steady-state density. Further + constraints can be used to specify the stochastic chaos as (state + dependent) solenoidal flow around a multivariate Gaussian, which might be + a reasonable approximation in the setting of random fluctuations. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/FEP_lorenz_surprise.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FEP_physics` + +```{text} + This demonstration uses an ensemble of particles with intrinsic (Lorenz + attractor) dynamics and (Newtonian) short-range coupling. the setup is + used to solve for dynamics among an ensemble of particles; from which a + Markov blanket emerges (which forms a particle at the next hierarchical + scale. These ensemble dynamics are then used to illustrate different + perspectives; namely, those afforded by quantum, statistical and + classical mechanics. A detailed description of each of these three + treatments precedes each of the sections in the script. these + descriptions are in the form of a figure legend, where each section is + summarised with a figure. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/FEP_physics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FEP_self_entropy` + +```{text} + This demonstration uses an ensemble of particles with intrinsic (Lorentz + attractor) dynamics and (Newtonian) short-range coupling. This routine + illustrates self organisation in terms of the entropy of blanket states + (and concomitant changes in terms of mutual information (i.e., complexity + cost or risk). Here, the ensemble average of these entropy measures is + taken over all (128) particles of macromolecules; where the Markov + blanket of each particle comprises all but the third (electrochemical) + hidden state. The graphics produced by this routine simply plot the + decrease in blanket entropy (and complexity cost) as the system + approaches its random dynamical attractor. Illustrative trajectories of + the particles are provided at three points during the (stochastic) + chaotic transient. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/FEP_self_entropy.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FieldMap` + +```{text} + FieldMap is an SPM Toolbox for creating field maps and unwarping EPI. + A full description of the toolbox and a usage manual can be found in + FieldMap.md. This can launched by the toolbox help button or using + `spm_help FieldMap.md`. The theoretical and practical principles behind + the toolbox are described in FieldMap_principles.md. + + FORMAT FieldMap + + FieldMap launches the GUI-based toolbox. Help is available via the help + button (which calls spm_help FieldMap.md). FieldMap is a multi function + function so that the toolbox routines can also be accessed without using + the GUI. A description of how to do this can be found in FieldMap_ngui.m + + Input parameters and the mode in which the toolbox works can be + customised using the defaults file called pm_defaults.m. + + Main data structure: + + IP.P : 4x1 cell array containing real part short TE, + imaginary part short TE, real part long TE and + imaginary part long TE. + IP.pP : Cell containing pre-calculated phase map. N.B. + IP.P and IP.pP are mutually exclusive. + IP.epiP : Cell containing EPI image used to demonstrate + effects of unwarping. + IP.fmagP : Cell containing fieldmap magnitude image used for + coregistration + IP.wfmagP : Cell containing forward warped fieldmap magnitude + image used for coregistration + IP.uepiP : Cell containing unwarped EPI image. + IP.nwarp : Cell containing non-distorted image. + IP.vdmP : Cell containing the voxel displacement map (VDM) + IP.et : 2x1 Cell array with short and long echo-time (ms). + IP.epifm : Flag indicating EPI based field map (1) or not (0). + IP.blipdir : Direction of phase-encode blips for k-space traversal + (1 = positive or -1 = negative) + IP.ajm : Flag indicating if Jacobian modulation should be applied + (1) or not (0). + IP.tert : Total epi readout time (ms). + IP.maskbrain : Flag indicating whether to mask the brain for fieldmap creation + IP.uflags : Struct containing parameters guiding the unwrapping. + Further explanations of these parameters are in + FieldMap.md and pm_make_fieldmap.m + .iformat : 'RI' or 'PM' + .method : 'Huttonish', 'Mark3D' or 'Mark2D' + .fwhm : FWHM (mm) of Gaussian filter for field map smoothing + .pad : Size (in-plane voxels) of padding kernel. + .etd : Echo time difference (ms). + .bmask + + IP.mflags : Struct containing parameters for brain maskin + .template : Name of template for segmentation. + .fwhm : fwhm of smoothing kernel for generating mask. + .nerode : number of erosions + .ndilate : number of dilations + .thresh : threshold for smoothed mask. + .reg : bias field regularisation + .graphics : display or not + + IP.fm : Struct containing field map information + IP.fm.upm : Phase-unwrapped field map (Hz). + IP.fm.mask : Binary mask excluding the noise in the phase map. + IP.fm.opm : "Raw" field map (Hz) (not unwrapped). + IP.fm.fpm : Phase-unwrapped, regularised field map (Hz). + IP.fm.jac : Partial derivative of field map in y-direction. + + IP.vdm : Struct with voxel displacement map information + IP.vdm.vdm : Voxel displacement map (scaled version of IP.fm.fpm). + IP.vdm.jac : Jacobian-1 of forward transform. + IP.vdm.ivdm : Inverse transform of voxel displacement + (used to unwarp EPI image if field map is EPI based) + (used to warp flash image prior to coregistration + when field map is flash based (or other T2 weighting). + IP.vdm.ijac : Jacobian-1 of inverse transform. + IP.jim : Jacobian sampled in space of EPI. + + IP.cflags : Struct containing flags for coregistration + (these are the default SPM coregistration flags - + defaults.coreg). + .cost_fun + .sep + .tol + .fwhm + + __________________________________________________________________________ + Refs and Background reading: + + Jezzard P & Balaban RS. 1995. Correction for geometric distortion in + echo planar images from Bo field variations. MRM 34:65-73. + + Hutton C et al. 2002. Image Distortion Correction in fMRI: A Quantitative + Evaluation, NeuroImage 16:217-240. + + Cusack R & Papadakis N. 2002. New robust 3-D phase unwrapping + algorithms: Application to magnetic field mapping and + undistorting echoplanar images. NeuroImage 16:754-764. + + Jenkinson M. 2003. Fast, automated, N-dimensional phase- + unwrapping algorithm. MRM 49:193-197. + __________________________________________________________________________ + Acknowledegments: + + Wellcome Trust and IBIM Consortium + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/FieldMap.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FieldMap_Run` + +```{text} + Auxillary file for running FieldMap jobs + FORMAT vdm = FieldMap_Run(job) + + job - FieldMap job structure containing various elements: + Common to all jobs: + defaults - cell array containing name string of the defaults file + options - structure containing the following: + epi - cell array containing name string of epi image to unwarp + matchvdm - match vdm to epi or not (1/0) + writeunwarped - write unwarped EPI or not (1/0) + anat - cell array containing name string of anatomical image + matchanat - match anatomical image to EPI or not (1/0) + + Elements specific to job type: + precalcfieldmap - name of precalculated fieldmap + + phase - name of phase image for presubtracted phase/mag job + magnitude - name of magnitude image for presubtracted phase/mag job + + shortphase - name of short phase image for phase/mag pair job + longphase - name of short phase image for phase/mag pair job + shortmag - name of short magnitude image for phase/mag pair job + longmag - name of short magnitude image for phase/mag pair job + + shortreal - name of short real image for real/imaginary job + longreal - name of long real image for real/imaginary job + shortimag - name of short imaginary image for real/imaginary job + longimag - name of long imaginary image for real/imaginary job + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/FieldMap_Run.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FieldMap_applyvdm` + +```{text} + Apply VDM and reslice images + FORMAT FieldMap_applyvdm(job) + job.data(sessnum).scans - images for session/run sessnum + job.data(sessnum).vdmfile - VDM file for session/run sessnum + job.roptions.rinterp - interpolation method + job.roptions.wrap - perform warp around in specified dimensions + job.roptions.mask - perform masking + job.roptions.which(1) - reslice images in time series only + job.roptions.which(2) - reslice images in time series and mean + job.roptions.prefix - prefix for vdm applied files + job.roptions.pedir - phase encode direction (i.e. aplly vdm file along + this dimension + __________________________________________________________________________ + + A VDM (voxel displacement map) created using the FieldMap toolbox + can be used to resample and reslice realigned images to the original + subdirectory with the same (prefixed) filename. + + Voxels in the images will be shifted according to the values in the VDM + file along the direction specified by job.roptions.pedir (i.e. this is + usually the phase encode direction) and resliced to the space of the + first image in the time series. + + Inputs: + A job structure containing fields for the input data and the processing + options. The input data contains the series of images conforming to + SPM data format (see 'Data Format'), the relative displacement of the images + is stored in their header and a VDM which has (probably) been created + using the FieldMap toolbox and matched to the first image in the time + series (this can also be done via the FieldMap toolbox). + + Outputs: + The resampled and resliced images resliced to the same subdirectory with a prefix. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/FieldMap_applyvdm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FieldMap_create` + +```{text} + Function to create VDM file from fieldmap images and can be called + using FieldMap_preprocess.m + + This function uses routines from the FieldMap toolbox to: + 1) Create a single field map from input fieldmap data. + 2) Convert fieldmap to a voxel displacement map (vdm_* file). + 3) Match vdm_* to input EPI(s) which should be the first image + that each session will be realigned/unwarped to. Writes out matched vdm + file with name extension 'session' or a user-specified name. + 4) Each selected EPI is unwarped and written out with the prefix 'u'. + + For details about the FieldMap toolbox, see FieldMap.md. For a + description of the components of the structure IP, see FieldMap.m. + For an introduction to the theoretcial and practical principles behind + the toolbox, see FieldMap_principles.md. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/FieldMap_create.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `FieldMap_preprocess` + +```{text} + Function to prepare fieldmap data for processing + + FORMAT VDM = FieldMap_preprocess(fm_dir,epi_dir,pm_defs,sessname) + fm_dir - name of directory containing fieldmap images + epi_dir - name of directory containing epi images (needs first epi in time + series to match the fieldmap to). + This can also be a cell array of directory names for creating + session-specific versions of a vdm file where each vdm file + is matched to the first image of each EPI directory specified. + Each session specific vdm file will be saved with the name + vdm5_XXXX_'sessname'N.img where 'sessname is 'session' by + default or another name if specified by the user as the fourth + argument to the script. + pm_defs - vector containing following values (optional flags in brackets): + [te1,te2,epifm,tert,kdir,(mask),(match),(write)]; + + te1 - short echo time + te2 - long echo time + epifm - epi-based fieldmap (1/0)? + tert - total echo readout time + kdir - blip direction (+1/-1) + mask - (optional flag, default=1) Do brain masking or not + (only if non-epi fieldmap) + match - (optional flag, default=1) Match fieldmap to epi or not + + writeunwarped + - (optional flag, default=1) Write unwarped epi or not + + sessname - (optional string, default='session') This will be the name + extension followed by an incremented integer for session specific vdm files. + + VDM - cell array of file pointers to the VDM file(s) (voxel displacement map) + required for the Unwarping process. This will be written to the + same directory as the fieldmap data. + + NB: + 1) This function takes input directory names and parameters and puts them + into the correct format for creating fieldmaps + 2) The function assumes that only the fieldmap images are in the + fieldmap directory + + Below is a list of the most common sequences and parameter lists + used at the FIL: + + Sonata Siemens fieldmap parameters and default EPI fMRI'); + VDM=FieldMap_preprocess(fm_dir,epi_dir,[10.0,14.76,0,32,-1]); + + Allegra Siemens fieldmap parameters and default EPI fMRI + VDM=FieldMap_preprocess(fm_dir,epi_dir,[10.0,12.46,0,21.12,-1]); + + Allegra Siemens fieldmap parameters and extended FOV EPI fMRI + VDM=FieldMap_preprocess(fm_dir,epi_dir,[10.0,12.46,0,23.76,-1]); + + Allegra Siemens fieldmap parameters and 128 EPI fMRI + VDM=FieldMap_preprocess(fm_dir,epi_dir,[10.0,12.46,0,71.68,-1]); + + It is also possible to switch off the brain masking which is + done by default with a siemens field map (set 6th flag to 0) + and the matching of the fieldmap to the EPI (set 7th flag to 0). + + This function generates session specific versions of the vdm file that + have been matched to the first image of each session. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/FieldMap_preprocess.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `KLDemo` + +```{text} + Illustration of information gains with Bayesian fusion + FORMAT KLDemo) + + -------------------------------------------------------------------------- + This routine illustrates the benefit of multimodal or Bayesian fusion in + terms of conditional dependencies among parameters. In other words, it + shows that even if one data modality contains no information about a + particular set of parameters, it can help resolve uncertainty about + another set and thereby disclose information contained in the other + modality. This is illustrated here using a simple linear model with + neuronal and haemodynamic parameters to show that EEG can provide some + information gain, in relation to haemodynamic parameters. + + comment the orthogonalisation of the fMRI design matrix below to see the + effect of conditional dependencies on the haemodynamic information gain + afforded by EEG data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/KLDemo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `MDP_DEM_Mixed_Models_Movement` + +```{text} + This demo illustrates a series of computational pathologies as elicited + during a synthetic neurological examination. This focuses upon an + examination of the biceps reflex, and a simple coordination task. Each of + these are simulated for an arm that may move in three dimensions through + internal and external rotation of the shoulder, flexion and extension of + the shoulder, and flexion and extension of the elbow. These dynamics play + out through an active Bayesian filtering scheme, where a series of + attracting points draw the hand to different locations in 3D space. The + selection of these attracting points involves a hierarhical Markov + Decision Process, which identifies these sequences based upon the prior + belief that (1) the sequence will minimise expected free energy and (2) + the sequence is consistent with the trajectory predicted by the highest + (contextual) level of the model. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/MDP_DEM_Mixed_Models_Movement.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `MDP_DEM_Oculomotion_Pharma_demo` + +```{text} + Demo of mixed models for oculmotor behaviour, with pharmacological + manipulations + + __________________________________________________________________________ + + This demo ilustrates the use of mixed (continuous and discrete) + generative models in simulating oculomotion. An MDP model is used to + select locations in visual space, and a continuous model is used to + implement these decisions. See also DEM_demo_MDP_DEM.m, + MDP_DEM_Oculomotion_demo.m + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/MDP_DEM_Oculomotion_Pharma_demo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `MDP_DEM_Oculomotion_demo` + +```{text} + Demo of mixed models for oculmotor behaviour + + __________________________________________________________________________ + + This demo ilustrates the use of mixed (continuous and discrete) + generative models in simulating oculomotion. An MDP model is used to + select locations in visual space, and a continuous model is used to + implement these decisions. See also DEM_demo_MDP_DEM.m. + For a version of this routine with simulated pharmacological + interventions (and a delay-period task) please see: + MDP_DEM_Oculomotion_Pharma_demo.m + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/MDP_DEM_Oculomotion_demo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `MDP_Heart_Beat` + +```{text} + This simulation uses a Markov Decision process formulation of active + inference to demonstrate the interaction between interoceptive and + exteroceptive perception. This relies upon the fact that the function of + exteroceptive sense organs depends upon oscillatory cycles in + interoceptive states. The example used here is the change in retinal + blood flow, and its influence on vision, during a cardiac cycle. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/MDP_Heart_Beat.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `Markov_blankets_and_NESS` + +```{text} + Meta-modelling of Bayes-optimal responses (Newton's method) + FORMAT Markov_blankets_and_NESS + + This demonstration routine deals with the conditional independence in + this induced by sparse coupling in a random dynamical systems, where the + sparse coupling is characterised in terms of the system's Jacobian. At + nonequilibrium steady-state, this places linear constraints on the + solenoidal flow (denoted by Q) under a Helmholtz decomposition. The + resulting curvature of the log density and at nonequilibrium steady-state + encodes conditional independencies; i.e., when the Hessian is zero. What + follows are a series of notes illustrating the conditions under which + conditional independence between internal and external states under a + Markov blanket partition emerges, either asymptotically as the system + becomes more dissipative - or under a particular constraints on the + Jacobian. When invoked symbolic maths is used to illustrate an analytic + solution for a simple the canonical Markov blanket, using a single + dimensional state for each subset of a Markovian position. Numerical + analyses are then used to illustrate how this generalises to high + dimensional systems. Subsequent notes drill down on particular instances + in the literature. + + __________________________________________________________________________ + Copyright (C) 2020 Wellcome Centre for Human Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/Markov_blankets_and_NESS.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `Neural_demo` + +```{text} + NEURAL_DEMO M-file for Neural_demo.fig + NEURAL_DEMO, by itself, creates a new NEURAL_DEMO or raises the existing + singleton*. + + H = NEURAL_DEMO returns the handle to a new NEURAL_DEMO or the handle to + the existing singleton*. + + NEURAL_DEMO('CALLBACK',hObject,eventData,handles,...) calls the local + function named CALLBACK in NEURAL_DEMO.M with the given input arguments. + + NEURAL_DEMO('Property','Value',...) creates a new NEURAL_DEMO or raises the + existing singleton*. Starting from the left, property value pairs are + applied to the GUI before Neural_demo_OpeningFunction gets called. An + unrecognized property name or invalid value makes property application + stop. All inputs are passed to Neural_demo_OpeningFcn via varargin. + + *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one + instance to run (singleton)". + + See also: GUIDE, GUIDATA, GUIHANDLES + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Neural_Models/Neural_demo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ROBOT_DCM_EEG` + +```{text} + test routine to check current implementations of DCM (electrophysiology) + ========================================================================== + options.analysis - 'ERP','CSD', 'IND' or 'TFM + options.model - 'ERP','SEP','LFP','CMC','CMM','NMM' or 'MFM' + options.spatial - 'ECD','LFP' or 'IMG' + + + [Matlab code]( https://github.com/spm/spm/blob/main/tests/ROBOT_DCM_EEG.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ROBOT_DCM_fMRI` + +```{text} + test routine to check current implementations of DCM for fMRI + ========================================================================== + + Options + -------------------------------------------------------------------------- + DCM.options.two_state % two regional populations (E and I) + DCM.options.stochastic % fluctuations on hidden states + DCM.options.nonlinear % interactions among hidden states + DCM.options.nograph % graphical display + DCM.options.centre % mean-centre inputs + DCM.options.P % starting estimates for parameters + DCM.options.hidden % indices of hidden regions + + + [Matlab code]( https://github.com/spm/spm/blob/main/tests/ROBOT_DCM_fMRI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ROBOT_DEM` + +```{text} + Tests routines in DEM GUI + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/tests/ROBOT_DEM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ROBOT_NMM` + +```{text} + Tests routines in neural mass model (NMM) GUI + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Neural_Models/ROBOT_NMM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `addCTFtrial` + +```{text} + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + % + This program creates datasets that can be analyzed by CTF software. % + % + Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. % + % + Please do not redistribute it without permission from VSM MedTech Ltd. % + % + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/ctf/addCTFtrial.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `appendstruct` + +```{text} + APPENDSTRUCT appends a structure or a struct-array to another structure or + struct-array. It also works if the initial structure is an empty structure or an + empty double array. It also works if the input structures have different fields. + + Use as + ab = appendstruct(a, b) + + See also PRINTSTRUCT, MERGESTRUCT, COPYFIELDS, KEEPFIELDS, REMOVEFIELDS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/appendstruct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bemcp_example` + +```{text} + Simple function to test/demonstrate how the Boundary element functions are + used in combination with Fildtrip/Forwinv routines. + + 1. A model is created as 3 concentric meshed spheres (using FT's + icosahedron routines), + 2. then random electrodes are placed on the upper part of the outer + sphere. + 3. the model is then "prepared" with 'ft_prepare_bemmodel', this bits + takes most time as it requires LOTS of calculation. + 4. sensors and volumes are plugged together by 'forwinv_prepare_vol_sens' + 5. Finally the leadfiled for 3 orthogonal sources placed at one location + is calculated with 'forwinv_compute_leadfield.m' + 6. Display the 3 leadfields + + NOTE: + this bit of code needs access to low level fieldtrip/forwinv routines + which have been copy/pasted here under. + Be aware that this way of programming is generally NOT advisable! + I used it only to ensure a quick & dirty check of the BEM module... + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/bemcp/bemcp_example.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `besa2fieldtrip` + +```{text} + BESA2FIELDTRIP reads and converts various BESA datafiles into a FieldTrip + data structure, which subsequently can be used for statistical analysis + or other analysis methods implemented in Fieldtrip. + + Use as + [output] = besa2fieldtrip(input) + where the input should be a string specifying the BESA file, or a MATLAB structure + with data that was exported by BESA. The output is a MATLAB structure that is + compatible with FieldTrip. + + The format of the output structure depends on the type of datafile: + *.avr is converted to a structure similar to the output of FT_TIMELOCKANALYSIS + *.mul is converted to a structure similar to the output of FT_TIMELOCKANALYSIS + *.swf is converted to a structure similar to the output of FT_TIMELOCKANALYSIS (*) + *.tfc is converted to a structure similar to the output of FT_FREQANALYSIS (*) + *.dat is converted to a structure similar to the output of FT_SOURCANALYSIS + *.dat combined with a *.gen or *.generic is converted to a structure similar to the output of FT_PREPROCESSING + + (*) If the BESA toolbox by Karsten Hochstatter is found on your MATLAB path, the + readBESAxxx functions will be used (where xxx=tfc/swf), alternatively the private + functions from FieldTrip will be used. + + See also EEGLAB2FIELDTRIP, SPM2FIELDTRIP + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/besa2fieldtrip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_copy` + +```{text} + Set up a new analysis by copying an existing one + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_copy.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_data` + +```{text} + Prepare the data and initialise the beamforming pipeline + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features` + +```{text} + Prepare data features for filter computation + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_contcov` + +```{text} + Robust covariance for continuous data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_contcov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_cov` + +```{text} + Simple band limited covariance computation + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_cov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_cov_bysamples` + +```{text} + Simple covariance computation to handle variable width WOIs, + Requires S.samples as a [1 x samples x ntrials] matrix of logical indices + indicating which data points should be used in the cov estimation + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_cov_bysamples.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_csd` + +```{text} + Compute cross-spectral density matrix for DICS + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_csd.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_identity` + +```{text} + Identity matrix for cases when covariance is not necessary + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_identity.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_regmulticov` + +```{text} + Simple covariance computation with regularization + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_regmulticov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_tdcov` + +```{text} + Simple band limited covariance computation with temporal decomposition + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_tdcov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_features_vbfa` + +```{text} + Variational Bayes Factor Analysis for computing noise covariance + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_features_vbfa.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_group` + +```{text} + A module for applying a processing step to a group of subjects + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_group.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_group_GALA` + +```{text} + Computes Minimum Norm projectors + + Please cite: + Hauk O, Stenroos M. + A framework for the design of flexible cross-talk functions for spatial + filtering of EEG/MEG data: DeFleCT. + Human Brain Mapping 2013 + http://imaging.mrc-cbu.cam.ac.uk/meg/AnalyzingData/DeFleCT_SpatialFiltering_Tools + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_group_GALA.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_group_batch` + +```{text} + Run a DAiSS batch on a group of subjects + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_group_batch.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_group_functionalROI` + +```{text} + Computes Minimum Norm projectors + + Please cite: + Hauk O, Stenroos M. + A framework for the design of flexible cross-talk functions for spatial + filtering of EEG/MEG data: DeFleCT. + Human Brain Mapping 2013 + http://imaging.mrc-cbu.cam.ac.uk/meg/AnalyzingData/DeFleCT_SpatialFiltering_Tools + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_group_functionalROI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse` + +```{text} + Compute inverse projectors + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_champagne` + +```{text} + Computes Champagne filters + + See Owen et al. Performance evaluation of the Champagne source + reconstruction algorithm on simulated and real M/EEG data. Neuroimage. + 2012 Mar;60(1):305-23 + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_champagne.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_deflect` + +```{text} + Used DeFleCT framework to compute spatial filters + + Please cite: + Hauk O, Stenroos M. + A framework for the design of flexible cross-talk functions for spatial + filtering of EEG/MEG data: DeFleCT. + Human Brain Mapping 2013 + http://imaging.mrc-cbu.cam.ac.uk/meg/AnalyzingData/DeFleCT_SpatialFiltering_Tools + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_deflect.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_dics` + +```{text} + Computes DICS filters + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_dics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_ebb` + +```{text} + Computes Empirical Bayes Beamformer filters + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_ebb.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_eloreta` + +```{text} + Computes eLORETA projectors + + please cite + R.D. Pascual-Marqui: Discrete, 3D distributed, linear imaging methods of electric neuronal activity. Part 1: exact, zero + error localization. arXiv:0710.3341 [math-ph], 2007-October-17, http://arxiv.org/pdf/0710.3341 + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_eloreta.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_lcmv` + +```{text} + Computes LCMV filters + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_lcmv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_lcmv_multicov` + +```{text} + Computes LCMV filters using spm_pca_order to constrain inverse of data + cov matrix. + + Based on the paper: + MEG beamforming using Bayesian PCA for adaptive data covariance matrix regularization. + Woolrich M, Hunt L, Groves A, Barnes G. + Neuroimage. 2011 Aug 15;57(4) + + and allowing for multiple covariance matrices, e.g. associated with + multiple states: + Dynamic State Allocation for MEG Source Reconstruction + Neuroimage. Woolrich et al. 2013. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_lcmv_multicov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_minimumnorm` + +```{text} + Computes Minimum Norm projectors + + Please cite: + Hauk O, Stenroos M. + A framework for the design of flexible cross-talk functions for spatial + filtering of EEG/MEG data: DeFleCT. + Human Brain Mapping 2013 + http://imaging.mrc-cbu.cam.ac.uk/meg/AnalyzingData/DeFleCT_SpatialFiltering_Tools + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_minimumnorm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_inverse_nutmeg` + +```{text} + Interface to NUTMEG inverse methods + http://www.nitrc.org/plugins/mwiki/index.php/nutmeg:MainPage + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_inverse_nutmeg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_isfield` + +```{text} + Efficiently identify if a field is contained within a BF file + FORMAT bool = bf_isfield(BF,field) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_isfield.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_load` + +```{text} + Load BF data into memory with just the requested fields + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_load.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output` + +```{text} + Perform postprocessing based on beamforming projectors + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_PLI` + +```{text} + Generate a montage for source extraction, projects the sources one by + one and computes phase lag index on the fly, which is written out with no + need to call bf_write. Only one VOI allowed, which can be a sphere or a + mask image. + + PLI computation using code published by Gerald Cooray (2010) Karolinska + Institutet: EFFECT OF DIABETES MELLITUS ON HUMAN BRAIN FUNCTION + (https://openarchive.ki.se/xmlui/bitstream/handle/10616/40241/ram_ber%C3%A4ttelse.pdf?sequence=1) + with a method based on Stam CJ, Nolte G, Daffertshofer A (Hum Brain Mapp 2007) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_PLI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_cfGLM` + +```{text} + Compute phase-amplitude coupling using a general linear model + currently takes both low frequency phase and amplitude as regressors + needs epoched data - uses epochs for statistics + writes out images for summary phase-amplitude coupling and + amplitude-amplitude coupling, as well as B coefficients per trial + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_cfGLM.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_dics` + +```{text} + Computes DICS image + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_dics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_filtcorr` + +```{text} + Computes filter correlation images + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_filtcorr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_gain` + +```{text} + Compute gain image + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_gain.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_kurtosis` + +```{text} + Compute kurtosis image + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_kurtosis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_mv` + +```{text} + Compute multivariate test on a number of frequency bands + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_mv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_pac` + +```{text} + Computes phase-amplitude coupling + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_pac.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_powcorr` + +```{text} + Compute phase-amplitude coupling + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_powcorr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_power` + +```{text} + Computes power image + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_power.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_image_sensitivity` + +```{text} + Sensitivity profile for a group of sensors + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_image_sensitivity.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_montage` + +```{text} + Generate a montage for source extraction + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_montage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_output_sourcedata_robust` + +```{text} + Extract source data, handling bad data segments + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_output_sourcedata_robust.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_regularise_clifftrunc` + +```{text} + Regularisation based on the sudden drop-off in the covariance Eigenspectrum + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_regularise_clifftrunc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_regularise_mantrunc` + +```{text} + User-specified dimensional reduction + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_regularise_mantrunc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_regularise_manual` + +```{text} + Manual specification of the regularisation parameter + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_regularise_manual.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_regularise_minkatrunc` + +```{text} + Bayesian regularisation based on Minka's method + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_regularise_minkatrunc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_regularise_roi` + +```{text} + ROI regularisation + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_regularise_roi.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_regularise_tichonov_rankdef` + +```{text} + Tichonov regularisation for rank deficient matrices based on the function + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_regularise_tichonov_rankdef.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_save` + +```{text} + Save BF data in a MAT file + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_save.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_save_path` + +```{text} + Saves BF data in a MAT file + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_save_path.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_sources` + +```{text} + Prepare source locations and lead fields for beamforming + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_sources.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_sources_grid` + +```{text} + Generate beamforming grid + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_sources_grid.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_sources_grid_phantom` + +```{text} + Generate beamforming grid + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_sources_grid_phantom.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_sources_mesh` + +```{text} + Generate cortical mesh + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_sources_mesh.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_sources_mni_coords` + +```{text} + Generate beamforming grid + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_sources_mni_coords.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_sources_scalp` + +```{text} + Generate source space on the scalp surface, as a part of measuring a + magnetomyogram (MMG) of the face. + + See https://doi.org/10.1111/psyp.13507 for more information. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_sources_scalp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_sources_voi` + +```{text} + Generate a set of VOIs specified in MNI coordinates + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_sources_voi.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_stat_evoked_t` + +```{text} + Compute t-stat accross trials for evoked response + FORMAT BF = bf_stat_evoked_t(S) + S - input structure + fields of S: + S.BF - path to BF.mat file + S.act - active timpeoint(ms) - 1 x 1 matrix -Default: none + S.base - base timpeoint(ms) - 1 x 1 matrix -Default: none + S.condact - active condition label - string -Default: 'ALL' + S.condbase - baseline condition label - string -Default: 'ALL' + S.MNI - flag to output in MNI space - logical -Default: true + S.summary - output summary statistic - logical -Default: false + Output: + BF - path to BF.mat file + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_stat_evoked_t.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_std_fields` + +```{text} + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_std_fields.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_view` + +```{text} + Display the results of beamforming analysis + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_view.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_view_glass` + +```{text} + Diplays glass brain plot of DAISS output results + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_view_glass.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_view_surface` + +```{text} + Diplay surface plot of DAISS output results + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_view_surface.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_data` + +```{text} + A handy command-line based batch filler with some defaults for DAiSS + data module, pick a few options and default for unpopulated fields. It + will by default run the batch for the user. + + FORMAT [BF, batch, data] = bf_wizard_data(S) + S - input structure + Optional fields of S: + S.D - SPM MEEG object - Default: REQUIRED + S.dir - path to save DAiSS BF.mat - Default: same as S.D + S.val - which D.inv to use - Default: 1 + S.gradsource - where to pool sensor information from + (inv | sens) + - Default: 'inv' + S.space - which space to do calculations in + (MNI-Aligned | Head | Native) + - Default: MNI-Aligned + S.overwite - Overwrite existing BF.mat - Default: 1 + S.run - Run the batch, set to 0 to + bypass the run for debugging + - Default: 1 + S.batch - matlabbatch, of which this job + can be appended to + - Default: [] + + Output: + BF - Resultant DAiSS BF structure + batch - matlabbatch job for spm_jobman to run + data - simplified summary of options selected + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_features` + +```{text} + A handy command-line based batch filler with some defaults for DAiSS + features module, pick a few options, and it will default for unpopulated + fields + + FORMAT [BF, batch, features] = bf_wizard_data(S) + S - input structure + + Output: + BF - Resultant DAiSS BF structure + batch - matlabbatch job for spm_jobman to run + features - simplified summary of options selected + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_features.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_headmodel` + +```{text} + A handy command-line based batch filler with some defaults for SPM + head model specification for MEEG data. Will generate the job which + performs coregistration between the data and the MRI + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_headmodel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_inverse` + +```{text} + A handy command-line based batch filler with some defaults for DAiSS + invert module, pick a few options, and it will default for unpopulated + fields + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_inverse.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_output` + +```{text} + A handy command-line based batch filler with some defaults for DAiSS + output module, pick a few options, and it will default for unpopulated + fields + + Current *definitely* supported output methods include: + - image_dics + - image_mv + - image_power + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_output.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_sources` + +```{text} + A handy command-line based batch filler with some defaults for DAiSS + source module, pick a few options, and it will default for unpopulated + fields + + FORMAT [BF, batch, sources] = bf_wizard_sources(S) + S - input structure + Optional fields of S: + S.BF - Path to a BF structure or the + structure itself + - Default: REQUIRED + + S.batch - matlabbatch, of which this job + can be appended to + - Default: [] + + S.reduce_rank - [1x2] vector determining the + dimensionality of the lead + fields for a source, first + element for MEG, second for EEG + - Default: [2 3] + + S.keep3d - If the leadfield rank has been + reduced with S.reduce_rank, this + ensures the are still 3 lead fields + per source. + - Default: true + + S.normalise_lf - Make the norms of each lead field 1 + - Default: false + + S.visualise - Visualise the source space, sensors + and conductive boundar[y/ies] + - Default: true + + S.method - How do we want the source space + generated? Validated methods with + this are ( 'grid' | 'mesh' ) + - Default: REQUIRED + + S.run - Run the batch, set to 0 to + bypass the run for debugging + - Default: 1 + + + Method options for S: + Extensive details can be found at + https://github.com/spm/spm/blob/main/toolbox/DAiSS/doc/commands/02_sources.md + But a summary of the essential options below. + + GRID METHOD + + S.grid.resolution - Distance between sources + (in mm) - Default: 5 + + S.grid.constrain - Which boundary do we want + sources outside of to be + excluded? Options: ('iskull' + | 'oskull' | 'scalp') - Default: 'iskull' + + MESH METHOD + + S.mesh.orient - How are sources oriented on + the vertices of the mesh? + 'unoriented' keeps the lead field + triplet, whilst 'original' returns + one lead field normal to the mesh + surface + - Default: 'unoriented' + Output: + BF - Resultant DAiSS BF structure + batch - matlabbatch job for spm_jobman to run + sources - simplified summary of options selected + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_sources.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_view` + +```{text} + A handy command-line based batch filler with some defaults for DAiSS + view module, pick a few options, and it will default for unpopulated + fields + + Currently supported output methods include: + - glass + - surface + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_view.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_wizard_write` + +```{text} + A handy command-line based batch filler with some defaults for DAiSS + write module, pick a few options, and it will default for unpopulated + fields + + Currently supported output methods include: + - nifti (for volumetric data) + - gifti (for surface data) + - spmmeeg (for virtual electrodes) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_wizard_write.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_write` + +```{text} + Write out the results of beamforming analysis + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_write.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_write_gifti` + +```{text} + Write out beamformer results as GIfTI meshes + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_write_gifti.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_write_nifti` + +```{text} + Writes out nifti images of beamformer results + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_write_nifti.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bf_write_spmeeg` + +```{text} + Writes out beamformer results as M/EEG dataset + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DAiSS/bf_write_spmeeg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `binocdf` + +```{text} + BINOCDF binomial cumulative distribution function + + Y=BINOCDF(X,N,P) returns the binomial cumulative distribution + function with parameters N and P at the values in X. + + See also BINOPDF and STATS (Matlab statistics toolbox) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/stats/binocdf.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `binopdf` + +```{text} + BINOPDF binomial probability density function + + Y = BINOPDF(X,N,P) returns the binomial probability density + function with parameters N and P at the values in X. + + See also BINOCDF and STATS (Matlab statistics toolbox) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/stats/binopdf.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `bis2fieldtrip` + +```{text} + BIS2FIELDTRIP reads BioImage Suite .mgrid files and converts them + into a FieldTrip-compatible elec datatype structure and converts electrode + positions from BioImage Suite mgrid that are in 'xyz' to head coordinates + of the corresponding MRI volume + + Use as + elec = bis2fieldtrip('Subject_grid.mgrid', 'Subject_MR.nii') + + See also FIELDTRIP2BIS, FT_READ_SENS, READ_BIOIMAGE_MGRID + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/bis2fieldtrip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `boxcar` + +```{text} + BOXCAR returns a boxcar taper + + Use as + w = boxcar(n) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/signal/boxcar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_basicio_rewrite` + +```{text} + Rewrite job to conform to new submenu structure of BasicIO + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_basicio_rewrite.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_callbuiltin` + +```{text} + cfg_callbuiltin is a function. + varargout = cfg_callbuiltin(varargin) + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_callbuiltin.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_cfg_basicio` + +```{text} + 'BasicIO' - MATLABBATCH configuration + This MATLABBATCH configuration file has been generated automatically + by MATLABBATCH using ConfGUI. It describes menu structure, validity + constraints and links to run time code. + Changes to this file will be overwritten if the ConfGUI batch is executed again. + Created at 2015-12-01 13:53:35. + --------------------------------------------------------------------- + files Files + --------------------------------------------------------------------- + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_cfg_basicio.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_cfg_basicio_def` + +```{text} + 'BasicIO' - MATLABBATCH defaults + This MATLABBATCH defaults file has been generated automatically + by MATLABBATCH using ConfGUI. It contains all pre-defined values for + menu items and provides a full documentation of all fields that may + be present in a job variable for this application. + Changes to this file will be overwritten if the ConfGUI batch is executed again. + Created at 2015-12-01 13:53:35. + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_cfg_basicio_def.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_check_assignin` + +```{text} + Check whether the name entered for the workspace variable is a proper + variable name. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_check_assignin.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_confgui` + +```{text} + This function describes the user defined fields for each kind of + cfg_item and their layout in terms of cfg_items. Thus, the + configuration system can be used to generate code for new configuration + files itself. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_confgui/cfg_confgui.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_dbstop` + +```{text} + cfg_dbstop is a function. + cfg_dbstop(fh) + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_dbstop.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_add1` + +```{text} + Example script that creates an cfg_exbranch to sum two numbers. The + inputs are entered as two single numbers, the output is just a single + number. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_add1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_add2` + +```{text} + Example script that creates an cfg_exbranch to sum two numbers. The + inputs are entered as 2-vector, the output is just a single + number. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_add2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_cumsum1` + +```{text} + Example script that creates an cfg_exbranch to sum two numbers. The + inputs are entered as vector, the output is a vector containing the + cumulative sums. This function differs from cfg_example_sum (except from + names) only in the specification of the output subscript. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_cumsum1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_cumsum2` + +```{text} + Example script that creates an cfg_exbranch to sum two numbers. The + inputs are entered as vector, the output is a vector containing the + cumulative sums. This function differs from cfg_example_sum (except from + names) only in the specification of the output subscript. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_cumsum2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_div` + +```{text} + Example script that creates an cfg_exbranch to compute mod and rem of two + natural numbers. The inputs are entered as two single numbers, the output + is a struct with two fields 'mod' and 'rem'. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_div.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_master` + +```{text} + Master file that collects the cfg_exbranches in conceptually similar + groups. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_master.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_run_add1` + +```{text} + Example function that returns the sum of two numbers given in job.a and + job.b in out. The output is referenced as out(1), this is defined in + cfg_example_vout_add1. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_run_add1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_run_add2` + +```{text} + Example function that returns the sum of two numbers given in job.a in + out. The output is referenced as out(1), this is defined in + cfg_example_vout_add2. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_run_add2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_run_cumsum1` + +```{text} + Example function that returns the cumulative sum of an vector given in + job.a in out. The output is referenced as out(:), this is defined in + cfg_example_vout_cumsum1. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_run_cumsum1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_run_cumsum2` + +```{text} + Example function that returns the cumulative sum of an vector given in + job.a in out. The output is referenced as out(:), this is defined in + cfg_example_vout_cumsum1. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_run_cumsum2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_run_div` + +```{text} + Example function that returns the mod and rem of two numbers given in + job.a and job.b in out.mod and out.rem. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_run_div.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_run_sum` + +```{text} + Example function that returns the sum of an vector given in job.a in out. + The output is referenced as out(1), this is defined in + cfg_example_vout_sum. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_run_sum.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_example_sum` + +```{text} + Example script that creates an cfg_exbranch to sum two numbers. The + inputs are entered as vector, the output is just a single + number. This function differs from cfg_example_add2 (except from names) + only in the specification of input1.num. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/examples/cfg_example_sum.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_findspec` + +```{text} + function spec = cfg_findspec(cellspec) + Create a find specification. cellspec should contain a cell array of + cells, each of them containing name/value pairs that will be combined + into a struct suitable for e.g. @cfg_item/match and @cfg_item/list. + These methods will be used to e.g. select items in a configuration tree or + to match dependencies and input items. + + Name/value pairs within a cell will be OR concatenated, while cells + will be AND concatenated. + + A cellspec + {{'field1','val1','field2','val2'},{'field3','val3'}} + + matches an item if + (item.field1==val1 || item.field2==val2) && item.field3==val3 + + If the field name is 'class', an item matches, if its class name is equal to + spec.value. + + For class specific matching rules, see the help for the + resp. @cfg_.../match method. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_findspec.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_get_defaults` + +```{text} + function varargout = cfg_get_defaults(defspec, varargin) + Get/set defaults for various properties of matlabbatch utilities. + The values can be modified permanently by editing the file + private/cfg_mlbatch_defaults.m + or for the current MATLAB session by calling + cfg_get_defaults(defspec, defval). + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_get_defaults.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_getfile` + +```{text} + File selector + FORMAT [t,sts] = cfg_getfile(n,typ,mesg,sel,wd,filt,prms) + n - Number of files + A single value or a range. e.g. + 1 - Select one file + Inf - Select any number of files + [1 Inf] - Select 1 to Inf files + [0 1] - select 0 or 1 files + [10 12] - select from 10 to 12 files + typ - file type + 'any' - all files + 'batch' - matlabbatch batch files (.m, .mat and XML) + 'dir' - select a directory. By default, hidden ('.xyz') and + MATLAB class directories are not shown. + 'mat' - MATLAB .mat files or .txt files (assumed to contain + ASCII representation of a 2D-numeric array) + 'xml' - XML files + Other strings act as a filter to regexp. This means + that e.g. DCM*.mat files should have a typ of '^DCM.*\.mat$'. + A combination of types can be specified as a cellstr list of + types. A file must match at least one of the specified types. + mesg - a prompt (default 'Select files...') + sel - list of already selected files + wd - Directory to start off in + filt - value for user-editable filter (default '.*'). Can be a + string or cellstr. If it is a cellstr, filter expressions + will be concatenated by '|' (regexp OR operator). + prms - Type specific parameters + + t - selected files + sts - status (1 means OK, 0 means window quit) + + FORMAT [t,ind] = cfg_getfile('Filter',files,typ,filt,prms,...) + filter the list of files (column cell array) in the same way as the + GUI would do. The 'prms...' argument(s) will be passed to a typ + specific filtering function, if available. + When filtering directory names, the filt argument will be applied to the + last directory in a path only. + t returns the filtered list (cell array), ind an index array, such that + t = files(ind). + + FORMAT cpath = cfg_getfile('CPath',path,cwd) + function to canonicalise paths: Prepends cwd to relative paths, processes + '..' & '.' directories embedded in path. + path - cellstr containing path names + cwd - cellstr containing current working directory [default '.'] + cpath - conditioned paths, in same format as input path argument + + FORMAT [files,dirs]=cfg_getfile('List'[,direc[,typ[,filt[,prms]]]]) + Returns files matching the filter (filt) and directories within direc + direc - directory to search. Defaults to pwd. + typ - file type + filt - additional filter to select files with (see regexp) + e.g. '^w.*\.img$' + files - files matching 'typ' and 'filt' in directory 'direc' + dirs - subdirectories of 'direc' + FORMAT [files,dirs]=cfg_getfile('FPList'[,direc[,typ[,filt[,prms]]]]) + As above, but returns files with full paths (i.e. prefixes direc to + each). + FORMAT [files,dirs]=cfg_getfile('FPListRec'[,direc[,typ[,filt[,prms]]]]) + As above, but returns files with full paths (i.e. prefixes direc to + each) and searches through sub directories recursively. + + FORMAT cfg_getfile('PrevDirs',dir) + Add directory dir to list of previous directories. + FORMAT dirs=cfg_getfile('prevdirs') + Retrieve list of previous directories. + + FORMAT cfg_getfile('DirFilters', filter_list) + Specify a list of regular expressions to filter directory names. To show + all directories, use {'.*'}. Default is {'^[^.@]'}, i.e. directory names + starting with '.' or '@' will not be shown. + + FORMAT cfg_getfile('ListDrives'[, reread]) + On PCWIN(64) machines, list all available drive letters. If reread is + true, refresh internally cached list of drive letters. + + This code is based on the file selection dialog in SPM5, with virtual + file handling turned off. + ____________________________________________________________________________ + Copyright (C) 2005 Wellcome Department of Imaging Neuroscience + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_getfile.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_load_jobs` + +```{text} + function newjobs = cfg_load_jobs(job) + + Load a list of possible job files, return a cell list of jobs. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_load_jobs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_load_vars` + +```{text} + Load a .mat file, and return its contents via output dependencies. + varargout = cfg_load_vars(cmd, varargin) + where cmd is one of + 'run' - out = cfg_load_vars('run', job) + Run a job, and return its output argument + 'vout' - dep = cfg_load_vars('vout', job) + Create a virtual output for each requested variable. If + "all variables" are requested, only one output will be + generated. + 'check' - str = cfg_load_vars('check', subcmd, subjob) + 'isvarname' - check whether the entered string is a valid + MATLAB variable name. This does not check + whether the variable is present in the .mat file. + 'defaults' - defval = cfg_load_vars('defaults', key) + No defaults. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_load_vars.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_message` + +```{text} + function cfg_message(msgid, msgfmt, varargin) + Display a message. The message identifier msgid will be looked up in a + message database to decide how to treat this message. This database is + a struct array with fields: + .identifier - message id + .level - message severity level. One of + 'info' - print message + 'warning' - print message, raise a warning + 'error' - print message, throw an error + .destination - output destination. One of + 'none' - silently ignore this message + 'stdout' - standard output + 'stderr' - standard error output + 'syslog' - (UNIX) syslog + Warnings and errors will always be logged to the command + window and to syslog, if destination == 'syslog'. All + other messages will only be logged to the specified location. + .verbose + .backtrace - control verbosity and backtrace, one of 'on' or 'off' + + function [oldsts msgids] = cfg_message('on'|'off', 'verbose'|'backtrace', msgidregexp) + Set verbosity and backtrace display for all messages where msgid + matches msgidregexp. To match a message id exactly, use the regexp + '^msgid$'. + + function [olddest msgids] = cfg_message('none'|'stdout'|'stderr'|'syslog', 'destination', msgidregexp) + Set destination for all messages matching msgidregexp. + + function [oldlvl msgids] = cfg_message('info'|'warning'|'error', 'level', msgidregexp) + Set severity level for all messages matching msgidregexp. + + For all matching message ids and message templates, the old value and + the id are returned as cell strings. These can be used to restore + previous settings one-by-one. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_message.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_mlbatch_appcfg` + +```{text} + Add BasicIO to applications list of cfg_util. This file is an example how + to add your own application configuration to cfg_util. To add an + application, create a file called cfg_mlbatch_appcfg.m in the application + folder and add this folder to the MATLAB path. cfg_util will look for + files with the exact name cfg_mlbatch_appcfg.m and run all of them in + order of their occurrence on the path. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_mlbatch_appcfg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_assignin` + +```{text} + Assign the value of job.output to a workspace variable job.name. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_assignin.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_call_matlab` + +```{text} + A generic interface to call any MATLAB function through the batch system + and make its output arguments available as dependencies. + varargout = cfg_run_call_matlab(cmd, varargin) + where cmd is one of + 'run' - out = cfg_run_call_matlab('run', job) + Run the function, and return the specified output arguments + 'vout' - dep = cfg_run_call_matlab('vout', job) + Return dependencies as specified via the output cfg_repeat. + 'check' - str = cfg_run_call_matlab('check', subcmd, subjob) + Examine a part of a fully filled job structure. Return an empty + string if everything is ok, or a string describing the check + error. subcmd should be a string that identifies the part of + the configuration to be checked. + 'defaults' - defval = cfg_run_call_matlab('defaults', key) + Retrieve defaults value. key must be a sequence of dot + delimited field names into the internal def struct which is + kept in function local_def. An error is returned if no + matching field is found. + cfg_run_call_matlab('defaults', key, newval) + Set the specified field in the internal def struct to a new + value. + Application specific code needs to be inserted at the following places: + 'run' - main switch statement: code to compute the results, based on + a filled job + 'vout' - main switch statement: code to compute cfg_dep array, based + on a job structure that has all leafs, but not necessarily + any values filled in + 'check' - create and populate switch subcmd switchyard + 'defaults' - modify initialisation of defaults in subfunction local_defs + Callbacks can be constructed using anonymous function handles like this: + 'run' - @(job)cfg_run_call_matlab('run', job) + 'vout' - @(job)cfg_run_call_matlab('vout', job) + 'check' - @(job)cfg_run_call_matlab('check', 'subcmd', job) + 'defaults' - @(val)cfg_run_call_matlab('defaults', 'defstr', val{:}) + Note the list expansion val{:} - this is used to emulate a + varargin call in this function handle. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_call_matlab.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_cd` + +```{text} + Make a directory and return its path in out.dir{1}. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_cd.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_dir_move` + +```{text} + Move, copy or delete directory + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_dir_move.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_file_filter` + +```{text} + Return filtered files. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_file_filter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_file_fplist` + +```{text} + function out = cfg_run_file_fplist(job) + + Select files non-interactively using cfg_getfile('FPList',...) or + cfg_getfile('FPListRec',...). + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_file_fplist.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_file_move` + +```{text} + Move files to another directory or delete them, if no directory is + specified. Special treatment to move .img/.hdr/.mat pairs of files + together. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_file_move.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_file_split` + +```{text} + Split a set of files according to subset indices. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_file_split.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_fileparts` + +```{text} + Run fileparts on a list of files. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_fileparts.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_gunzip_files` + +```{text} + Run gunzip on a list of files. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_gunzip_files.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_gzip_files` + +```{text} + Run gzip on a list of files. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_gzip_files.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_mkdir` + +```{text} + Make a directory and return its path in out.dir{1}. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_mkdir.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_named_dir` + +```{text} + Return selected dirs as separate output arguments. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_named_dir.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_named_file` + +```{text} + Return selected files as separate output arguments. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_named_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_named_input` + +```{text} + Return evaluated input. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_named_input.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_runjobs` + +```{text} + Initialise, fill, save and run a job with repeated inputs. + To make use of possible parallel execution of independent jobs, all + repeated jobs are filled first and (if successfully filled) run as one + large job. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_runjobs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_save_vars` + +```{text} + Save input variables to .mat file - either as a struct array, or as + individual variables. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_save_vars.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_subsrefvar` + +```{text} + Template function to implement callbacks for an cfg_exbranch. The calling + syntax is + varargout = cfg_run_subsrefvar(cmd, varargin) + where cmd is one of + 'run' - out = cfg_run_subsrefvar('run', job) + Run a job, and return its output argument + 'vout' - dep = cfg_run_subsrefvar('vout', job) + Examine a job structure with all leafs present and return an + array of cfg_dep objects. + 'check' - str = cfg_run_subsrefvar('check', subcmd, subjob) + Examine a part of a fully filled job structure. Return an empty + string if everything is ok, or a string describing the check + error. subcmd should be a string that identifies the part of + the configuration to be checked. + 'defaults' - defval = cfg_run_subsrefvar('defaults', key) + Retrieve defaults value. key must be a sequence of dot + delimited field names into the internal def struct which is + kept in function local_def. An error is returned if no + matching field is found. + cfg_run_subsrefvar('defaults', key, newval) + Set the specified field in the internal def struct to a new + value. + Application specific code needs to be inserted at the following places: + 'run' - main switch statement: code to compute the results, based on + a filled job + 'vout' - main switch statement: code to compute cfg_dep array, based + on a job structure that has all leafs, but not necessarily + any values filled in + 'check' - create and populate switch subcmd switchyard + 'defaults' - modify initialisation of defaults in subfunction local_defs + Callbacks can be constructed using anonymous function handles like this: + 'run' - @(job)cfg_run_subsrefvar('run', job) + 'vout' - @(job)cfg_run_subsrefvar('vout', job) + 'check' - @(job)cfg_run_subsrefvar('check', 'subcmd', job) + 'defaults' - @(val)cfg_run_subsrefvar('defaults', 'defstr', val{:}) + Note the list expansion val{:} - this is used to emulate a + varargin call in this function handle. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_run_subsrefvar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_run_template` + +```{text} + Template function to implement callbacks for an cfg_exbranch. The calling + syntax is + varargout = cfg_run_template(cmd, varargin) + where cmd is one of + 'run' - out = cfg_run_template('run', job) + Run a job, and return its output argument + 'vout' - dep = cfg_run_template('vout', job) + Examine a job structure with all leafs present and return an + array of cfg_dep objects. + 'check' - str = cfg_run_template('check', subcmd, subjob) + Examine a part of a fully filled job structure. Return an empty + string if everything is ok, or a string describing the check + error. subcmd should be a string that identifies the part of + the configuration to be checked. + 'defaults' - defval = cfg_run_template('defaults', key) + Retrieve defaults value. key must be a sequence of dot + delimited field names into the internal def struct which is + kept in function local_def. An error is returned if no + matching field is found. + cfg_run_template('defaults', key, newval) + Set the specified field in the internal def struct to a new + value. + Application specific code needs to be inserted at the following places: + 'run' - main switch statement: code to compute the results, based on + a filled job + 'vout' - main switch statement: code to compute cfg_dep array, based + on a job structure that has all leafs, but not necessarily + any values filled in + 'check' - create and populate switch subcmd switchyard + 'defaults' - modify initialisation of defaults in subfunction local_defs + Callbacks can be constructed using anonymous function handles like this: + 'run' - @(job)cfg_run_template('run', job) + 'vout' - @(job)cfg_run_template('vout', job) + 'check' - @(job)cfg_run_template('check', 'subcmd', job) + 'defaults' - @(val)cfg_run_template('defaults', 'defstr', val{:}) + Note the list expansion val{:} - this is used to emulate a + varargin call in this function handle. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_confgui/cfg_run_template.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_serial` + +```{text} + This function is deprecated. + The functionality should replaced by the following sequence of calls: + + Instead of + cfg_serial(guifcn, job, varargin) + use + cjob = cfg_util('initjob', job); + sts = cfg_util('filljobui', cjob, guifcn, varargin); + if sts + cfg_util('run', cjob); + end; + cfg_util('deljob', cjob); + + Instead of + cfg_serial(guifcn, tagstr, varargin) + use + cjob = cfg_util('initjob'); + mod_cfg_id = cfg_util('tag2cfg_id', tagstr); + cfg_util('addtojob', cjob, mod_cfg_id); + sts = cfg_util('filljobui', cjob, guifcn, varargin); + if sts + cfg_util('run', cjob); + end; + cfg_util('deljob', cjob); + + Instead of + cfg_serial(guifcn, mod_cfg_id, varargin) + use + cjob = cfg_util('initjob'); + cfg_util('addtojob', cjob, mod_cfg_id); + sts = cfg_util('filljobui', cjob, guifcn, varargin); + if sts + cfg_util('run', cjob); + end; + cfg_util('deljob', cjob); + + If no guifcn is specified, use cfg_util('filljob',... instead. + + GuiFcn semantics + [val sts] = guifcn(item) + val should be suitable to set item.val{1} using setval(item, val, + false) for all cfg_leaf items. For cfg_repeat/cfg_choice items, val + should be a cell array of indices into item.values. For each element of + val, setval(item, [val{k} Inf], false) + will be called and thus item.values{k} will be appended to item.val. + sts should be set to true, if guifcn returns with success (i.e. a + valid value is returned or input should continue for the next item, + regardless of value validity). + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_serial.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_struct2cfg` + +```{text} + Import a config structure into a matlabbatch class tree. Input structures + are those generated from the configuration editor, cfg2struct methods or + spm_jobman config structures. + + The layout of the configuration tree and the types of configuration items + have been kept compatible to a configuration system and job manager + implementation in SPM5 (Statistical Parametric Mapping, Copyright (C) + 2005 Wellcome Department of Imaging Neuroscience). This code has been + completely rewritten based on an object oriented model of the + configuration tree. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_struct2cfg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_tropts` + +```{text} + function tropts = cfg_tropts(stopspec, clvl, mlvl, cnt, mcnt, dflag) + This function is a shorthand that generates a traversal options structure + from the following items: + stopspec - a find spec shorthand as input to cfg_findspec (see + cfg_findspec for details) + clvl, mlvl - current/maximum tree level + cnt, mcnt - found items/maximum #items + dflag - traverse val/values part of tree + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_tropts.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_txtdesc2cfg` + +```{text} + Create a cfg_item tree from a short-hand text description + cfg = cfg_txtdesc2cfg(fname) + This utility reads a text file from fname and creates a configuration + object tree according to the following grammar rules. + + Each line in the file has the form + + TAGNAME = RIGHTHANDSIDE + + where TAGNAME is a valid tag name for a cfg_item object. For each line, a + cfg_item object with tag TAGNAME will be created. Its class is determined + by the format of RIGHTHANDSIDE. RIGHTHANDSIDE can be one of + + (TAGNAME_1 TAGNAME_2 ... TAGNAME_N) - cfg_branch + + {TAGNAME_1 TAGNAME_2 ... TAGNAME_N} - cfg_repeat + + [TAGNAME_1 TAGNAME_2 ... TAGNAME_N] - cfg_mchoice + + |TAGNAME_1 TAGNAME_2 ... TAGNAME_N| - cfg_choice + + with .val (for cfg_branch) or .values (all other cases) fields set to the + cfg_item objects referenced by TAGNAME_1 ... TAGNAME_N. + + TAGNAME_1 - same type as TAGNAME_1, but with tag TAGNAME instead of + TAGNAME_1 + + 'some_matlab_code' - this MATLAB code will be evaluated. Its return + value should be a cfg_* object. The tag of this + object will be set to 'TAGNAME' + + The cfg_item object returned will be the one defined in the first line of + the file. The depth of the substitutions is not limited, but all + substitutions must finally be resolvable to 'some_matlab_code'. + + A valid description would be + + toplevel = {mychoice mybranch} + mychoice = |myrepeat myconst| + myrepeat = {mymenu} + mybranch = (mymchoice myentry) + mymchoice = [myfiles myfiles1] + myfiles1 = myfiles + myfiles = 'cfg_files' + myconst = 'cfg_const' + myentry = 'cfg_entry' + mymenu = 'cfg_menu' + + The resulting object tree will need further adjustment, but it can serve + as a good starting point for modifying program code. The sequence + + cfg = cfg_txtdesc2cfg('mygrammar.txt'); + cfgstr = gencode(cfg); + cfgchr = sprintf('%s + ',cfgstr{:}); + clipboard('copy', cfgchr) + + will create a cfg_item tree as defined in 'mygrammar.txt', convert it + into MATLAB code lines, print them into a newline-separated string and + copy this string into the clipboard. From there, it can be pasted into + any application (MATLAB editor, external editor ...) where it can be + processed further. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_txtdesc2cfg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_ui` + +```{text} + CFG_UI M-File for cfg_ui.fig + CFG_UI, by itself, creates a new CFG_UI or raises the existing + singleton*. + + H = CFG_UI returns the handle to a new CFG_UI or the handle to + the existing singleton*. + + CFG_UI('CALLBACK',hObject,eventData,handles,...) calls the local + function named CALLBACK in CFG_UI.M with the given input arguments. + + CFG_UI('Property','Value',...) creates a new CFG_UI or raises the + existing singleton*. Starting from the left, property value pairs are + applied to the GUI before cfg_ui_OpeningFcn gets called. An + unrecognized property name or invalid value makes property application + stop. All inputs are passed to cfg_ui_OpeningFcn via varargin. + + *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one + instance to run (singleton)". + + See also: GUIDE, GUIDATA, GUIHANDLES + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_ui.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_ui_multibatch` + +```{text} + CFG_UI_MULTIBATCH MATLAB code for cfg_ui_multibatch.fig + CFG_UI_MULTIBATCH, by itself, creates a new CFG_UI_MULTIBATCH or raises the existing + singleton*. + + H = CFG_UI_MULTIBATCH returns the handle to a new CFG_UI_MULTIBATCH or the handle to + the existing singleton*. + + CFG_UI_MULTIBATCH('CALLBACK',hObject,eventData,handles,...) calls the local + function named CALLBACK in CFG_UI_MULTIBATCH.M with the given input arguments. + + CFG_UI_MULTIBATCH('Property','Value',...) creates a new CFG_UI_MULTIBATCH or raises the + existing singleton*. Starting from the left, property value pairs are + applied to the GUI before cfg_ui_multibatch_OpeningFcn gets called. An + unrecognized property name or invalid value makes property application + stop. All inputs are passed to cfg_ui_multibatch_OpeningFcn via varargin. + + *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one + instance to run (singleton)". + + See also: GUIDE, GUIDATA, GUIHANDLES + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_ui_multibatch.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_ui_util` + +```{text} + CFG_UI_UTIL utility functions for displaying job, module and item values + This function is a collection of utility functions to display a job, + module or data summary. It also handles all value display and editing for + a particular item. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_ui_util.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_util` + +```{text} + This is the command line interface to the batch system. It manages the + following structures: + * Generic configuration structure c0. This structure will be initialised + to an cfg_repeat with empty .values list. Each application should + provide an application-specific master configuration file, which + describes the executable module(s) of an application and their inputs. + This configuration will be rooted directly under the master + configuration node. In this way, modules of different applications can + be combined with each other. + CAVE: the root nodes of each application must have an unique tag - + cfg_util will refuse to add an application which has a root tag that is + already used by another application. + * Job specific configuration structure cj. This structure contains the + modules to be executed in a job, their input arguments and + dependencies between them. The layout of cj is not visible to the user. + To address executable modules and their input values, cfg_util will + return id(s) of unspecified type. If necessary, these id(s) should be + stored in cell arrays in a calling application, since their internal + format may change. + + The commands to manipulate these structures are described below in + alphabetical order. + + cfg_util('addapp', cfg[, def[, ver]]) + + Add an application to cfg_util. If cfg is a cfg_item, then it is used + as initial configuration. Alternatively, if cfg is a MATLAB function, + this function is evaluated. The return argument of this function must be + a single variable containing the full configuration tree of the + application to be batched. + Optionally, a defaults configuration struct or function can be supplied. + This function must return a single variable containing a (pseudo) job + struct/cell array which holds defaults values for configuration items. + These defaults should be rooted at the application's root node, not at + the overall root node. They will be inserted by calling initialise on the + application specific part of the configuration tree. + Optionally, a version string can be specified. This version string will + be documented in all batches that are saved as .m files. + + mod_job_id = cfg_util('addtojob', job_id, mod_cfg_id) + + Append module with id mod_cfg_id in the cfg tree to job with id + job_id. Returns a mod_job_id, which can be passed on to other cfg_util + callbacks that modify the module in the job. + + [new_job_id] = cfg_util('clonejob', job_id) + + Clone an already initialised job. + + [mod_job_idlist, new2old_id] = cfg_util('compactjob', job_id) + + Modifies the internal representation of a job by removing deleted modules + from the job configuration tree. This will invalidate all mod_job_ids and + generate a new mod_job_idlist. + A translation table new2old_id is provided, where + mod_job_idlist = old_mod_job_idlist{new2old_id} + translates between an old id list and the compact new id list. + + cfg_util('dbstop', job_id, mod_job_id) + + Set a breakpoint at the beginning of the function that executes the + module. If a module occurs more than once in a job or its .prog is a + multi-purpose function, execution will stop at all calls of that function. + + cfg_util('delfromjob', job_id, mod_job_id) + + Delete a module from a job. + + cfg_util('deljob', job_id) + + Delete job with job_id from the job list. + + sts = cfg_util('filljob', job_id, input1, ..., inputN) + sts = cfg_util('filljobui', job_id, ui_fcn, input1, ..., inputN) + + Fill missing inputs in a job from a list of input items. For + cfg_entry/cfg_files, each input should be suitable to be assigned to + item.val{1}. For cfg_menu, input should be an index into the menu list as + displayed in the GUI, starting with 1. + If an item can not be filled by the specified input, this input will be + discarded. If cfg_util('filljobui'...) is called, [val sts] = + ui_fcn(item) will be run and should return a value which is suitable for + setval(item, val, false). sts should be set to true if input should + continue with the next item. This can result in an partially filled job. + If ui_fcn is interrupted, the job will stay unfilled. + If cfg_util('filljob'...) is called, the current job can become partially + filled. + Returns the all_set status of the filled job, returns always false if + ui_fcn is interrupted. + + cfg_util('gencode', fname, apptag|cfg_id[, tropts]) + + Generate code from default configuration structure, suitable for + recreating the tree structure. Note that function handles may not be + saved properly. By default, the entire tree is saved into a file fname. + If tropts is given as a traversal option specification, code generation + will be split at the nodes matching tropts.stopspec. Each of these nodes will + generate code in a new file with filename cfg_util_, and the + nodes up to tropts.stopspec will be saved into fname. + If a file named cfg_util_mlb_preamble.m exists in the folder where the + configuration code is being written, it will be read in literally + and its contents will be prepended to each of the created files. This + allows to automatically include e.g. copyright or revision. + + cfg_util('genscript', job_id, scriptdir, filename) + + Generate a script which collects missing inputs of a batch job and runs + the job using cfg_util('filljob', ...). The script will be written to + file filename.m in scriptdir, the job will be saved to filename_job.m in + the same folder. The script must be completed by adding code to collect + the appropriate inputs for the job. + + outputs = cfg_util('getAllOutputs', job_id) + + outputs - cell array with module outputs. If a module has not yet been + run, a cfg_inv_out object is returned. + + voutputs = cfg_util('getAllVOutputs', job_id[, mod_job_id]) + + voutputs - cell array with virtual output descriptions (cfg_dep objects). + These describe the structure of the job outputs. To create + dependencies, they can be entered into matching input objects + in subsequent modules of the same job. + If mod_job_id is supplied, only virtual output descriptions of + the referenced module are returned. + + cfg = cfg_util('getcfg') + + Get internal cfg representation from cfg_util. + + diary = cfg_util('getdiary', job_id) + + diary - cellstr containing command window output of job execution. + If cfg_get_defaults('cfg_util.run_diary') is set to true, cfg_util will + use MATLABs diary function to capture all command line output of a + running job. cfg_util('getdiary', jobid) retrieves the last diary saved + for a job. + + [mod_job_idlist, mod_names, mod_item_idx, ... + item_mod_idlists, item_names] = cfg_util('getopeninputs', cjob) + + List all modules and input items that are not yet filled in a job + template. This is a combination of 'showjob' and parts of 'showmod' to + access only unset input items in an entire job. + mod_job_idlist - cell list of module ids with open inputs + mod_names - names of modules with open inputs + mod_item_idx - index into mod_job_idlist/mod_names to match a + linearized version of item_mod_idlists/item_names + item_mod_idlists - cell list of item_mod_ids with open inputs. One cell + entry per module, containing the within-module + item_mod_idlist. + item_names - cell list of item name lists for each item with open + inputs. + + [tag, val] = cfg_util('harvest', job_id[, mod_job_id[, item_mod_id]]) + + Harvest is a method defined for all 'cfg_item' objects. It collects the + entered values and dependencies of the input items in the tree and + assembles them in a struct/cell array. + If only job_id is supplied, the internal configuration tree will be + cleaned up before harvesting. Dependencies will not be resolved in this + case. The internal state of cfg_util is not modified in this case. The + structure returned in val may be saved to disk as a job and can be loaded + back into cfg_util using the 'initjob' command. + If a mod_job_id, but not an item_mod_id is supplied, only the relevant + part of the configuration tree is harvested, dependencies are resolved + and the internal state of cfg_util is updated. In this case, the val + output is only part of a job description. It can be used as an input + argument to the corresponding module's .prog function, but can not be + loaded back into cfg_util. + If all ids are supplied, the configuration tree starting at the + specified item will be harvested. No dependencies will be resolved, and + no cleanup will be done. + + [tag, appdef] = cfg_util('harvestdef'[, apptag|cfg_id]) + + Harvest the defaults branches of the current configuration tree. If + apptag is supplied, only the subtree of that application whose root tag + matches apptag/whose id matches cfg_id is harvested. In this case, + appdef is a struct/cell array that can be supplied as a second argument + in application initialisation by cfg_util('addapp', appcfg, + appdef). + If no application is specified, defaults of all applications will be + returned in one struct/cell array. + + [tag, val] = cfg_util('harvestrun', job_id) + + Harvest data of a job that has been (maybe partially) run, resolving + all dependencies that can be resolved. This can be used to document + what has actually been done in a job and which inputs were passed to + modules with dependencies. + If the job has not been run yet, tag and val will be empty. + + cfg_util('initcfg') + + Initialise cfg_util configuration. All currently added applications and + jobs will be cleared. + Initial application data will be initialised to a combination of + cfg_mlbatch_appcfg.m files in their order found on the MATLAB path. Each + of these config files should be a function with calling syntax + function [cfg, def] = cfg_mlbatch_appcfg(varargin) + This function should do application initialisation (e.g. add + paths). cfg and def should be configuration and defaults data + structures or the name of m-files on the MATLAB path containing these + structures. If no defaults are provided, the second output argument + should be empty. + cfg_mlbatch_appcfg files are executed in the order they are found on + the MATLAB path with the one first found taking precedence over + following ones. + + cfg_util('initdef', apptag|cfg_id[, defvar]) + + Set default values for application specified by apptag or + cfg_id. If defvar is supplied, it should be any representation of a + defaults job as returned by cfg_util('harvestdef', apptag|cfg_id), + i.e. a MATLAB variable, a function creating this variable... + Defaults from defvar are overridden by defaults specified in .def + fields. + New defaults only apply to modules added to a job after the defaults + have been loaded. Saved jobs and modules already present in the current + job will not be changed. + + [job_id, mod_job_idlist] = cfg_util('initjob'[, job]) + + Initialise a new job. If no further input arguments are provided, a new + job without modules will be created. + If job is given as input argument, the job tree structure will be + loaded with data from the struct/cell array job and a cell list of job + ids will be returned. + The new job will be appended to an internal list of jobs. It must + always be referenced by its job_id. + + sts = cfg_util('isjob_id', job_id) + sts = cfg_util('ismod_cfg_id', mod_cfg_id) + sts = cfg_util('ismod_job_id', job_id, mod_job_id) + sts = cfg_util('isitem_mod_id', item_mod_id) + Test whether the supplied id seems to be of the queried type. Returns + true if the id matches the data format of the queried id type, false + otherwise. For item_mod_ids, no checks are performed whether the id is + really valid (i.e. points to an item in the configuration + structure). This can be used to decide whether 'list*' or 'tag2*' + callbacks returned valid ids. + + [mod_cfg_idlist, stop, [contents]] = cfg_util('listcfg[all]', mod_cfg_id, find_spec[, fieldnames]) + + List modules and retrieve their contents in the cfg tree, starting at + mod_cfg_id. If mod_cfg_id is empty, search will start at the root level + of the tree. The returned mod_cfg_id_list is always relative to the root + level of the tree, not to the mod_cfg_id of the start item. This search + is designed to stop at cfg_exbranch level. Its behaviour is undefined if + mod_cfg_id points to an item within an cfg_exbranch. See 'match' and + 'cfg_item/find' for details how to specify find_spec. A cell list of + matching modules is returned. + If the 'all' version of this command is used, also matching + non-cfg_exbranch items up to the first cfg_exbranch are returned. This + can be used to build a menu system to manipulate configuration. + If a cell array of fieldnames is given, contents of the specified fields + will be returned. See 'cfg_item/list' for details. This callback is not + very specific in its search scope. To find a cfg_item based on the + sequence of tags of its parent items, use cfg_util('tag2mod_cfg_id', + tagstring) instead. + + [item_mod_idlist, stop, [contents]] = cfg_util('listmod', job_id, mod_job_id, item_mod_id, find_spec[, tropts][, fieldnames]) + [item_mod_idlist, stop, [contents]] = cfg_util('listmod', mod_cfg_id, item_mod_id, find_spec[, tropts][, fieldnames]) + + Find configuration items starting in module mod_job_id in the job + referenced by job_id or in module mod_cfg_id in the defaults tree, + starting at item item_mod_id. If item_mod_id is an empty array, start + at the root of a module. By default, search scope are the filled items + of a module. See 'match' and 'cfg_item/find' for details how to specify + find_spec and tropts and how to search the default items instead of the + filled ones. A cell list of matching items is returned. + If a cell array of fieldnames is given, contents of the specified fields + will be returned. See 'cfg_item/list' for details. + + sts = cfg_util('match', job_id, mod_job_id, item_mod_id, find_spec) + + Returns true if the specified item matches the given find spec and false + otherwise. An empty item_mod_id means that the module node itself should + be matched. + + new_mod_job_id = cfg_util('replicate', job_id, mod_job_id[, item_mod_id, val]) + + If no item_mod_id is given, replicate a module by appending it to the + end of the job with id job_id. The values of all items will be + copied. This is in contrast to 'addtojob', where a module is added with + default settings. Dependencies where this module is a target will be + kept, whereas source dependencies will be dropped from the copied module. + If item_mod_id points to a cfg_repeat object within a module, its + setval method is called with val. To achieve replication, val(1) must + be finite and negative, and val(2) must be the index into item.val that + should be replicated. All values are copied to the replicated entry. + + cfg_util('run'[, job|job_id]) + + Run the currently configured job. If job is supplied as argument and is + a harvested job, then cfg_util('initjob', job) will be called first. If + job_id is supplied and is a valid job_id, the job with this job id will + be run. + The job is harvested and dependencies are resolved if possible. + If cfg_get_defaults('cfg_util.runparallel') returns true, all + modules without unresolved dependencies will be run in arbitrary order. + Then the remaining modules are harvested again and run, if their + dependencies can be resolved. This process is iterated until no modules + are left or no more dependencies can resolved. In a future release, + independent modules may run in parallel, if there are licenses to the + Distributed Computing Toolbox available. + Note that this requires dependencies between modules to be described by + cfg_dep objects. If a module e.g. relies on file output of another module + and this output is already specified as a filename of a non-existent + file, then the dependent module may be run before the file is created. + Side effects (changes in global variables, working directories) are + currently not modeled by dependencies. + If a module fails to execute, computation will continue on modules that + do not depend on this module. An error message will be logged and the + module will be reported as 'failed to run' in the MATLAB command window. + + cfg_util('runserial'[, job|job_id]) + + Like 'run', but force cfg_util to run the job as if each module was + dependent on its predecessor. If cfg_get_defaults('cfg_util.runparallel') + returns false, cfg_util('run',...) and cfg_util('runserial',...) are + identical. + + cfg_util('savejob', job_id, filename) + + The current job will be save to the .m file specified by filename. This + .m file contains MATLAB script code to recreate the job variable. It is + based on gencode (part of this MATLAB batch system) for all standard + MATLAB types. For objects to be supported, they must implement their own + gencode method. + + cfg_util('savejobrun', job_id, filename) + + Save job after it has been run, resolving dependencies (see + cfg_util('harvestrun',...)). If the job has not been run yet, nothing + will be saved. + + sts = cfg_util('setval', job_id, mod_job_id, item_mod_id, val) + + Set the value of item item_mod_id in module mod_job_id to val. If item is + a cfg_choice, cfg_repeat or cfg_menu and val is numeric, the value will + be set to item.values{val(1)}. If item is a cfg_repeat and val is a + 2-vector, then the min(val(2),numel(item.val)+1)-th value will be set + (i.e. a repeat added or replaced). If val is an empty cell, the value of + item will be cleared. + sts returns the status of all_set_item after the value has been + set. This can be used to check whether the item has been successfully + set. + Once editing of a module has finished, the module needs to be harvested + in order to update dependencies from and to other modules. + + cfg_util('setdef', mod_cfg_id, item_mod_id, val) + + Like cfg_util('setval',...) but set items in the defaults tree. This is + only supported for cfg_leaf items, not for cfg_choice, cfg_repeat, + cfg_branch items. + Defaults only apply to new jobs, not to already configured ones. + + doc = cfg_util('showdoc', tagstr|cfg_id|(job_id, mod_job_id[, item_mod_id])) + + Return help text for specified item. Item can be either a tag string or + a cfg_id in the default configuration tree, or a combination of job_id, + mod_job_id and item_mod_id from the current job. + The text returned will be a cell array of strings, each string + containing one paragraph of the help text. In addition to the help + text, hints about valid values, defaults etc. are displayed. + + doc = cfg_util('showdocwidth', handle|width, tagstr|cfg_id|(job_id, mod_job_id[, item_mod_id])) + + Same as cfg_util('showdoc', but use handle or width to determine the + width of the returned strings. + + [mod_job_idlist, str, sts, dep, sout] = cfg_util('showjob', job_id[, mod_job_idlist]) + + Return information about the current job (or the part referenced by the + input cell array mod_job_idlist). Output arguments + * mod_job_idlist - cell list of module ids (same as input, if provided) + * str - cell string of names of modules + * sts - array of all set status of modules + * dep - array of dependency status of modules + * sout - array of output description structures + Each module configuration may provide a callback function 'vout' that + returns a struct describing module output variables. See 'cfg_exbranch' + for details about this callback, output description and output structure. + The module needs to be harvested before to make output_struct available. + This information can be used by the calling application to construct a + dependency object which can be passed as input to other modules. See + 'cfg_dep' for details about dependency objects. + + [mod_cfg_id, item_mod_id] = cfg_util('tag2cfg_id', tagstr) + + Return a mod_cfg_id for the cfg_exbranch item that is the parent to the + item in the configuration tree whose parents have tag names as in the + dot-delimited tag string. item_mod_id is relative to the cfg_exbranch + parent. If tag string matches a node above cfg_exbranch level, then + item_mod_id will be invalid and mod_cfg_id will point to the specified + node. + Use cfg_util('ismod_cfg_id') and cfg_util('isitem_mod_id') to determine + whether returned ids are valid or not. + Tag strings should begin at the root level of an application configuration, + not at the matlabbatch root level. + + mod_cfg_id = cfg_util('tag2mod_cfg_id', tagstr) + + Same as cfg_util('tag2cfg_id', tagstr), but it only returns a proper + mod_cfg_id. If none of the tags in tagstr point to a cfg_exbranch, then + mod_cfg_id will be invalid. + + The layout of the configuration tree and the types of configuration items + have been kept compatible to a configuration system and job manager + implementation in SPM5 (Statistical Parametric Mapping, Copyright (C) + 2005 Wellcome Department of Imaging Neuroscience). This code has been + completely rewritten based on an object oriented model of the + configuration tree. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_util.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_dir_move` + +```{text} + Define virtual output for cfg_run_dir_move. Output can be passed on to + either a cfg_files or an evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_dir_move.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_file_filter` + +```{text} + Define virtual outputs for cfg_vout_file_filter. The file names can either + be assigned to a cfg_files input or to a evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_file_filter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_file_fplist` + +```{text} + function dep = cfg_vout_file_fplist(job) + + Virtual outputs for cfg_run_file_fplist. Struct with fields .files and + .dirs. See help on cfg_getfile. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_file_fplist.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_file_move` + +```{text} + Define virtual output for cfg_run_move_file. Output can be passed on to + either a cfg_files or an evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_file_move.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_file_split` + +```{text} + Define virtual outputs for cfg_run_file_split. File names can either be + assigned to a cfg_files input or to a evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_file_split.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_fileparts` + +```{text} + Define virtual outputs for cfg_run_fileparts. The path names can either + be assigned to a cfg_files input or to an evaluated cfg_entry. File names + and extensions can only be assigned to an evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_fileparts.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_gunzip_files` + +```{text} + Define virtual outputs for "Gunzip Files". File names can either be + assigned to a cfg_files input or to a evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_gunzip_files.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_gzip_files` + +```{text} + Define virtual outputs for "Gzip Files". File names can either be + assigned to a cfg_files input or to a evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_gzip_files.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_mkdir` + +```{text} + Define virtual outputs for cfg_run_mkdir. The directory name can either + be assigned to a cfg_files directory input or to a evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_mkdir.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_named_dir` + +```{text} + Define virtual outputs for cfg_run_named_dir. Dir names can either be + assigned to a cfg_dirs input or to a evaluated cfg_entry. Dir indices + can be assigned to any numeric or evaluated cfg_entry item. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_named_dir.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_named_file` + +```{text} + Define virtual outputs for cfg_run_named_file. File names can either be + assigned to a cfg_files input or to a evaluated cfg_entry. File indices + can be assigned to any numeric or evaluated cfg_entry item. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_named_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_named_input` + +```{text} + Define virtual output for cfg_run_named_input. This input can be assigned + to any cfg_entry input item. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_named_input.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_runjobs` + +```{text} + Return dependency to jobfiles, if files are to be saved. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_runjobs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `cfg_vout_save_vars` + +```{text} + Define virtual output for cfg_run_save_vars. Output can be passed on to + either a cfg_file or an evaluated cfg_entry. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/cfg_vout_save_vars.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `common_size` + +```{text} + common_size is a function. + [errorcode, varargout] = common_size(varargin) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/stats/common_size.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `copyfields` + +```{text} + COPYFIELDS copies a selection of the fields from one structure to another + + Use as + b = copyfields(a, b, fields); + which copies the specified fields over from structure a to structure b. Fields that + are specified but not present will be silently ignored. + + See also KEEPFIELDS, REMOVEFIELDS, RENAMEFIELDS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/copyfields.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `covLin` + +```{text} + Covariance function for linear regression/classification + FORMAT [K1,lambda] = covLin(lambda0,settings,args,lab) + No usage documentation yet + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Shoot/covLin.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `create_cfg_cfg_basicio` + +```{text} + create_cfg_cfg_basicio is a function. + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/cfg_basicio/src/create_cfg_cfg_basicio.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `dartel3` + +```{text} + DARTEL 3D image registration stuff + __________________________________________________________________________ + + FORMAT v = dartel3(v,g,f,param) + v - flow field n1*n2*n3*3 (single precision float) + g - first image n1*n2*n3*n4 (single precision float) + f - second image n1*n2*n3*n4 (single precision float) + param - 9 parameters (settings) + - [1] Regularisation type, can take values of + - 0 Linear elasticity + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Regularisation parameters + - For "membrane energy", the parameters are + lambda, unused and id. + - For "linear elasticity", the parameters are + mu, lambda, and id + - For "bending energy", the parameters are + lambda, id1 and id2, such that regularisation is by + (-lambda*\grad^2 + id1)^2 + id2 + - [5] Levenberg-Marquardt regularisation + - [6] Number of Full Multigrid cycles + - [7] Number of relaxation iterations per cycle + - [8] K, such that 2^K time points are used to + generate the deformations. A value of zero + indicates a small deformation model. + - [9] code of 0, 1 or 2. + 0 - asymmetric sums of squares objective function. + 1 - symmetric sums of squares objective function. + 2 - assumes multinomial distribution, where template + encodes the means and interpolation of temlate + done using logs and softmax function. + + This is for performing a single iteration of the Dartel optimisation. + All flow fields and images are represented by single precision floating + point values. Images can be scalar fields, in which case the objective + function is the sum of squares difference. Alternatively, images can be + vector fields, in which case the objective function is the sum of squares + difference between each scalar field + the sum of squares difference + between one minus the sum of the scalar fields. + + __________________________________________________________________________ + + FORMAT v = dartel3('cgs',A, b, param) + v - the solution + A - parameterisation of 2nd derivatives + b - parameterisation of first derivatives + param - 6 parameters (settings) + - [1] Regularisation type, can take values of + - 0 Linear elasticity + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Voxel sizes + - [5][6][7] Regularisation parameters + - For "membrane energy", the parameters are + lambda, unused and id. + - For "linear elasticity", the parameters are + mu, lambda, and id + - For "bending energy", the parameters are + lambda, id1 and id2. + - [8] Tolerance. Indicates required degree of accuracy. + - [9] Maximum number of iterations. + + This is for solving a set of equations using a conjugate gradient + solver. This method is less efficient than the Full Multigrid. + v = inv(A+H)*b + A, b and v are all single precision floating point. + + __________________________________________________________________________ + + FORMAT v = dartel3('fmg',A, b, param) + v - the solution n1*n2*n3*3 + A - parameterisation of 2nd derivatives + b - parameterisation of first derivatives + param - 6 parameters (settings) + - [1] Regularisation type, can take values of + - 0 Linear elasticity + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Voxel sizes + - [5][6][7] Regularisation parameters + - For "membrane energy", the parameters are + lambda, unused and id. + - For "linear elasticity", the parameters are + mu, lambda, and id + - For "bending energy", the parameters are + lambda, id1 and id2. + - [8] Number of Full Multigrid cycles + - [9] Number of relaxation iterations per cycle + + Solve equations using a Full Multigrid method. See Press et al + for more information. + v = inv(A+H)*b + A, b and v are all single precision floating point. + + __________________________________________________________________________ + + FORMAT [y,J] = dartel3('Exp', v, param) + v - flow field + J - Jacobian. Usually a tensor field of Jacobian matrices, but can + be a field of Jacobian determinants. + param - 2 (or 3) parameters. + [1] K, the number of recursions (squaring steps), such + that exponentiation is done using an Euler-like + integration with 2^K time steps. + [2] a scaling parameter. + If there is a third parameter, and it is set to 1, then + the J will be the Jacobian determinants. + + A flow field is "exponentiated" to generate a deformation field + using a scaling and squaring approach. See the work of Arsigny + et al, or Cleve Moler's "19 Dubious Ways" papers. + + __________________________________________________________________________ + + FORMAT m = dartel3('vel2mom', v, param) + v - velocity (flow) field n1*n2*n3*3. + param - 4 parameters (settings) + - [1] Regularisation type, can take values of + - 0 Linear elasticity + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Voxel sizes + - [5][6][7] Regularisation parameters + - For "membrane energy", the parameters are + lambda, unused and id. + - For "linear elasticity", the parameters are + mu, lambda, and id + - For "bending energy", the parameters are + lambda, id1 and id2. + m - `momentum' field n1*n2*n3*3. + + Convert a flow field to a momentum field by m = H*v, where + H is the large sparse matrix encoding some form of regularisation. + v and m are single precision floating point. + + __________________________________________________________________________ + + FORMAT y3 = dartel3('comp',y1,y2) + y1, y2 - deformation fields n1*n2*n3*3. + y3 - deformation field field n1*n2*n3*3. + + Composition of two deformations y3 = y1(y2) + y1, y2 and y3 are single precision floating point. + + + + FORMAT [y3,J3] = dartel3('comp', y1, y2, J1, J2) + y1, y2 - deformation fields n1*n2*n3*3. + y3 - deformation field n1*n2*n3*3. + J1, J2 - Jacobian tensor fields n1*n2*n3*3*3. + J3 - Jacobian tensor field n1*n2*n3*3*3. + + Composition of two deformations, with their Jacobian fields. + All fields are single precision floating point. + + __________________________________________________________________________ + + FORMAT f2 = dartel3('samp', f1, y) + f1 - input image(s) n1*n2*n3*n4 + y - points to sample n1*n2*n3*3 + f2 - output image n1*n2*n3*3 + + Sample a function according to a deformation. + f2 = f1(y) + f1, f2 and y are single precision floating point. + + __________________________________________________________________________ + + FORMAT v2 = dartel3('resize', v1, dim) + v1 - input fields n1*n2*n3*n4 + v2 - output field dim1*dim2*dim3*n4 + dim - output dimensions + + Resize a field according to dimensions dim. This is + a component of the FMG approach. + + __________________________________________________________________________ + + FORMAT v3 = dartel3('brc', v1, v2) + v1, v2, v3 - flow fields n1*n2*n3*3 + + Lie Bracket. Useful for many things + e.g. Baker-Campbell-Haussdorf series expansion. + The Lie bracket is denoted by + v3 = [v1,v2] + and on scalar fields, is computed by + v3 = J1*v2 - J2*v1, where J1 and J2 are the Jacobian + tensor fields. For matrices, the Lie bracket is simply + [A,B] = A*B-B*A + + __________________________________________________________________________ + + Note that the boundary conditions are circulant throughout. + Interpolation is trilinear, except for the resize function + which uses a 2nd degree B-spline (without first deconvolving). + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DARTEL/dartel3.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `data2bids` + +```{text} + DATA2BIDS is a helper function to convert MRI, MEG, EEG, iEEG or NIRS data to the + Brain Imaging Data Structure. The overall idea is that you write a MATLAB script in + which you call this function multiple times, once for each individually recorded + data file (or data set). It will write the corresponding sidecar JSON and TSV files + for each data file. + + Use as + data2bids(cfg) + or as + data2bids(cfg, data) + + The first input argument 'cfg' is the configuration structure, which contains the + details for the (meta)data and which specifies the sidecar files you want to write. + The optional 'data' argument corresponds to preprocessed raw data according to + FT_DATAYPE_RAW or an anatomical MRI according to FT_DATAYPE_VOLUME. The optional + data input argument allows you to write preprocessed electrophysiological data + and/or realigned and defaced anatomical MRI to disk. + + The implementation in this function aims to correspond to the latest BIDS version. + See https://bids-specification.readthedocs.io/ for the full specification + and http://bids.neuroimaging.io/ for further details. + + The configuration structure should contains + cfg.method = string, can be 'decorate', 'copy' or 'convert', see below (default is automatic) + cfg.dataset = string, filename of the input data + cfg.outputfile = string, optional filename for the output data (default is automatic) + cfg.writejson = string, 'yes', 'replace', 'merge' or 'no' (default = 'yes') + cfg.writetsv = string, 'yes', 'replace', 'merge' or 'no' (default = 'yes') + + This function starts from existing data file on disk or from a FieldTrip compatible + data structure in MATLAB memory that is passed as the second input argument. + Depending on cfg.method it will add the sidecar files, copy the dataset and add + sidecar files, or convert the dataset and add the sidecar files. Each of the + methods is discussed here. + + DECORATE - data2bids will read the header details and events from the data and write + the appropriate sidecar files alongside the existing dataset. You would use this to + obtain the sidecar files for data files that are already in the BIDS organization. + + CONVERT - data2bids will read the input data (or use the specified input data) and + write it to a new output file that is BIDS compliant. The output format is NIfTI + for MRI data, and BrainVision for EEG and iEEG. Note that MEG data files are stored + in BIDS in their native format and this function will NOT convert them for you. + + COPY - data2bids will copy the data from the input data file to the output data + file, which renames it, but does not change its content. Furthermore, it will read + the header details and events from the data and construct the appropriate sidecar + files. + + Although you can explicitly specify cfg.outputfile yourself, it is recommended to + use the following configuration options. This results in a BIDS compliant output + directory and file name. With these options data2bids will also write or, if + already present, update the participants.tsv and scans.tsv files. + cfg.bidsroot = string, top level directory for the BIDS output + cfg.sub = string, subject name + cfg.ses = string, optional session name + cfg.run = number, optional + cfg.task = string, task name is required for functional data + cfg.suffix = string, can be any of 'FLAIR', 'FLASH', 'PD', 'PDT2', 'PDmap', 'T1map', 'T1rho', 'T1w', 'T2map', 'T2star', 'T2w', 'angio', 'audio', 'bold', 'bval', 'bvec', 'channels', 'coordsystem', 'defacemask', 'dwi', 'eeg', 'emg', 'epi', 'events', 'eyetracker', 'fieldmap', 'headshape', 'ieeg', 'inplaneT1', 'inplaneT2', 'magnitude', 'magnitude1', 'magnitude2', 'meg', 'motion', 'nirs', 'phase1', 'phase2', 'phasediff', 'photo', 'physio', 'sbref', 'stim', 'video' + cfg.acq = string + cfg.ce = string + cfg.rec = string + cfg.dir = string + cfg.mod = string + cfg.echo = string + cfg.proc = string + cfg.tracksys = string + cfg.space = string + cfg.desc = string + + If you specify cfg.bidsroot, this function will also write the dataset_description.json + file. Among others, you can specify the following fields: + cfg.dataset_description.writesidecar = 'yes' or 'no' (default = 'yes') + cfg.dataset_description.Name = string + cfg.dataset_description.BIDSVersion = string + cfg.dataset_description.License = string + cfg.dataset_description.Authors = cell-array of strings + cfg.dataset_description.ReferencesAndLinks = cell-array of strings + cfg.dataset_description.EthicsApprovals = cell-array of strings + cfg.dataset_description.Funding = cell-array of strings + cfg.dataset_description.Acknowledgements = string + cfg.dataset_description.HowToAcknowledge = string + cfg.dataset_description.DatasetDOI = string + + If you specify cfg.bidsroot, you can also specify additional information to be + added as extra columns in the participants.tsv and scans.tsv files. For example: + cfg.participants.age = scalar + cfg.participants.sex = string, 'm' or 'f' + cfg.scans.acq_time = string, should be formatted according to RFC3339 as '2019-05-22T15:13:38' + cfg.sessions.acq_time = string, should be formatted according to RFC3339 as '2019-05-22T15:13:38' + cfg.sessions.pathology = string, recommended when different from healthy + If any of these values is specified as [] or as nan, it will be written to + the tsv file as 'n/a'. + + If you specify cfg.bidsroot, this function can also write some modality agnostic + files at the top-level of the dataset. You can specify their content here and/or + subsequently edit them with a text editor. + cfg.README = string (default is a template with instructions) + cfg.LICENSE = string (no default) + cfg.CHANGES = string (no default) + + General BIDS options that apply to all data types are + cfg.InstitutionName = string + cfg.InstitutionAddress = string + cfg.InstitutionalDepartmentName = string + cfg.Manufacturer = string + cfg.ManufacturersModelName = string + cfg.DeviceSerialNumber = string + cfg.SoftwareVersions = string + + General BIDS options that apply to all functional data types are + cfg.TaskName = string + cfg.TaskDescription = string + cfg.Instructions = string + cfg.CogAtlasID = string + cfg.CogPOID = string + + For anatomical and functional MRI data you can specify cfg.dicomfile to read the + detailed MRI scanner and sequence details from the header of that DICOM file. This + will be used to fill in the details of the corresponding JSON file. + cfg.dicomfile = string, filename of a matching DICOM file for header details (default = []) + cfg.deface = string, 'yes' or 'no' (default = 'no') + + You can specify cfg.events as a Nx3 matrix with the "trl" trial definition (see + FT_DEFINETRIAL) or as a MATLAB table. When specified as table, you can use the + "trl" format from FT_DEFINETRIAL with the first three columns corresponding to the + begsample, endsample and offset (in samples). You can also a table with the + "events.tsv" format with the first two columns corresponding to the onset and + duration (in seconds). In either case the table can have additional columns with + numerical or string values. If you do not specify cfg.events, the events will be + read from the MEG/EEG/iEEG dataset. + cfg.events = trial definition (see FT_DEFINETRIAL) or event structure (see FT_READ_EVENT) + + If NBS Presentation was used in combination with another functional data type, you + can specify cfg.presentationfile with the name of the presentation log file, which + will be aligned with the data based on triggers (MEG/EEG/iEEG) or based on the + volumes (fMRI). Events from the presentation log file will also be written to + events.tsv. To indicate how triggers (in MEG/EEG/iEEG) or volumes (in fMRI) match + the presentation events, you should specify the mapping between them. + cfg.presentationfile = string, optional filename for the presentation log file + cfg.trigger.eventtype = string (default = []) + cfg.trigger.eventvalue = string or number + cfg.trigger.skip = 'last'/'first'/'none' + cfg.presentation.eventtype = string (default = []) + cfg.presentation.eventvalue = string or number + cfg.presentation.skip = 'last'/'first'/'none' + + For EEG and iEEG data you can specify an electrode definition according to + FT_DATATYPE_SENS as an "elec" field in the input data, or you can specify it as + cfg.elec or you can specify a filename with electrode information. + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + + For NIRS data you can specify an optode definition according to + FT_DATATYPE_SENS as an "opto" field in the input data, or you can specify + it as cfg.opto or you can specify a filename with optode information. + cfg.opto = structure with optode positions or filename,see FT_READ_SENS + + There are more BIDS options for the mri/meg/eeg/ieeg data type specific sidecars. + Rather than listing them all here, please open this function in the MATLAB editor, + and scroll down a bit to see what those are. In general the information in the JSON + files is specified by a field that is specified in CamelCase + cfg.mri.SomeOption = string, please check the MATLAB code + cfg.meg.SomeOption = string, please check the MATLAB code + cfg.eeg.SomeOption = string, please check the MATLAB code + cfg.ieeg.SomeOption = string, please check the MATLAB code + cfg.nirs.SomeOption = string, please check the MATLAB code + cfg.coordsystem.SomeOption = string, please check the MATLAB code + The information for TSV files is specified with a column header in lowercase or + snake_case and represents a list of items + cfg.channels.some_option = cell-array, please check the MATLAB code + cfg.events.some_option = cell-array, please check the MATLAB code + cfg.electrodes.some_option = cell-array, please check the MATLAB code + cfg.optodes.some_option = cell-array, please check the MATLAB code + + See also FT_DATAYPE_RAW, FT_DATAYPE_VOLUME, FT_DATATYPE_SENS, FT_DEFINETRIAL, + FT_PREPROCESSING, FT_READ_MRI, FT_READ_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/data2bids.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `dccnpath` + +```{text} + DCCNPATH manages the filename and path for test files. It helps to locate and read + test file from Linux, Windows or macOS computers both inside and outside the DCCN. + + Use as + filename = dccnpath(filename) + where the input filename corresponds to the test data on the DCCN cluster and the + output filename corresponds to the local file including the full path where the + test data is available. + + The test data location on the DCCN cluster is '/home/common/matlab/fieldtrip/data' + and the specification of the input filename MUST start with this. + + This function will search-and-replace the location on the DCCN cluster by the + location that applies to your computer. If needed, it will replace '/home' by 'H:' + and will replace forward by backward slashes. + + In case you have a local copy of the data, or if you are inside the DCCN and have + mounted the '/home' drive on another letter than 'H:', you should override the + default location using + global ft_default + ft_default.dccnpath = '/your/copy'; + + If you DO HAVE a local copy, it should contain a directory with the name 'ftp'. The + content of the ftp directory should match that on the FieldTrip download server, + for example '/your/copy/ftp/test/ctf'. + + If you DO NOT have a local copy and do not define ft_default.dccnpath manually, + then this function will automatically try to download the publicly available data + to a temporary directory. + + See also WHICH, WEBSAVE + Copyright (C) 2012-2024, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL + + 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 . + + $Id$ + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/dccnpath.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `dcm_fit_finger` + +```{text} + Fit DCM model to finger data + FORMAT [DCM] = dcm_fit_finger(yy,M,U,m) + + yy - yy{n} for nth trial data + M - model structure + U - input structure + m - PIF order + + DCM - o/p data structure + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/man/example_scripts/dcm_fit_finger.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `det2x2` + +```{text} + DET2X2 computes determinant of matrix x, using explicit analytic definition + if size(x,1) < 4, otherwise use MATLAB det-function + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/det2x2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `det3x3` + +```{text} + DET3X3 computes determinant of matrix x, using explicit analytic definition + if size(x) = [3 3 K M] + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/det3x3.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `edf2fieldtrip` + +```{text} + EDF2FIELDTRIP reads data from a EDF file with channels that have a different + sampling rates. It upsamples all data to the highest sampling rate and + concatenates all channels into a raw data structure that is compatible with the + output of FT_PREPROCESSING. + + Use as + data = edf2fieldtrip(filename) + or + [data, event] = edf2fieldtrip(filename) + + For reading EDF files in which all channels have the same sampling rate, you can + use the standard procedure with FT_DEFINETRIAL and FT_PREPROCESSING. + + See also FT_PREPROCESSING, FT_DEFINETRIAL, FT_REDEFINETRIAL, + FT_READ_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/edf2fieldtrip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `end2end_attention` + +```{text} + End-to-end test for attention dataset + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/tests/end2end_attention.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `end2end_restingfMRI` + +```{text} + End-to-end test for resting dataset + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/tests/end2end_restingfMRI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `estimate_greens_mmclab` + +```{text} + Estimate Green's function of the photon fluence by simulating photon + migration through the head and brain using the MMCLAB software + + This function provides input parameters to perform the Monte Carlo + simulation. Output of MMCLAB, Green's function, is then saved as data + format to be used in DCM-fNIRS analysis. + + Following software and Brain atlas are required: + MMCLAB: http://mcx.sourceforge.net/cgi-bin/index.cgi?MMC/Doc/MMCLAB + iso2mesh: http://iso2mesh.sourceforge.net/cgi-bin/index.cgi + Brain atlas mesh: http://mcx.sourceforge.net/cgi-bin/index.cgi?MMC/Colin27AtlasMesh + Collin 27 average brain: http://www.bic.mni.mcgill.ca/ServicesAtlases/Colin27 + + FORMAT [G] = estimate_greens_mmclab(F, P) + + G Green's function of the photon fluence + + F names of files required to use MMClab software + P optical parameters for Monte Carlo simulation + + -------------------------------------------------------------------------- + F.mmc name of directory of MMCLAB (eg, /mmclab) + F.isomesh name of directory of iso2mesh (eg, /iso2mesh) + F.mesh file name of brain atlas mesh (eg, MMC_Collins_Atlas_Mesh_Version_2L.mat) + F.atlas file name of Collin 27 brain (eg, colin27_t1_tal_lin.nii) + F.sdpos file name of MNI locations of optical source and detectors + If F is not specified, files are selected using GUI. + -------------------------------------------------------------------------- + P optical parameters for Monte Carlo simulation + if this is not specified, optical parameters for 750 + nm and 850 nm are used. + -------------------------------------------------------------------------- + G.s - estimated Green's function from sensor (light emitter) positions + into source positions [# sensor x # voxels x # wavelengths] + G.d - estimated Green's function from sensor (light detector) positions + into source positions [# sensor x # voxels x # wavelengths] + G.xyz - MNI locations [3 x # voxels] + G.elem - tissue types of voxels [3 x # voxels] + 1-scalp, 2-CSF, 3-gray matter, 4-white matter + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/dcm_fnirs/mmclab/estimate_greens_mmclab.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `expmall` + +```{text} + expmall is a function. + dx = expmall(J, f, t, EP) + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/expmall.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fieldtrip2besa` + +```{text} + FIELDTRIP2BESA saves a FieldTrip data structures to a corresponding BESA file. This + export function is based on documentation that was provided by Todor Jordanov of + BESA. + + Use as + fieldtrip2besa(filename, data) + with data as obtained from FT_PREPROCESSING to export single trial data as a + set of .avr files. + + Use as + fieldtrip2besa(filename, elec) + or + fieldtrip2besa(filename, grad) + with an electrode structure as obtained from FT_READ_SENS to export channel + positions to an .elp file. + + Additional key-value pairs can be specified according to + channel = cell-array, can be used to make subset and to reorder the channels + + See also FIELDTRIP2SPSS, FIELDTRIP2FIFF + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fieldtrip2besa.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fieldtrip2bis` + +```{text} + FIELDTRIP2BIS writes BioImage Suite .mgrid files with eletrode + positions in 'xyz' coordinates using a elec datatype structure and the + corresponding MRI volume + + Use as + fieldtrip2bis('Subject_grid.mgrid', elec, 'Subject_MR.nii') + + See also BIS2FIELDTRIP, FT_WRITE_SENS, WRITE_BIOIMAGE_MGRID + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fieldtrip2bis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fieldtrip2ctf` + +```{text} + FIELDTRIP2CTF saves a FieldTrip data structure to a CTF dataset. + + The file to which the data is exported depends on the input data structure that you + provide. The "raw" and "timelock" structures can be exported to a CTF dataset. The + "montage" structure can be exported to a CTF "Virtual Channels" file. + + Use as + fieldtrip2ctf(filename, data, ...) + where filename is a string and data is a FieldTrip raw, timelock or montage + structure. + + Additional options should be specified in key-value pairs and can be + 'ds' = struct, original dataset information as obtained with readCTFds + + See also FT_DATATYPE, FT_APPLY_MONTAGE, FT_VOLUMEWRITE, FT_SOURCEWRITE, FT_WRITE_DATA + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fieldtrip2ctf.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fieldtrip2fiff` + +```{text} + FIELDTRIP2FIFF saves a FieldTrip raw data structure as a fiff-file, allowing it + to be further analyzed by the Neuromag/Elekta/Megin software, or in MNE-python. + + Use as + fieldtrip2fiff(filename, data) + where filename is the name of the output file, and data is a raw data structure + as obtained from FT_PREPROCESSING, or a timelock structure obtained from + FT_TIMELOCKANALYSIS. If the input data is a raw data structure with a single + trial, a continuous fif-file will be written. If the input data contains multiple + trials, either in a timelock or raw format, and epoched fif-file will be written. + If trials have different time axes, nans will be added to pad the trials to equal + length and time axis. If the input data contains an average across trials, an evoked + fif-file will be written. + + Additional options can be specified as key-value pairs: + precision = string ('single'/'double'), determines the precision with which the + numeric data is written to file, default is the class of the data. + coordsys = string ('native'/'neuromag'), determines the coordinate system in which + the MEG sensors are written (default = 'neuromag'). In case of + 'neuromag' the MEG sensors are expressed in (approximate) neuromag + coordinates, which may facilitate downstream handling of the fif-files + in other software such as MNE-python. This is according to the + official fif-file format definition. This option does not have an + effect on EEG electrodes or fNIRS optodes. + event = structure as obtained from FT_READ_EVENT, note that the sampling in the + event structure should be the same as the sampling of the data structure, + i.e. the values in data.sampleinfo should be in line with event.sample, and + the sampling rate should be the same. No check will be performed. Also, the + events will only be written to file if the input data is of type raw with + a single trial. + eventtype = string or cell array of string with the event types to be + written to the continuous fif-file (default is all) + hdr = structure as obtained from FT_READ_HEADER + + If present in the data, the original header is reused (also removing the non-used channels). + Otherwise, the function attempts to create the header, which might or might not be correct + (e.g. with respect to the scaling and the sensor locations). + + The events are written in MNE format (three columns) into the continuous + fif-file, with a mapping string that allows for a richer interpretation of the events. + + See also FT_DATATYPE_RAW, FT_DATATYPE_TIMELOCK + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fieldtrip2fiff.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fieldtrip2homer` + +```{text} + FIELDTRIP2HOMER converts a continuous raw data structure from FieldTrip format to + Homer format. + + Use as + nirs = fieldtrip2homer(data, ...) + where the input data structure is formatted according to the output of + FT_PREPROCESSING and the output nirs structure is according to Homer. + + Additional options should be specified in key-value pairs and can be + 'event' = event structure that corresponds to the data, see FT_READ_EVENT + + See https://www.nitrc.org/plugins/mwiki/index.php/homer2:Homer_Input_Files#NIRS_data_file_format + for a description of the Homer data structure. + + See also HOMER2FIELDTRIP, FT_PREPROCESSING, FT_DATATYPE_RAW + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fieldtrip2homer.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fieldtrip2spss` + +```{text} + FIELDTRIP2SPSS compiles data and correpsonding labels into a textfile, + suitable for importing into SPSS or JASP (jasp-stats.org). + + Use as + fieldtrip2spss(filename, labels, data) + + When exporting from MATLAB, set: + - filename; should be string (e.g. 'counts.txt') + - labels; should be a cell-array (e.g. {'ones', 'twos', 'threes'}) + - data; should be either a vector or matrix (e.g. [1 2 3; 1 2 3; 1 2 3]) + + When importing to SPSS, set; + - variables included at top of file: 'yes' + - first case of data on line number: '2' (default) + - delimiter appearing between variables: 'tab' (default) + + In case the columns that make up the data matrix have unequal lengths + (e.g. because of different number of subjects per group), use: + data = ones(30,2)*9999 + data(1:30,1) = 1 (30 subj in Group 1) + data(1:20,2) = 2 (20 subj in Group 2) + After importing to SPSS, click the Missing cell in the Variable View + window and enter 9999 as the missing value definition. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fieldtrip2spss.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_copy_tree` + +```{text} + fiff_copy_tree(fidin, in_id, nodes, fidout) + + Copies directory subtrees from fidin to fidout + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_copy_tree.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_define_constants` + +```{text} + Authors: Alexandre Gramfort + Matti Hämäläinen + + License: BSD-3-Clause + Copyright the MNE-Python contributors. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_define_constants.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_dir_tree_find` + +```{text} + [nodes] = fiff_dir_tree_find(tree,kind) + + Find nodes of the given kind from a directory tree structure + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_dir_tree_find.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_end_block` + +```{text} + fiff_end_block(fid, kind) + + Writes a FIFF_BLOCK_END tag + + fid An open fif file descriptor + kind The block kind to end + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_end_block.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_end_file` + +```{text} + fiff_end_file(fid) + + Writes the closing tags to a fif file and closes the file + + fid An open fif file descriptor + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_end_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_find_evoked` + +```{text} + [data_sets] = fiff_find_evoked(fname) + + Find all evoked data sets in a fif file and create a list of descriptors + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_find_evoked.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_finish_writing_raw` + +```{text} + function fiff_finish_writing_raw(fid) + + fid of an open raw data file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_finish_writing_raw.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_invert_transform` + +```{text} + [itrans] = fiff_invert_transform(trans) + + Invert a coordinate transformation + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_invert_transform.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_list_dir_tree` + +```{text} + fiff_list_dir_tree(fid, tree) + + List the fiff directory tree structure + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_list_dir_tree.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_make_ch_rename` + +```{text} + fiff_make_ch_rename is a function. + ch_rename = fiff_make_ch_rename(chs) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_make_ch_rename.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_make_dir_tree` + +```{text} + [tree, last] = fiff_make_dir_tree(fid,dir,start,indent) + + Create the directory tree structure + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_make_dir_tree.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_open` + +```{text} + [fid, tree, dir] = fiff_open(fname) + + Open a fif file and provide the directory of tags + + fid the opened file id + tree tag directory organized into a tree + dir the sequential tag directory + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_open.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_pick_channels` + +```{text} + [sel] = fiff_pick_channels(ch_names,include,exclude) + + Make a selector to pick desired channels from data + + ch_names - The channel name list to consult + include - Channels to include (if empty, include all available) + exclude - Channels to exclude (if empty, do not exclude any) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_pick_channels.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_pick_channels_evoked` + +```{text} + [res] = fiff_pick_channels_evoked(orig,include,exclude) + + Pick desired channels from evoked-response data + + orig - The original data + include - Channels to include (if empty, include all available) + exclude - Channels to exclude (if empty, do not exclude any) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_pick_channels_evoked.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_pick_info` + +```{text} + [res] = fiff_pick_info(info,sel) + + Pick desired channels from measurement info + + res - Info modified according to sel + info - The original data + sel - List of channels to select + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_pick_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_pick_types` + +```{text} + [sel] = fiff_pick_types(info,meg,eeg,stim,exclude) + + Create a selector to pick desired channel types from data + + info - The measurement info + meg - Include MEG channels + eeg - Include EEG channels + stim - Include stimulus channels + include - Additional channels to include (if empty, do not add any) + exclude - Channels to exclude (if empty, do not exclude any) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_pick_types.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_pick_types_evoked` + +```{text} + [res] = fiff_pick_types_evoked(orig,meg,eeg,stim,include,exclude) + + Pick desired channels types from evoked-response data + + orig - The original data + meg - Include MEG channels + eeg - Include EEG channels + stim - Include stimulus channels + include - Additional channels to include (if empty, do not add any) + exclude - Channels to exclude (if empty, do not exclude any) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_pick_types_evoked.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_bad_channels` + +```{text} + [bads] = fiff_read_bad_channels(fid,node[,ch_rename]) + + Reas the bad channel list from a node if it exists + + fid - The file id + node - The node of interes + ch_rename - Short-to-long channel name mapping + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_bad_channels.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_coord_trans` + +```{text} + usage: [trans_head2mri] = fiff_read_coord_trans(transfile) + + input: + transfile = name of transformation fif file (usually stored in + the subject's Freesurfer directory in /mri/T1-neuromag/sets). + + output: + trans_head2mri = transformation structure from head to MRI coordinate systems. + + Note: the inverse transformation, from MRI to head coordinate systems + can be obtained by just taking the inverse: + trans_mri2head.from=5; trans_mri2head.to=4; + trans_mri2head.trans=inv(trans_head2mri.trans); + + author: Rey Ramirez email: rrramir@uw.edu + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_coord_trans.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_ctf_comp` + +```{text} + [ compdata ] = fiff_read_ctf_comp(fid,node,chs,ch_rename) + + Read the CTF software compensation data from the given node + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_ctf_comp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_epochs` + +```{text} + [epochs] = fiff_read_epochs(fname,setno) + + Read epochs from file + + + Author : Martin Luessi, MGH Martinos Center + License : BSD 3-clause + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_epochs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_events` + +```{text} + [events, mappings] = fiff_read_events(source, tree) + + Read the events + + If tree is specified, source is assumed to be an open file id, + otherwise a the name of the file to read. If tree is missing, the + meas output argument should not be specified. + + + Author : Martin Luessi, MGH Martinos Center + License : BSD 3-clause + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_events.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_evoked` + +```{text} + [data] = fiff_read_evoked(fname,setno) + + Read one evoked data set + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_evoked.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_evoked_all` + +```{text} + [data] = fiff_read_evoked_all(fname) + + Read all evoked data set (averages only) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_evoked_all.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_extended_ch_info` + +```{text} + fiff_read_extended_ch_info is a function. + [chs, ch_rename] = fiff_read_extended_ch_info(chs, meas_info, fid) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_extended_ch_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_hpi_result` + +```{text} + [ res ] = fiff_read_hpi_result(name) + + Read the HPI result block from a measurement file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_hpi_result.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_meas_info` + +```{text} + [info,meas] = fiff_read_meas_info(source,tree) + + Read the measurement info + + If tree is specified, source is assumed to be an open file id, + otherwise a the name of the file to read. If tree is missing, the + meas output argument should not be specified. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_meas_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_mri` + +```{text} + [stack] = fiff_read_mri(fname,read_data) + + read_data argument is optional, if set to false the pixel data are + not read. The default is to read the pixel data + + Read a fif format MRI description file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_mri.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_named_matrix` + +```{text} + [mat] = fiff_read_named_matrix(fid,node) + + Read named matrix from the given node + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_named_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_proj` + +```{text} + [ projdata ] = fiff_read_proj(fid,node,ch_rename) + + Read the SSP data under a given directory node + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_proj.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_raw_segment` + +```{text} + [data,times] = fiff_read_raw_segment(raw,from,to,sel) + + Read a specific raw data segment + + raw - structure returned by fiff_setup_read_raw + from - first sample to include. If omitted, defaults to the + first sample in data + to - last sample to include. If omitted, defaults to the last + sample in data + sel - optional channel selection vector + + data - returns the data matrix (channels x samples) + times - returns the time values corresponding to the samples (optional) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_raw_segment.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_raw_segment_times` + +```{text} + [data,times] = fiff_read_raw_segment_times(raw,from,to) + + Read a specific raw data segment + + raw - structure returned by fiff_setup_read_raw + from - starting time of the segment in seconds + to - end time of the segment in seconds + sel - optional channel selection vector + + data - returns the data matrix (channels x samples) + times - returns the time values corresponding to the samples (optional) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_raw_segment_times.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_tag` + +```{text} + [tag] = fiff_read_tag(fid,pos) + + Read one tag from a fif file. + if pos is not provided, reading starts from the current file position + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_tag.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_read_tag_info` + +```{text} + [fid,dir] = fiff_open(fname) + + Open a fif file and provide the directory of tags + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_read_tag_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_rename_comp` + +```{text} + fiff_rename_comp is a function. + comp = fiff_rename_comp(comp, ch_rename) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_rename_comp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_rename_list` + +```{text} + fiff_rename_list is a function. + lst = fiff_rename_list(lst, ch_rename) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_rename_list.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_reset_ch_pos` + +```{text} + [res] = fiff_reset_ch_pos(chs) + + Reset channel position data to their original values as listed in + the fif file + + NOTE: Only the coil_trans field is modified by this routine, not + loc which remains to reflect the original data read from the fif file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_reset_ch_pos.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_setup_read_raw` + +```{text} + [data] = fiff_setup_read_raw(fname,allow_maxshield) + + Read information about raw data file + + fname Name of the file to read + allow_maxshield Accept unprocessed MaxShield data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_setup_read_raw.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_split_name_list` + +```{text} + [names] = fiff_split_name_list(list) + + + Split a name list containing colon-separated entries into a cell array + containing the strings + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_split_name_list.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_start_block` + +```{text} + fiff_start_block(fid,kind) + + Writes a FIFF_BLOCK_START tag + + fid An open fif file descriptor + kind The block kind to start + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_start_block.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_start_file` + +```{text} + [fid] = fiff_start_file(name) + + Opens a fif file for writing and writes the compulsory header tags + + name The name of the file to open. It is recommended + that the name ends with .fif + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_start_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_start_writing_raw` + +```{text} + function [fid,cals] = fiff_start_writing_raw(name,info,sel) + + name filename + info The measurement info block of the source file + sel Which channels will be included in the output file (optional) + precision Numeric precision with which the data will be written + (optional). Default 'single', can also be 'double' + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_start_writing_raw.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_transform_eeg_chs` + +```{text} + [res, count] = fiff_transform_eeg_chs(chs,trans) + + Move to another coordinate system in EEG channel channel info + Count gives the number of channels transformed + + NOTE: Only the eeg_loc field is modified by this routine, not + loc which remains to reflect the original data read from the fif file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_transform_eeg_chs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_transform_meg_chs` + +```{text} + [res, count] = fiff_transform_meg_chs(chs,trans) + + Move to another coordinate system in MEG channel channel info + Count gives the number of channels transformed + + NOTE: Only the coil_trans field is modified by this routine, not + loc which remains to reflect the original data read from the fif file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_transform_meg_chs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_ch_info` + +```{text} + fiff_write_ch_info(fid,ch) + + Writes a channel information record to a fif file + + fid An open fif file descriptor + ch The channel information structure to write + + The type, cal, unit, and pos members are explained in Table 9.5 + of the MNE manual + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_ch_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_ch_infos` + +```{text} + fiff_write_ch_infos is a function. + cals = fiff_write_ch_infos(fid, chs, reset_range, ch_rename) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_ch_infos.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_complex` + +```{text} + fiff_write_complex(fid,kind,data) + + Writes a single-precision complex tag to a fif file + + fid An open fif file descriptor + kind Tag kind + data The data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_complex.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_complex_matrix` + +```{text} + fiff_write_complex_matrix(fid,kind,mat) + + Writes a single-precision complex matrix tag + + fid An open fif file descriptor + kind The tag kind + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_complex_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_coord_trans` + +```{text} + fiff_write_coord_trans(fid,trans) + + Writes a coordinate transformation structure + + fid An open fif file descriptor + trans The coordinate transfomation structure + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_coord_trans.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_ctf_comp` + +```{text} + fiff_write_ctf_comp(fid,comps,ch_rename) + + Writes the CTF compensation data into a fif file + + fid An open fif file descriptor + comps The compensation data to write + ch_rename Short-to-long channel name mapping + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_ctf_comp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_dau16` + +```{text} + fiff_write_dau16(fid, kind, data) + + Writes a 16-bit integer tag to a fif file + + fid An open fif file descriptor + kind Tag kind + data The integers to use as data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_dau16.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_dig_file` + +```{text} + 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) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_dig_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_dig_point` + +```{text} + fiff_write_dig_point(fid,dig) + + Writes a digitizer data point into a fif file + + fid An open fif file descriptor + dig The point to write + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_dig_point.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_double` + +```{text} + fiff_write_int(fid,kind,data) + + Writes a double-precision floating point tag to a fif file + + fid An open fif file descriptor + kind Tag kind + data The data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_double.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_double_complex` + +```{text} + fiff_write_double_complex(fid,kind,data) + + Writes a double-precision complex tag to a fif file + + fid An open fif file descriptor + kind Tag kind + data The data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_double_complex.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_double_complex_matrix` + +```{text} + fiff_write_double_complex_matrix(fid,kind,mat) + + Writes a double-precision complex matrix tag + + fid An open fif file descriptor + kind The tag kind + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_double_complex_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_double_matrix` + +```{text} + fiff_write_double_matrix(fid,kind,mat) + + Writes a double-precision floating-point matrix tag + + fid An open fif file descriptor + kind The tag kind + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_double_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_epochs` + +```{text} + function fiff_write_epochs(name,data) + + name filename + data the data structure returned from fiff_write_evoked + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_epochs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_events` + +```{text} + fiff_write_events(filename,eventlist,mappings) + + Write an event list into a fif file, and include an optional description + of the event ids. This function has been adjusted by Jan Mathijs Schoffelen + from mne_write_events, with the intention to make a writing function that + is symmetric in its behavior w.r.t. fiff_read_events (which can read the + mappings). The filename argument can be a string, or a file identifier to + an open (for writing) fif-file. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_events.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_evoked` + +```{text} + function fiff_write_evoked(name,data,datatype) + + name filename + data the data structure returned from fiff_read_evoked + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_evoked.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_float` + +```{text} + fiff_write_float(fid,kind,data) + + Writes a single-precision floating point tag to a fif file + + fid An open fif file descriptor + kind Tag kind + data The data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_float.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_float_matrix` + +```{text} + fiff_write_float_matrix(fid,kind,mat) + + Writes a single-precision floating-point matrix tag + + fid An open fif file descriptor + kind The tag kind + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_float_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_float_sparse_ccs` + +```{text} + fiff_write_float_sparsce_ccs(fid,kind,mat) + + Writes a single-precision sparse (ccs) floating-point matrix tag + + fid An open fif file descriptor + kind The tag kind + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_float_sparse_ccs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_float_sparse_rcs` + +```{text} + fiff_write_float_sparsce_rcs(fid,kind,mat) + + Writes a single-precision sparse (RCS) floating-point matrix tag + + fid An open fif file descriptor + kind The tag kind + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_float_sparse_rcs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_id` + +```{text} + fiff_write_id(fid,kind,id) + + Writes fiff id + + fid An open fif file descriptor + kind The tag kind + id The id to write + + If the id argument is missing it will be generated here + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_id.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_int` + +```{text} + fiff_write_int(fid,kind,data) + + Writes a 32-bit integer tag to a fif file + + fid An open fif file descriptor + kind Tag kind + data The integers to use as data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_int.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_int_matrix` + +```{text} + fiff_write_int_matrix(fid,kind,mat) + + Writes a integer matrix tag + + fid An open fif file descriptor + kind The tag kind + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_int_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_name_list` + +```{text} + fiff_write_name_list(fid,kind,mat) + + Writes a colon-separated list of names + + fid An open fif file descriptor + kind The tag kind + data An array of names to create the list from + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_name_list.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_named_matrix` + +```{text} + fiff_write_named_matrix(fid,kind,mat) + + Writes a named single-precision floating-point matrix + + fid An open fif file descriptor + kind The tag kind to use for the data + mat The data matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_named_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_proj` + +```{text} + fiff_write_proj(fid,projs,ch_rename) + + Writes the projection data into a fif file + + fid An open fif file descriptor + projs The compensation data to write + ch_rename Short-to-long channel name mapping + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_proj.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_raw_buffer` + +```{text} + function fiff_write_raw_buffer(fid,buf,cals,datatype) + + fid of an open raw data file + buf the buffer to write + cals calibration factors + datatype (optional) datatype to write, default float + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_raw_buffer.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_raw_segment` + +```{text} + FIFF_WRITE_RAW_SEGMENT Write chunck of raw data to disk + [] = FIFF_WRITE_RAW_SEGMENT(FNAME, RAW, FROM, TO, SEL) + + The functions reads data from a file specified by raw + which is obtained with fiff_setup_read_raw + + fname - the name of the file where to write + raw - structure returned by fiff_setup_read_raw + from - first sample to include. If omitted, defaults to the + first sample in data + to - last sample to include. If omitted, defaults to the last + sample in data + sel - optional channel selection vector + drop_small_buffer - optional bool to say if the last data buffer is dropped + to make sure all buffers have the same size + (required by maxfilter) + buffer_size - float (size of data buffers) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_raw_segment.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_raw_segment_times` + +```{text} + FIFF_WRITE_RAW_SEGMENT_TIMES Write chunck of raw data to disk + [] = FIFF_WRITE_RAW_SEGMENT_TIMES(FNAME, RAW, FROM, TO, SEL) + + The functions reads data from a file specified by raw + which is obtained with fiff_setup_read_raw + + fname - the name of the file where to write + raw - structure returned by fiff_setup_read_raw + from - starting time of the segment in seconds + to - end time of the segment in seconds + sel - optional channel selection vector + drop_small_buffer - optional bool to say if the last data buffer is dropped + to make sure all buffers have the same size + (required by maxfilter) + buffer_size_sec - float (size of data buffers in seconds) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_raw_segment_times.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_short` + +```{text} + fiff_write_short(fid, kind, data) + + Writes a 16-bit integer tag to a fif file + + fid An open fif file descriptor + kind Tag kind + data The integers to use as data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_short.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fiff_write_string` + +```{text} + fiff_write_string(fid,kind,data) + + Writes a string tag + + fid An open fif file descriptor + kind The tag kind + data The string data to write + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/fiff_write_string.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_fit` + +```{text} + Bohning bound CCA stuff + FORMAT [mod,Z,V] = fil_fit(F,sett,ind,p,mod,Z,Z0,P0) + F{l} - Nvox x M x N + ind - N x L + p - N x 1 + mod(l).mu - Nvox x M + mod(l).W - Nvox x M x K + Z - K x N + Z0 - K x N + P0 - K x K + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_fit.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_install` + +```{text} + Download files required for Factorisation-based Image Labelling + FORMAT [mufile,filfile] = fil_install(datadir) + + https://figshare.com/projects/Factorisation-based_Image_Labelling/128189 + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_install.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_io` + +```{text} + Function handles for I/O, used by fil_train + FORMAT io = fil_io + io - Structure of function handles + io.init - initialise + io.block - read in a block of data + io.patch - extract a patch from the read in block + + FORMAT dat = io.block(dat,x0,y0,z0) + dat - data structure + x0 - x indices + y0 - y indices + z0 - z indices + + FORMAT [X,J,C] = io.patch(dat,x0,y0,z0, r) + dat - data structure + x0 - x indices + y0 - y indices + z0 - z indices + r - search radius + + FORMAT dat = io.init(varargin) + varargin - arrays of input filenames containing output from + fil_push_train_data + dat - data structure + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_io.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_label` + +```{text} + Label image(s) + FORMAT files = fil_label(fil,mbsett,mbdat,iterations,vsett_scale,odir,df,Mf) + fil - a trained model (see fil_train) loaded with + fil = load('fil_blah.mat'); + mbsett - global parameters from mb toolbox registration + mbdat - subject data from mb toolbox registration + mb = load('mb_blah.mat'); + mbsett = mb.sett; + mbdat = mb.dat; + iterations - three elements containing + Number of registration Gauss-Newton updates + Number of outer iterations to update the latent vars + Number of inner iterations to update the latent vars + (defaults to [6 10 10]) + vsett_scale - scaling of the regularisation, relative to what was used + originally by the mb toolbox (defaults to 0.25) + odir - output directory name (defaults to '.') + df - dimensions of label image (optional) + Mf - voxel-to-world matrix of label image (optional) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_label.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_prec` + +```{text} + Attach matrices for computing priors + FORMAT model = fil_prec(model,sett) + model - The learned model from fil_train + sett - Settings + Uses sett.matname, sett.nu and sett.v0 + + Takes a fitted model, and converts to a form that allows the + distributions of latent variables to be estimated by a neural network + type formulation. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_prec.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_prune` + +```{text} + Prune the model + FORMAT model = fil_prune(model,sett,p) + model - The learned model from fil_train + + Take a fitted model, orthogonalise and remove irrelevent latent + variables. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_prune.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_push_train_data` + +```{text} + Generate ``modulated categorical data'' for fil training + FORMAT fil_push_train_data(dw, Mw, Niiy, Nii1) + dw - image dimensions of output + Mw - voxel-to-world mapping of output + Niiy - NIfTI data structure of deformations + Nii1 - NIfTI data structure of categorical image data to push + Note that the first dimension encodes the number of subjects + and the behaviour of the code depends on the second dimension. + * If the second dimension is 1, then the images are assumed + to be categorical labels. The output is a pcat_blah.mat file + containing a sparse matrix that encodes the pushed labels. + warped labels. + * If the second dimension is greater than 1, then the images + are assumed to encode segmentation probabilities. The output + in this case is a 4D image file. Note that the total + Number of categories is the number of dimensions + 1, accounting + for an implicit background class. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_push_train_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_subvol` + +```{text} + Dimensions and voxel-to world mapping of a subvolume + FORMAT [d,M] = fil_subvol(Nii,bb) + Nii - SPM NIfTI object + bb - bounding box (2 x 3) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_subvol.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `fil_train` + +```{text} + Fit the patch-wise CCA-like model. + FORMAT model = fil_train(data,sett,model) + data - a data structure encoding the images used, as well as the + amount of jitter etc. + sett - a data structure encoding settings. Fields used are (with suggested values): + K - Number of components to use in the model [it depends] + nit - Number of inner iterations for updating mu, W & Z [5] + nu0 - Wishart degrees of freedom: A ~ W(I v_0 + u_0, nu_0) [2] + v0 - Wishart scale parameter: A ~ W(I v_0 + u_0, nu_0) [6.0] + d1 - Patch-size (currently same in all directions) [4] + r - search radius [2 voxels] + sd - Standard deviation of weights within search radius [0.75 voxels] + nit0 - Outer iterations [8] + matname - filename for saving model [a string] + workers - Number of workers in parfor [it depends] + model - the estimated model + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/MB/fil_train.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `flattopwin` + +```{text} + Author: Paul Kienzle (2004) + This program is granted to the public domain. + + flattopwin(L, [periodic|symmetric]) + + Return the window f(w): + + f(w) = 1 - 1.93 cos(2 pi w) + 1.29 cos(4 pi w) + - 0.388 cos(6 pi w) + 0.0322cos(8 pi w) + + where w = i/(L-1) for i=0:L-1 for a symmetric window, or + w = i/L for i=0:L-1 for a periodic window. The default + is symmetric. The returned window is normalized to a peak + of 1 at w = 0.5. + + This window has low pass-band ripple, but high bandwidth. + + According to [1]: + + The main use for the Flat Top window is for calibration, due + to its negligible amplitude errors. + + [1] Gade, S; Herlufsen, H; (1987) 'Use of weighting functions in DFT/FFT + analysis (Part I)', Bruel & Kjaer Technical Review No.3. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/signal/flattopwin.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_affinecoordinates` + +```{text} + FT_AFFINECOORDINATES returns the affine coordinate transformation matrix that + converts FROM a specific head coordinate TO a specific head coordinate system. + + Use as + [transform] = ft_affinecoordinates(from, to) + + Note that translations are expressed in millimeters, therefore the geometrical data + to which this coordinate transformation is applied must also be specified in + millimeters. + + See also FT_CONVERT_COORDSYS, FT_CONVERT_UNITS, FT_HEADCOORDINATES, FT_WARP_APPLY + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_affinecoordinates.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_analysispipeline` + +```{text} + FT_ANALYSIPIPELINE reconstructs the complete analysis pipeline that was used to create + the input FieldTrip data structure. The pipeline will be visualized as a flowchart. + In the future it might be possible to output the complete pipeline as a MATLAB script + or in a specialized pipeline format like PSOM, JIST, LONI, or Taverna. + + Use as + output = ft_analysispipeline(cfg, data) + + The first cfg input contains the settings that apply to the behavior of this + particular function and the second data input argument can be the output of any + FieldTrip function, e.g. FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_SOURCEANALYSIS, + FT_FREQSTATISTICS or whatever you like. + + Alternatively, for the second data input argument you can also only give the + configuration of the processed data (for example data.cfg) instead of the full data + structure. + + The configuration options that apply to the behavior of this function are + cfg.filename = string, filename without the extension + cfg.filetype = string, can be 'matlab', 'html', 'dot' or 'prov' + cfg.feedback = string, 'no', 'text', 'gui' or 'yes', whether text and/or + graphical feedback should be presented (default = 'yes') + cfg.showinfo = string or cell-array of strings, information to display + in the GUI boxes, can be any combination of + 'functionname', 'revision', 'matlabversion', + 'computername', 'username', 'calltime', 'timeused', + 'memused', 'workingdir', 'scriptpath' (default = + 'functionname', only display function name). Can also + be 'all', show all pipeline. Please note that if you want + to show a lot of information, this will require a lot + of screen real estate. + cfg.remove = cell-array with strings, determines which objects will + be removed from the configuration prior to writing it to + file. For readibility of the script, you may want to + remove the large objectssuch as event structure, trial + definition, source positions + cfg.keepremoved = 'yes' or 'no', determines whether removed fields are + completely removed, or only replaced by a short textual + description (default = 'no') + + This function uses the nested cfg and cfg.previous that are present in + the data structure. It will use the configuration and the nested previous + configurations to climb all the way back into the tree. This funtction + will print a complete MATLAB script to screen (and optionally to file). + Furthermore, it will show an interactive graphical flowchart + representation of the steps taken during the pipeline(i). In the flowchart + you can click on one of the steps to see the configuration details of + that pipeline(i). + + Example use: + data = ft_timelocksimulation([]); + data_bl = ft_timelockbaseline([], data); + data_avg = ft_timelockanalysis([], data_bl); + ft_analysispipeline([], data_avg) + + Note that the nested cfg and cfg.previous in your data might not contain + all details that are required to reconstruct a complete and valid + analysis script. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this, the input data will be read from a *.mat file on disk. The + file should contain only a single variable, corresponding with the input structure. + + See also FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_FREQANALYSIS, FT_SOURCEANALYSIS, + FT_CONNECTIVITYANALYSIS, FT_NETWORKANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_analysispipeline.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_annotate` + +```{text} + FT_ANNOTATE returns the same output data as the user has provided as input, but allows + to add comments to that data structure. These comments are stored along with the other + provenance information and can be displayed with FT_ANALYSISPIPELINE. Adding comments + is especially useful if you have manually (i.e. in plain MATLAB) modified the data + structure, whereby some provenance information is missing. + + Use as + outdata = ft_annotate(cfg, indata) + where the input data structure can be any of the FieldTrip data structures and + the configuration structure should contain + cfg.comment = string + + 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_ANALYSISPIPELINE, FT_MATH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_annotate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_anonymizedata` + +```{text} + FT_ANONYMIZEDATA clears the value of potentially identifying fields in + the data and in the provenance information, i.e., it updates the data and + the configuration structure and history that is maintained by FieldTrip + in the cfg field. + + Use as + output = ft_anonymizedata(cfg, data) + where data is any FieldTrip data structure and cfg is a configuration + structure that should contain + cfg.keepnumeric = 'yes' or 'no', keep numeric fields (default = 'yes') + cfg.keepfield = cell-array with strings, fields to keep (default = {}) + cfg.removefield = cell-array with strings, fields to remove (default = {}) + cfg.keepvalue = cell-array with strings, values to keep (default = {}) + cfg.removevalue = cell-array with strings, values to remove (default = {}) + + The graphical user interface consists of a table that shows the name and + value of each provenance element, and whether it should be kept or + removed. Furthermore, it has a number of buttons: + - sort specify which column is used for sorting + - apply apply the current selection of 'keep' and 'remove' and hide the corresponding rows + - keep all toggle all visibe rows to 'keep' + - remove all toggle all visibe rows to 'keep' + - clear all clear all visibe rows, i.e. neither 'keep' nor 'remove' + - quit apply the current selection of 'keep' and 'remove' and exit + + 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_DEFACEVOLUME, FT_DEFACEMESH, FT_ANALYSISPIPELINE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_anonymizedata.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_appenddata` + +```{text} + FT_APPENDDATA concatenates multiple raw data structures that have been preprocessed + separately into a single raw data structure. + + Use as + data = ft_appenddata(cfg, data1, data2, data3, ...) + + The following configuration options are supported: + cfg.keepsampleinfo = 'yes', 'no', 'ifmakessense' (default = 'ifmakessense') + + If the input datasets all have the same channels, the trials will be concatenated. + This is useful for example if you have different experimental conditions, which, + besides analyzing them separately, for some reason you also want to analyze + together. The function will check for consistency in the order of the channels. If + the order is inconsistent the channel order of the output will be according to the + channel order of the first data structure in the input. + + If the input datasets have different channels, but the same number of trials, the + channels will be concatenated within each trial. This is useful for example if the + data that you want to analyze contains both MEG and EMG channels which require + different preprocessing options. + + If you concatenate trials and the data originates from the same original datafile, + the sampleinfo is consistent and you can specify cfg.keepsampleinfo='yes'. If the + data originates from different datafiles, the sampleinfo is inconsistent and does + not point to the same recording, hence you should specify cfg.keepsampleinfo='no'. + + Occasionally, the data needs to be concatenated in the trial dimension while + there's a slight discrepancy in the channels in the input data (e.g. missing + channels in one of the data structures). The function will then return a data + structure containing only the channels which are present in all inputs. + + 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. The data structure in the input file should be a + cell-array for this particular function. + + See also FT_PREPROCESSING, FT_DATAYPE_RAW, FT_APPENDTIMELOCK, FT_APPENDFREQ, + FT_APPENDSOURCE, FT_APPENDSENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_appenddata.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_appendfreq` + +```{text} + FT_APPENDFREQ concatenates multiple frequency or time-frequency data structures + that have been processed separately. If the input data structures contain different + channels, it will be concatenated along the channel direction. If the channels are + identical in the input data structures, the data will be concatenated along the + repetition dimension. + + Use as + combined = ft_appendfreq(cfg, freq1, freq2, ...) + + The configuration should contain + cfg.parameter = string, the name of the field to concatenate + + The configuration can optionally contain + cfg.appenddim = string, the dimension to concatenate over (default is automatic) + cfg.tolerance = scalar, tolerance to determine how different the frequency and/or + time axes are allowed to still be considered compatible (default = 1e-5) + + 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_FREQANALYSIS, FT_DATATYPE_FREQ, FT_APPENDDATA, FT_APPENDTIMELOCK, + FT_APPENDSENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_appendfreq.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_appendlayout` + +```{text} + FT_APPENDLAYOUT concatenates multiple layout descriptions that have been constructed + separately. + + Use as + combined = ft_appendlayout(cfg, layout1, layout2, ...) + where the input layouts result from FT_PREPARE_LAYOUT and the configuration + should contain + cfg.direction = string, 'horizontal' or 'vertical' (default = 'horizontal') + cfg.align = string, 'center', 'left', 'right', 'top' or 'bottom' (default = 'center') + cfg.distance = number, distance between layouts (default is automatic) + cfg.xscale = number, scaling to apply to input layouts along the horizontal direction (default = 1) + cfg.yscale = number, scaling to apply to input layouts along the vertical direction (default = 1) + + See also FT_PREPARE_LAYOUT, FT_LAYOUTPLOT, FT_APPENDSENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_appendlayout.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_appendsens` + +```{text} + FT_APPENDSENS concatenates multiple sensor definitions that have been processed + separately. + + Use as + combined = ft_appendsens(cfg, sens1, sens2, ...) + + A call to FT_APPENDSENS results in the label, pos and ori fields to be + concatenated, and the tra matrix to be merged. Any duplicate electrodes + will be removed. The labelold and chanposold fields are kept under the + condition that they are identical across the inputs. + + See also FT_ELECTRODEPLACEMENT, FT_ELECTRODEREALIGN, FT_DATAYPE_SENS, + FT_APPENDDATA, FT_APPENDTIMELOCK, FT_APPENDFREQ, FT_APPENDSOURCE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_appendsens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_appendsource` + +```{text} + FT_APPENDSOURCE concatenates multiple volumetric source reconstruction data + structures that have been processed separately. + + Use as + combined = ft_appendsource(cfg, source1, source2, ...) + + If the source reconstructions were computed for different ROIs or different slabs + of a regular 3D grid (as indicated by the source positions), the data will be + concatenated along the spatial dimension. + + If the source reconstructions were computed on the same source positions, but for + different frequencies and/or latencies, e.g. for time-frequency spectrally + decomposed data, the data will be concatenated along the frequency and/or time + dimension, but only of the frequency or time axes are well-behaved, i.e. all data + points along the dimension of interest should be sortable across data objects; + interleaving across data objects is not possible. + + See also FT_SOURCEANALYSIS, FT_DATATYPE_SOURCE, FT_APPENDDATA, FT_APPENDTIMELOCK, + FT_APPENDFREQ + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_appendsource.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_appendspike` + +```{text} + FT_APPENDSPIKE combines continuous data (i.e. LFP) with point-process data + (i.e. spikes) into a single large dataset. For each spike channel an + additional continuos channel is inserted in the data that contains + zeros most of the time, and an occasional one at the samples at which a + spike occurred. The continuous and spike data are linked together using + the timestamps. + + Use as + [spike] = ft_appendspike(cfg, spike1, spike2, spike3, ...) + where the input structures come from FT_READ_SPIKE, or as + [data] = ft_appendspike(cfg, data, spike1, spike2, ...) + where the first data structure is the result of FT_PREPROCESSING + and the subsequent ones come from FT_READ_SPIKE. + + See also FT_APPENDDATA, FT_PREPROCESSING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_appendspike.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_appendtimelock` + +```{text} + FT_APPENDTIMELOCK concatenates multiple timelock (ERP/ERF) data structures that + have been processed separately. If the input data structures contain different + channels, it will be concatenated along the channel direction. If the channels are + identical in the input data structures, the data will be concatenated along the + repetition dimension. + + Use as + combined = ft_appendtimelock(cfg, timelock1, timelock2, ...) + + The configuration can contain + cfg.appenddim = string, the dimension to concatenate over which to append, + this can be 'chan' and 'rpt' (default is automatic) + cfg.tolerance = scalar, tolerance to determine how different the time axes + are allowed to still be considered compatible (default = 1e-5) + cfg.keepsampleinfo = 'yes', 'no', 'ifmakessense' (default = 'ifmakessense') + + See also FT_TIMELOCKANALYSIS, FT_DATATYPE_TIMELOCK, FT_APPENDDATA, FT_APPENDFREQ, + FT_APPENDSOURCE, FT_APPENDSENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_appendtimelock.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_apply_montage` + +```{text} + FT_APPLY_MONTAGE changes the montage (i.e. linear combination) of a set of + electrode or gradiometer channels. A montage can be used for EEG rereferencing, MEG + synthetic gradients, MEG planar gradients or unmixing using ICA. This function not + only applies the montage to the EEG or MEG data, but also applies the montage to + the input EEG or MEG sensor array, which can subsequently be used for forward + computation and source reconstruction of the data. + + Use as + [sens] = ft_apply_montage(sens, montage, ...) + [data] = ft_apply_montage(data, montage, ...) + [freq] = ft_apply_montage(freq, montage, ...) + [montage] = ft_apply_montage(montage1, montage2, ...) + + A montage is specified as a structure with the fields + montage.tra = MxN matrix + montage.labelold = Nx1 cell-array + montage.labelnew = Mx1 cell-array + + As an example, a bipolar montage could look like this + bipolar.labelold = {'1', '2', '3', '4'} + bipolar.labelnew = {'1-2', '2-3', '3-4'} + bipolar.tra = [ + +1 -1 0 0 + 0 +1 -1 0 + 0 0 +1 -1 + ]; + + The montage can optionally also specify the channel type and unit of the input + and output data with + montage.chantypeold = Nx1 cell-array + montage.chantypenew = Mx1 cell-array + montage.chanunitold = Nx1 cell-array + montage.chanunitnew = Mx1 cell-array + + Additional options should be specified in key-value pairs and can be + 'keepunused' = string, 'yes' or 'no' (default = 'no') + 'inverse' = string, 'yes' or 'no' (default = 'no') + 'balancename' = string, name of the montage (default = '') + 'feedback' = string, see FT_PROGRESS (default = 'text') + 'warning' = boolean, whether to show warnings (default = true) + + If the first input is a montage, then the second input montage will be + applied to the first. In effect, the output montage will first do + montage1, then montage2. + + See also FT_READ_SENS, FT_DATATYPE_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_apply_montage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_clip` + +```{text} + FT_ARTIFACT_CLIP scans the data segments of interest for channels that clip, i.,e. + channels that have a constant value for a prolonged time, often indicating that the + signal was outside the range for the amplifier. These clipping artifacts are + detected by the signal being completely flat for a given amount of time. + + Use as + [cfg, artifact] = ft_artifact_clip(cfg) + with the configuration options + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_clip(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data (default is automatic) + and + cfg.artfctdef.clip.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.artfctdef.clip.pretim = pre-artifact rejection interval in seconds (default = 0) + cfg.artfctdef.clip.psttim = post-artifact rejection interval in seconds (default = 0) + cfg.artfctdef.clip.timethreshold = number, minimum duration in seconds of a segment with consecutive identical samples to be considered as 'clipped' + cfg.artfctdef.clip.amplthreshold = number, minimum amplitude difference in consecutive samples to be considered as 'clipped' (default = 0) + string, percent of the amplitude range considered as 'clipped' (i.e. '1%') + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_clip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_ecg` + +```{text} + FT_ARTIFACT_ECG performs a peak-detection on the ECG-channel and identifies the + windows around the QRS peak as artifacts. Using FT_REJECTARTIFACT you can remove + these windows from your data, or using FT_REMOVETEMPLATEARTIFACT you can subtract + an averaged template artifact from your data. + + Use as + [cfg, artifact] = ft_artifact_ecg(cfg) + with the configuration options + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_ecg(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest. See FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data + and + cfg.artfctdef.ecg.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.artfctdef.ecg.pretim = pre-artifact rejection interval in seconds (default = 0.05) + cfg.artfctdef.ecg.psttim = post-artifact rejection interval in seconds (default = 0.3) + cfg.artfctdef.ecg.cutoff = peak threshold (default = 3) + cfg.artfctdef.ecg.inspect = Nx1 list of channels which will be shown as a QRS-locked average + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the begin samples of an + artifact period, the second column contains the end samples of the QRS periods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_REMOVETEMPLATEARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, + FT_ARTIFACT_EOG, FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, + FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_ecg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_eog` + +```{text} + FT_ARTIFACT_EOG scans data segments of interest for EOG artifacts. + + Use as + [cfg, artifact] = ft_artifact_eog(cfg) + with the configuration options + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_eog(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data + + Prior to artifact detection, the data is preprocessed (again) with the following + configuration parameters, which are optimal for identifying EOG artifacts. + cfg.artfctdef.eog.bpfilter = 'yes' + cfg.artfctdef.eog.bpfilttype = 'but' + cfg.artfctdef.eog.bpfreq = [1 15] + cfg.artfctdef.eog.bpfiltord = 4 + cfg.artfctdef.eog.hilbert = 'yes' + + Artifacts are identified by means of thresholding the z-transformed value + of the preprocessed data. + cfg.artfctdef.eog.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.artfctdef.eog.cutoff = z-value at which to threshold (default = 4) + cfg.artfctdef.eog.trlpadding = number in seconds (default = 0.5) + cfg.artfctdef.eog.fltpadding = number in seconds (default = 0.1) + cfg.artfctdef.eog.artpadding = number in seconds (default = 0.1) + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_eog.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_jump` + +```{text} + FT_ARTIFACT_JUMP scans data segments of interest for SQUID jump artifacts. + + Use as + [cfg, artifact] = ft_artifact_jump(cfg) + with the configuration options + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_jump(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data + + Prior to artifact detection, the data is preprocessed (again) with the following + configuration parameters, which are optimal for identifying SQUID jump artifacts. + cfg.artfctdef.jump.medianfilter = 'yes' + cfg.artfctdef.jump.medianfiltord = 9 + cfg.artfctdef.jump.absdiff = 'yes' + + Artifacts are identified by means of thresholding the z-transformed value + of the preprocessed data. + cfg.artfctdef.jump.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.artfctdef.jump.cutoff = z-value at which to threshold (default = 20) + cfg.artfctdef.jump.trlpadding = number in seconds (default = 0.0) + cfg.artfctdef.jump.fltpadding = number in seconds (default = 0.0) + cfg.artfctdef.jump.artpadding = number in seconds (default = 0.0) + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_jump.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_muscle` + +```{text} + FT_ARTIFACT_MUSCLE scans data segments of interest for muscle artifacts. + + Use as + [cfg, artifact] = ft_artifact_muscle(cfg) + with the configuration options + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_muscle(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data + + Prior to artifact detection, the data is preprocessed (again) with the following + configuration parameters, which are optimal for identifying muscle artifacts. + cfg.artfctdef.muscle.bpfilter = 'yes' + cfg.artfctdef.muscle.bpfreq = [110 140] + cfg.artfctdef.muscle.bpfiltord = 8 + cfg.artfctdef.muscle.bpfilttype = 'but' + cfg.artfctdef.muscle.hilbert = 'yes' + cfg.artfctdef.muscle.boxcar = 0.2 + + Artifacts are identified by means of thresholding the z-transformed value + of the preprocessed data. + cfg.artfctdef.muscle.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.artfctdef.muscle.cutoff = z-value at which to threshold (default = 4) + cfg.artfctdef.muscle.trlpadding = number in seconds (default = 0.1) + cfg.artfctdef.muscle.fltpadding = number in seconds (default = 0.1) + cfg.artfctdef.muscle.artpadding = number in seconds (default = 0.1) + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_muscle.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_nan` + +```{text} + FT_ARTIFACT_NAN identifies artifacts that are indicated in the data as NaN (not a + number) values. + + Use as + [cfg, artifact] = ft_artifact_nan(cfg, data) + where the input data is a structure as obtained from FT_REJECTARTIFACT with the + option cfg.artfctdef.reject='nan', or from FT_REJECTVISUAL with cfg.keeptrial='nan' + or cfg.keepchannel='nan'. + + The configuration can contain + cfg.artfctdef.nan.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_nan.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_threshold` + +```{text} + FT_ARTIFACT_THRESHOLD scans data segments of interest for channels in which the + signal exceeds a specified minimum or maximum value, or in which the peak-to-peak + range within the trial exceeds a specified threshold. + + Use as + [cfg, artifact] = ft_artifact_threshold(cfg) + with the configuration options + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_threshold(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data + and + cfg.artfctdef.threshold.channel = cell-array with channel labels + cfg.artfctdef.threshold.bpfilter = 'no' or 'yes' (default = 'yes') + cfg.artfctdef.threshold.bpfreq = [0.3 30] + cfg.artfctdef.threshold.bpfiltord = 4 + + In the same way as specifying the options for band-pass filtering, it is also + possible to specify lpfilter, hpfilter, bsfilter, dftfilter or medianfilter, see + FT_PREPROCESSING. + + The detection of artifacts is done according to the following settings, + you should specify at least one of these thresholds + cfg.artfctdef.threshold.min = value in uV or T, default -inf + cfg.artfctdef.threshold.max = value in uV or T, default inf + cfg.artfctdef.threshold.onset = value in uV or T, default inf + cfg.artfctdef.threshold.offset = value in uV or T, default inf + + When cfg.artfctdef.threshold.onset and offset are used, the rising and falling + flank are thresholded with different values. In case onset and offset are both + positive, the data will be thresholded above their values. In case both onset and + offset are negative, the data will be thresholded below their values. + + Note that this function does not support artifactpadding or filterpadding. + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_threshold.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_tms` + +```{text} + FT_ARTIFACT_TMS reads the data segments of interest from file and identifies + artefacts in EEG recordings that were done during TMS stimulation. + + Use as + [cfg, artifact] = ft_artifact_tms(cfg) + with the configuration options + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_tms(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data (default = 'yes') + and + cfg.method = 'detect' or 'marker', see below. + cfg.prestim = scalar, time in seconds prior to onset of detected event to mark as artifactual (default = 0.005 seconds) + cfg.poststim = scalar, time in seconds post onset of detected even to mark as artifactual (default = 0.010 seconds) + + The different methods are described in detail below. + + With cfg.method='detect', TMS-artifact are detected on basis of transient + high-amplidude gradients that are typical for TMS-pulses. The data is preprocessed + (again) with the following settings, which are optimal for identifying TMS-pulses. + Artifacts are identified by means of thresholding the z-transformed value of the + preprocessed data. This method acts as a wrapper around FT_ARTIFACT_ZVALUE. + cfg.artfctdef.tms.derivative = 'yes' + cfg.artfctdef.tms.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.artfctdef.tms.cutoff = z-value at which to threshold (default = 4) + cfg.artfctdef.tms.trlpadding = 0.1 + cfg.artfctdef.tms.fltpadding = 0.1 + cfg.artfctdef.tms.artpadding = 0.01 + Be aware that if one artifact falls within this specified range of another + artifact, both artifact will be counted as one. Depending on cfg.prestim and + cfg.poststim you may not mark enough data as artifactual. + + With cfg.method='marker', TMS-artifact onsets and offsets are based on + markers/triggers that are written into the EEG dataset. This method acts as a + wrapper around FT_DEFINETRIAL to determine on- and offsets of TMS pulses by reading + markers in the EEG. + cfg.trialfun = function name, see below (default = 'ft_trialfun_general') + cfg.trialdef.eventtype = 'string' + cfg.trialdef.eventvalue = number, string or list with numbers or strings + The cfg.trialfun option is a string containing the name of a function that you + wrote yourself and that FT_ARTIFACT_TMS will call. The function should take the + cfg-structure as input and should give a NxM matrix with M>=3 in the same format as + "trl" as the output. You can add extra custom fields to the configuration structure + to pass as arguments to your own trialfun. Furthermore, inside the trialfun you can + use the FT_READ_EVENT function to get the event information from your data file. + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_tms.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_artifact_zvalue` + +```{text} + FT_ARTIFACT_ZVALUE scans data segments of interest for artifacts, by means of + thresholding the z-scored values of signals that have been preprocessed, + using heuristics that increase the sensitivity to detect certain types of artifacts. + Depending on the preprocessing options, this method will be sensitive to EOG, muscle + or SQUID jump artifacts. The z-scoring is applied in order to make the threshold + independent of the phsyical units in the data. + + Use as + [cfg, artifact] = ft_artifact_zvalue(cfg) + with the configuration options + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data. + If the data has not been recorded continuously, then the cfg.trl should + stricly observe the boundaries of the discontinuous segments, and the + permitted values padding options (described below) are restricted to 0. + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat + cfg.dataformat + + Alternatively you can use it as + [cfg, artifact] = ft_artifact_zvalue(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. Any preprocessing options + defined in the cfg will be applied to the data before the z-scoring and thresholding. + + In both cases the configuration should also contain + cfg.trl = structure that defines the data segments of interest, see FT_DEFINETRIAL + cfg.continuous = 'yes' or 'no' whether the file contains continuous data + and + cfg.artfctdef.zvalue.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.artfctdef.zvalue.cutoff = number, z-value threshold + cfg.artfctdef.zvalue.trlpadding = number in seconds + cfg.artfctdef.zvalue.fltpadding = number in seconds + cfg.artfctdef.zvalue.artpadding = number in seconds + + If you encounter difficulties with memory usage, you can use + cfg.memory = 'low' or 'high', whether to be memory or computationally efficient, respectively (default = 'high') + + The optional configuration settings (see below) are: + cfg.artfctdef.zvalue.artfctpeak = 'yes' or 'no' + cfg.artfctdef.zvalue.artfctpeakrange = [begin end] + cfg.artfctdef.zvalue.interactive = 'yes' or 'no' + cfg.artfctdef.zvalue.zscore = 'yes' (default) or 'no' + + If you specify cfg.artfctdef.zvalue.artfctpeak='yes', a peak detection on the suprathreshold + z-scores will be performed, and the artifact will be defined relative to + the peak, where the begin and end points will be defined by + cfg.artfctdef.zvalue artfctpeakrange, rather than by the time points that + exceed the threshold. + + You can specify cfg.artfctdef.zvalue.artfctpeakrange if you want to use the + detected artifacts as input to the DSS method of FT_COMPONENTANALYSIS. The result + is saved into cfg.artfctdef.zvalue.artifact. The range will automatically + respect the trial boundaries, i.e. it will be shorter if peak is near the beginning + or end of a trial. Samples between trials will be removed, thus this will not match + the sampleinfo of the data structure. + + If you specify cfg.artfctdef.zvalue.zscore = 'no', the data will NOT be z-scored prior + to thresholding. This goes a bit against the name of the function, but it may be useful + if the threshold is to be defined in meaningful physical units, e.g. degrees of visual + angle for eye position data. + + If you specify cfg.artfctdef.zvalue.interactive = 'yes', a graphical user interface + will show in which you can manually accept/reject the detected artifacts, and/or + change the threshold. To control the graphical interface via keyboard, use the + following keys: + + q : Stop + + comma : Step to the previous artifact trial + a : Specify artifact trial to display + period : Step to the next artifact trial + + x : Step 10 trials back + leftarrow : Step to the previous trial + t : Specify trial to display + rightarrow : Step to the next trial + c : Step 10 trials forward + + k : Keep trial + space : Mark complete trial as artifact + r : Mark part of trial as artifact + + downarrow : Shift the z-threshold down + z : Specify the z-threshold + uparrow : Shift the z-threshold down + + Configuration settings related to the preprocessing of the data are + cfg.artfctdef.zvalue.lpfilter = 'no' or 'yes' lowpass filter + cfg.artfctdef.zvalue.hpfilter = 'no' or 'yes' highpass filter + cfg.artfctdef.zvalue.bpfilter = 'no' or 'yes' bandpass filter + cfg.artfctdef.zvalue.bsfilter = 'no' or 'yes' bandstop filter for line noise removal + cfg.artfctdef.zvalue.dftfilter = 'no' or 'yes' line noise removal using discrete fourier transform + cfg.artfctdef.zvalue.medianfilter = 'no' or 'yes' jump preserving median filter + cfg.artfctdef.zvalue.lpfreq = lowpass frequency in Hz + cfg.artfctdef.zvalue.hpfreq = highpass frequency in Hz + cfg.artfctdef.zvalue.bpfreq = bandpass frequency range, specified as [low high] in Hz + cfg.artfctdef.zvalue.bsfreq = bandstop frequency range, specified as [low high] in Hz + cfg.artfctdef.zvalue.lpfiltord = lowpass filter order + cfg.artfctdef.zvalue.hpfiltord = highpass filter order + cfg.artfctdef.zvalue.bpfiltord = bandpass filter order + cfg.artfctdef.zvalue.bsfiltord = bandstop filter order + cfg.artfctdef.zvalue.medianfiltord = length of median filter + cfg.artfctdef.zvalue.lpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' + cfg.artfctdef.zvalue.hpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' + cfg.artfctdef.zvalue.bpfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' + cfg.artfctdef.zvalue.bsfilttype = digital filter type, 'but' (default) or 'firws' or 'fir' or 'firls' + cfg.artfctdef.zvalue.detrend = 'no' or 'yes' + cfg.artfctdef.zvalue.demean = 'no' or 'yes' + cfg.artfctdef.zvalue.baselinewindow = [begin end] in seconds, the default is the complete trial + cfg.artfctdef.zvalue.hilbert = 'no' or 'yes' + cfg.artfctdef.zvalue.rectify = 'no' or 'yes' + + The output argument "artifact" is a Nx2 matrix comparable to the "trl" matrix of + FT_DEFINETRIAL. The first column of which specifying the beginsamples of an + artifact period, the second column contains the endsamples of the artifactperiods. + + To facilitate data-handling and distributed computing, you can use + cfg.inputfile = ... + to read the input data from a *.mat file on disk. This mat files should contain + only a single variable named 'data', corresponding to the input structure. + + See also FT_REJECTARTIFACT, FT_ARTIFACT_CLIP, FT_ARTIFACT_ECG, FT_ARTIFACT_EOG, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MUSCLE, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_ZVALUE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_artifact_zvalue.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_audiovideobrowser` + +```{text} + FT_AUDIOVIDEOBROWSER reads and vizualizes the audio and/or video data + corresponding to the EEG/MEG data that is passed into this function. + + Use as + ft_audiovideobrowser(cfg) + or as + ft_audiovideobrowser(cfg, data) + where the input data is the result from FT_PREPROCESSING or from FT_COMPONENTANALYSIS. + + The configuration structure can contain the following options + cfg.datahdr = header structure of the EEG/MEG data, see FT_READ_HEADER + cfg.audiohdr = header structure of the audio data, see FT_READ_HEADER + cfg.videohdr = header structure of the video data, see FT_READ_HEADER + cfg.audiofile = string with the filename + cfg.videofile = string with the filename + cfg.trl = Nx3 matrix, expressed in the MEG/EEG data samples, see FT_DEFINETRIAL + cfg.anonymize = [x1 x2 y1 y2], range in pixels for placing a bar over the eyes (default = []) + cfg.interactive = 'yes' or 'no' (default = 'yes') + + If you do NOT specify cfg.datahdr, the header must be present in the input data. + If you do NOT specify cfg.audiohdr, the header will be read from the audio file. + If you do NOT specify cfg.videohdr, the header will be read from the video file. + If you do NOT specify cfg.trl, the input data should contain a sampleinfo field. + + See also FT_DATABROWSER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_audiovideobrowser.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_average_sens` + +```{text} + FT_AVERAGE_SENS computes average sensor array from a series of input + arrays. Corresponding average fiducials can also be computed (optional) + + Use as + [asens, afid] = ft_average_sens(sens) + where sens is a 1xN structure array containing N sensor arrays + + Additional options should be specified in key-value pairs and can be + 'weights' a vector of weights (will be normalized to sum==1) + 'fiducials' optional structure array of headshapes + + See also FT_READ_SENS, FT_DATATYPE_SENS, FT_PREPARE_VOL_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_average_sens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_badchannel` + +```{text} + FT_BADCHANNEL tries to identify bad channels in a MEG or EEG dataset. Different + methods are implemented to identify bad channels, these are largely shared with + those implemented in FT_REJECTVISUAL with the summary method. The methods are + shortly described in detail below. + + VAR, STD, MIN, MAX, MAXABS, RANGE, KURTOSIS, ZVALUE - compute the specified metric + for each channel in each trial and check whether it exceeds the threshold. + + NEIGHBEXPVAR - identifies channels that cannot be explained very well by a linear + combination of their neighbours. A general linear model is used to compute the + explained variance. A value close to 1 means that a channel is similar to its + neighbours, a value close to 0 indicates a "bad" channel. + + NEIGHBCORR - identifies channels that have low correlation with each of their + neighbours. The rationale is that "bad" channel have inherent noise that is + uncorrelated with other sensors. + + NEIGHBSTDRATIO - identifies channels that have a standard deviation which is very + different from that of each of their neighbours. This computes the difference in + the standard deviation of each channel to each of its neighbours, relative to that + of the neighbours. + + Use as + [cfg] = ft_badchannel(cfg, data) + where the input data corresponds to the output from FT_PREPROCESSING. + + The configuration should contain + cfg.metric = string, describes the metric that should be computed in summary mode for each channel in each trial, can be + 'var' variance within each channel (default) + 'std' standard deviation within each channel + 'db' decibel value within each channel + 'mad' median absolute deviation within each channel + '1/var' inverse variance within each channel + 'min' minimum value in each channel + 'max' maximum value in each channel + 'maxabs' maximum absolute value in each channel + 'range' range from min to max in each channel + 'kurtosis' kurtosis, i.e. measure of peakedness of the amplitude distribution + 'zvalue' mean and std computed over all time and trials, per channel + 'neighbexpvar' relative variance explained by neighboring channels in each trial + cfg.threshold = scalar, the optimal value depends on the methods and on the data characteristics + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS for details + cfg.nbdetect = 'any', 'most', 'all', 'median', see below (default = 'median') + cfg.feedback = 'yes' or 'no', whether to show an image of the neighbour values (default = 'no') + + The following options allow you to make a pre-selection + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + + The 'neighcorrel' and 'neighstdratio' methods implement the bad channel detection + (more or less) according to the paper "Adding dynamics to the Human Connectome + Project with MEG", Larson-Prior et al. https://doi.org/10.1016/j.neuroimage.2013.05.056. + + Most methods compute a scalar value for each channel that can simply be + thresholded. The NEIGHBCORR and NEIGHBSTDRATIO compute a vector with a value for + each of the neighbour of a channel. The cfg.nbdetect option allows you to specify + whether you want to flag the channel as bad in case 'all' of its neighbours exceed + the threshold, if 'most' exceed the threshold, or if 'any' of them exceeds the + threshold. Note that when you specify 'any', then all channels neighbouring a bad + channel will also be marked as bad, since they all have at least one bad neighbour. + You can also specify 'median', in which case the threshold is applied to the median + value over neighbours. + + See also FT_BADSEGMENT, FT_BADDATA, FT_REJECTVISUAL, FT_CHANNELREPAIR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_badchannel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_baddata` + +```{text} + FT_BADDATA identifies bad data in a MEG or EEG dataset by looping over all trials + and all channels. Each channel in each trial is considered separately, in the + remainder of the help we will refer to this as "traces". Different methods are + implemented, these are largely shared with those implemented in FT_REJECTVISUAL + with the "summary" method. The methods are shortly described in detail below. Bad + traces are replaced in the output data with nan. + + VAR, STD, MIN, MAX, MAXABS, RANGE, KURTOSIS, ZVALUE - compute the specified metric + for each channel in each trial and check whether it exceeds the threshold. + + NEIGHBEXPVAR - identifies channels that cannot be explained very well by a linear + combination of their neighbours. A general linear model is used to compute the + explained variance. A value close to 1 means that a channel is similar to its + neighbours, a value close to 0 indicates a "bad" channel. + + Use as + [data_clean] = ft_baddata(cfg, data) + where the input data corresponds to the output from FT_PREPROCESSING. + + The configuration should contain + cfg.metric = string, describes the metric that should be computed in summary mode for each channel in each trial, can be + 'var' variance within each channel (default) + 'std' standard deviation within each channel + 'db' decibel value within each channel + 'mad' median absolute deviation within each channel + '1/var' inverse variance within each channel + 'min' minimum value in each channel + 'max' maximum value in each channel + 'maxabs' maximum absolute value in each channel + 'range' range from min to max in each channel + 'kurtosis' kurtosis, i.e. measure of peakedness of the amplitude distribution in trace + 'zvalue' mean and std computed over all time and trials, per channel + 'neighbexpvar' relative variance explained by neighboring channels in each trial + cfg.threshold = scalar, the appropriate value depends on the data characteristics and the metric + cfg.feedback = 'yes' or 'no', whether to show an image of the neighbour values (default = 'no') + + The following options allow you to make a pre-selection + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + + See also FT_BADCHANNEL, FT_BADSEGMENT, FT_REJECTVISUAL, FT_CHANNELREPAIR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_baddata.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_badsegment` + +```{text} + FT_BADSEGMENT tries to identify bad segments or trials in a MEG or EEG dataset. + Different methods are implemented to identify bad channels, these are largely + shared with those implemented in FT_REJECTVISUAL with the summary method. + + VAR, STD, MIN, MAX, MAXABS, RANGE, KURTOSIS, ZVALUE - compute the specified metric + for each channel in each trial and check whether it exceeds the threshold. + + NEIGHBEXPVAR - identifies channels that cannot be explained very well by a linear + combination of their neighbours. A general linear model is used to compute the + explained variance. A value close to 1 means that a channel is similar to its + neighbours, a value close to 0 indicates a "bad" channel. + + NEIGHBCORR - identifies channels that have low correlation with each of their + neighbours. The rationale is that "bad" channel have inherent noise that is + uncorrelated with other sensors. + + NEIGHBSTDRATIO - identifies channels that have a standard deviation which is very + different from that of each of their neighbours. This computes the difference in + the standard deviation of each channel to each of its neighbours, relative to that + of the neighbours. + + Use as + [cfg, artifact] = ft_badchannel(cfg, data) + where the input data corresponds to the output from FT_PREPROCESSING. + + The configuration should contain + cfg.metric = string, describes the metric that should be computed in summary mode for each channel in each trial, can be + 'var' variance within each channel (default) + 'std' standard deviation within each channel + 'db' decibel value within each channel + 'mad' median absolute deviation within each channel + '1/var' inverse variance within each channel + 'min' minimum value in each channel + 'max' maximum value in each channel + 'maxabs' maximum absolute value in each channel + 'range' range from min to max in each channel + 'kurtosis' kurtosis, i.e. measure of peakedness of the amplitude distribution + 'zvalue' mean and std computed over all time and trials, per channel + 'neighbexpvar' relative variance explained by neighboring channels in each trial + cfg.threshold = scalar, the optimal value depends on the methods and on the data characteristics + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS for details + cfg.nbdetect = 'any', 'most', 'all', 'median', see below (default = 'median') + cfg.feedback = 'yes' or 'no', whether to show an image of the neighbour values (default = 'no') + + The following options allow you to make a pre-selection + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + + The 'neighcorrel' and 'neighstdratio' methods implement the bad channel detection + (more or less) according to the paper "Adding dynamics to the Human Connectome + Project with MEG", Larson-Prior et al. https://doi.org/10.1016/j.neuroimage.2013.05.056. + + Most methods compute a scalar value for each channel that can simply be + thresholded. The NEIGHBCORR and NEIGHBSTDRATIO compute a vector with a value for + each of the neighbour of a channel. The cfg.nbdetect option allows you to specify + whether you want to flag the channel as bad in case 'all' of its neighbours exceed + the threshold, if 'most' exceed the threshold, or if 'any' of them exceeds the + threshold. Note that when you specify 'any', then all channels neighbouring a bad + channel will also be marked as bad, since they all have at least one bad neighbour. + You can also specify 'median', in which case the threshold is applied to the median + value over neighbours. + + See also FT_BADCHANNEL, FT_BADDATA, FT_REJECTVISUAL, FT_REJECTARTIFACT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_badsegment.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_cfg2keyval` + +```{text} + FT_CFG2KEYVAL converts between a structure and a cell-array with key-value + pairs which can be used for optional input arguments. + + Use as + optarg = ft_cfg2keyval(cfg) + + See also FT_KEYVAL2CFG, FT_GETOPT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_cfg2keyval.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_channelcombination` + +```{text} + FT_CHANNELCOMBINATION creates a cell-array with combinations of EEG/MEG channels + for subsequent cross-spectral-density, coherence and/or connectivity ananalysis + + You should specify channel combinations as a two-column cell-array, + cfg.channelcmb = { 'EMG' 'MLF31' + 'EMG' 'MLF32' + 'EMG' 'MLF33' }; + to compare EMG with these three sensors, or + cfg.channelcmb = { 'MEG' 'MEG' }; + to make all MEG combinations, or + cfg.channelcmb = { 'EMG' 'MEG' }; + to make all combinations between the EMG and all MEG channels. + + For each column, you can specify a mixture of real channel labels + and of special strings that will be replaced by the corresponding + channel labels. Channels that are not present in the raw datafile + are automatically removed from the channel list. + + When directional connectivity measures will subsequently be computed, the + interpretation of each channel-combination is that the direction of the + interaction is from the first column to the second column. + + Note that the default behavior is to exclude symmetric pairs and + auto-combinations. + + See also FT_CHANNELSELECTION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_channelcombination.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_channelnormalise` + +```{text} + FT_CHANNELNORMALISE shifts and scales all channels of the the input data. + The default behavior is to subtract each channel's mean, and scale to a + standard deviation of 1, for each channel individually. + + Use as + [dataout] = ft_channelnormalise(cfg, data) + + The configuration can contain + cfg.channel = 'all', or a selection of channels + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.demean = 'yes' or 'no' (or boolean value) (default = 'yes') + cfg.scale = scalar value used for scaling (default = 1) + cfg.method = 'perchannel', or 'acrosschannel', computes the + standard deviation per channel, or across all channels. + The latter method leads to the same scaling across + channels and preserves topographical distributions + + 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_COMPONENTANALYSIS, FT_FREQBASELINE, FT_TIMELOCKBASELINE + + Copyright (C) 2010, Jan-Mathijs Schoffelen + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_channelnormalise.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_channelrepair` + +```{text} + FT_CHANNELREPAIR repairs bad or missing channels in the data by replacing + them with the plain average of of all neighbours, by a weighted average + of all neighbours, by an interpolation based on a surface Laplacian, or + by spherical spline interpolating (see Perrin et al., 1989). + + Use as + [interp] = ft_channelrepair(cfg, data) + where the input data corresponds to the output from FT_PREPROCESSING. + + The configuration should contain + cfg.method = 'weighted', 'average', 'spline', 'slap' or 'nan' (default = 'weighted') + cfg.badchannel = cell-array, see FT_CHANNELSELECTION for details + cfg.missingchannel = cell-array, see FT_CHANNELSELECTION for details + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.lambda = regularisation parameter (default = 1e-5, for method 'spline' and 'slap') + cfg.order = order of the polynomial interpolation (default = 4 for methods 'spline' and 'slap') + cfg.senstype = string, which type of data to repair. Can be 'meg', 'eeg' or 'nirs' (default is automatic) + + The weighted and average method are less reliable in case multiple bad channels lie + next to each other. In that case the bad channels will be removed from the + neighbours and not considered for interpolation. + + If you want to reconstruct channels that are absent in your data, those + channels may also be missing from the sensor definition (grad, elec or opto) + and determining the neighbours is non-trivial. In that case you must use + a complete sensor definition from another dataset or from a template. + + The EEG, MEG or NIRS sensor positions can be present as a field in the + data (data.grad/data.elec/data.opto, depending on the type of data), + or can be specified as cfg option. Either one is required for the following + methods: 'weighted', 'spline', and 'slap'. Depending on the type of + data this should be one of the following + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + cfg.opto = structure with optode definition, see FT_READ_SENS + + This function will only repair one type of channels (MEG, EEG or NIRS) at + a time. If you want to repair multiple types of channels, you should call + it multiple times and use FT_SELECTDATA and FT_APPENDDATA. + + This function only interpolates data over space, not over time. If you want to + interpolate using temporal information, e.g. using a segment of data before and + after the nan-marked artifact, you should use FT_INTERPOLATENAN. + + 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_MEGREALIGN, FT_MEGPLANAR, FT_PREPARE_NEIGHBOURS, FT_INTERPOLATENAN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_channelrepair.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_channelselection` + +```{text} + FT_CHANNELSELECTION makes a selection of EEG and/or MEG channel labels. This + function translates the user-specified list of channels into channel labels as they + occur in the data. This channel selection procedure can be used throughout + FieldTrip. + + You can specify a mixture of real channel labels and of special strings, or index + numbers that will be replaced by the corresponding channel labels. Channels that + are not present in the raw datafile are automatically removed from the channel + list. + + The order of the channels in the list that is returned corresponds to the order in + the data. + + E.g. the desired input specification can be: + 'all' is replaced by all channels in the datafile + 'gui' this will pop up a graphical user interface to select the channels + 'C*' is replaced by all channels that match the wildcard, e.g. C1, C2, C3, ... + '*1' is replaced by all channels that match the wildcard, e.g. C1, P1, F1, ... + 'M*1' is replaced by all channels that match the wildcard, e.g. MEG0111, MEG0131, MEG0131, ... + 'meg' is replaced by all MEG channels (works for CTF, 4D, Neuromag and Yokogawa) + 'megref' is replaced by all MEG reference channels (works for CTF and 4D) + 'meggrad' is replaced by all MEG gradiometer channels (works for CTF, Yokogawa and Neuromag306) + 'megplanar' is replaced by all MEG planar gradiometer channels (works for Neuromag306) + 'megmag' is replaced by all MEG magnetometer channels (works for Yokogawa and Neuromag306) + 'eeg' is replaced by all recognized EEG channels (this is system dependent) + 'eeg1020' is replaced by 'Fp1', 'Fpz', 'Fp2', 'F7', 'F3', ... + 'eog' is replaced by all recognized EOG channels + 'ecg' is replaced by all recognized ECG channels + 'nirs' is replaced by all channels recognized as NIRS channels + 'emg' is replaced by all channels in the datafile starting with 'EMG' + 'lfp' is replaced by all channels in the datafile starting with 'lfp' + 'mua' is replaced by all channels in the datafile starting with 'mua' + 'spike' is replaced by all channels in the datafile starting with 'spike' + 10 is replaced by the 10th channel in the datafile + + Other channel groups are + 'EEG1010' with approximately 90 electrodes + 'EEG1005' with approximately 350 electrodes + 'EEGREF' for mastoid and ear electrodes (M1, M2, LM, RM, A1, A2) + 'MZ' for MEG zenith + 'ML' for MEG left + 'MR' for MEG right + 'MLx', 'MRx' and 'MZx' with x=C,F,O,P,T for left/right central, frontal, occipital, parietal and temporal + + You can also exclude channels or channel groups using the following syntax + {'all', '-POz', '-Fp1', -EOG'} + + See also FT_PREPROCESSING, FT_SENSLABEL, FT_MULTIPLOTER, FT_MULTIPLOTTFR, + FT_SINGLEPLOTER, FT_SINGLEPLOTTFR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_channelselection.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_chantype` + +```{text} + FT_CHANTYPE determines for each individual channel what chantype of data it + represents, e.g. a planar gradiometer, axial gradiometer, magnetometer, + trigger channel, etc. If you want to know what the acquisition system is + (e.g. ctf151 or neuromag306), you should not use this function but + FT_SENSTYPE instead. + + Use as + type = ft_chantype(hdr) + type = ft_chantype(sens) + type = ft_chantype(label) + or as + type = ft_chantype(hdr, desired) + type = ft_chantype(sens, desired) + type = ft_chantype(label, desired) + + If the desired unit is not specified as second input argument, this + function returns a Nchan*1 cell-array with a string describing the type + of each channel. + + If the desired unit is specified as second input argument, this function + returns a Nchan*1 boolean vector with "true" for the channels of the + desired type and "false" for the ones that do not match. + + The specification of the channel types depends on the acquisition system, + for example the ctf275 system includes the following type of channels: + meggrad, refmag, refgrad, adc, trigger, eeg, headloc, headloc_gof. + + See also FT_READ_HEADER, FT_SENSTYPE, FT_CHANUNIT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_chantype.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_chanunit` + +```{text} + FT_CHANUNIT is a helper function that tries to determine the physical + units of each channel. In case the type of channel is not detected, it + will return 'unknown' for that channel. + + Use as + unit = ft_chanunit(hdr) + or as + unit = ft_chanunit(hdr, desired) + + If the desired unit is not specified as second input argument, this + function returns a Nchan*1 cell-array with a string describing the + physical units of each channel, or 'unknown' if those cannot be + determined. + + If the desired unit is specified as second input argument, this function + returns a Nchan*1 boolean vector with "true" for the channels that match + the desired physical units and "false" for the ones that do not match. + + The specification of the channel units depends on the acquisition system, + for example the neuromag306 system includes channel with the following + units: uV, T and T/cm. + + See also FT_CHANTYPE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_chanunit.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_checkconfig` + +```{text} + FT_CHECKCONFIG checks the input cfg of the main FieldTrip functions + + It checks whether the cfg contains all the required options, it gives + a warning when renamed or deprecated options are used, and it makes sure + no forbidden options are used. If necessary and possible, this function + will adjust the cfg to the input requirements. If the input cfg does NOT + correspond to the requirements, this function gives an elaborate warning + message. + + It controls the relevant cfg options that are being passed on to other + functions, by putting them into substructures or converting them into the + required format. + + Use as + [cfg] = ft_checkconfig(cfg, ...) + + The behavior of checkconfig can be controlled by the following cfg options, which + can be set as global FieldTrip defaults (see FT_DEFAULTS) + cfg.checkconfig = 'pedantic', 'loose' or 'silent', this controls the how strict this function is + cfg.checksize = number in bytes (can be inf), this controls the maximum size of output cfg fields + + Optional input arguments should be specified as key-value pairs and can include + renamed = {'old', 'new'} % list the old and new option + renamedval = {'opt', 'old', 'new'} % list option and old and new value + allowedtype = {'opt', 'allowed1', ...} % list of allowed data type classes for a particular option, anything else will throw an error + allowedval = {'opt', 'allowed1', ...} % list of allowed values for a particular option, anything else will throw an error + required = {'opt1', 'opt2', etc.} % list the required options + allowed = {'opt1', 'opt2', etc.} % list the allowed options, all other options are forbidden + forbidden = {'opt1', 'opt2', etc.} % list the forbidden options, these result in an error + deprecated = {'opt1', 'opt2', etc.} % list the deprecated options + unused = {'opt1', 'opt2', etc.} % list the unused options, these will be removed and a warning is issued + createsubcfg = {'subname', etc.} % list the names of the sub-configuration items + createtopcfg = {'subname', etc.} % list the names of the sub-configuration items + dataset2files = 'yes', 'no' % converts dataset into headerfile and datafile + inside2logical = 'yes', 'no' % converts cfg.inside or cfg.sourcemodel.inside into logical representation + checksize = 'yes', 'no' % remove large fields from the cfg + + See also FT_CHECKDATA, FT_CHECKOPT, FT_DEFAULTS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_checkconfig.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_checkdata` + +```{text} + FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether the + type of data structure corresponds with the required data. If necessary and possible, + this function will adjust the data structure to the input requirements (e.g. change + dimord, average over trials, convert inside from index into logical). + + If the input data does NOT correspond to the requirements, this function will give a + warning message and if applicable point the user to external documentation (link to + website). + + Use as + [data] = ft_checkdata(data, ...) + + Optional input arguments should be specified as key-value pairs and can include + feedback = 'yes' or 'no' + datatype = raw, freq, timelock, comp, spike, source, mesh, dip, volume, segmentation, parcellation + dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos + senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode + fsample = sampling frequency to use to go from SPIKE to RAW representation + ismeg = 'yes' or 'no', requires the data to have a grad structure + iseeg = 'yes' or 'no', requires the data to have an elec structure + isnirs = 'yes' or 'no', requires the data to have an opto structure + hasunit = 'yes' or 'no' + hascoordsys = 'yes' or 'no' + haschantype = 'yes' or 'no' + haschanunit = 'yes' or 'no' + hassampleinfo = 'yes', 'no', or 'ifmakessense' (applies to raw and timelock data) + hascumtapcnt = 'yes' or 'no' (only applies to freq data) + hasdim = 'yes' or 'no' + hasdof = 'yes' or 'no' + hasbrain = 'yes' or 'no' (only applies to segmentation) + insidestyle = logical, index, can also be empty + cmbstyle = sparse, sparsewithpow, full, fullfast, fourier (applies to covariance and cross-spectral density) + segmentationstyle = indexed, probabilistic (only applies to segmentation) + parcellationstyle = indexed, probabilistic (only applies to parcellation) + trialinfostyle = matrix, table or empty + + For some options you can specify multiple values, e.g. + [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign + [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis + + See also FT_DATATYPE_XXX for each of the respective data types. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_checkdata.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_checkopt` + +```{text} + FT_CHECKOPT does a validity test on the types and values of a configuration + structure or cell-array with key-value pairs. + + Use as + opt = ft_checkopt(opt, key) + opt = ft_checkopt(opt, key, allowedtype) + opt = ft_checkopt(opt, key, allowedtype, allowedval) + + For allowedtype you can specify a string or a cell-array with multiple + strings. All the default MATLAB types can be specified, such as + 'double' + 'logical' + 'char' + 'single' + 'float' + 'int16' + 'cell' + 'struct' + 'function_handle' + + Furthermore, the following custom types can be specified + 'empty' + 'doublescalar' + 'doublevector' + 'doublebivector' i.e. [1 1] or [1 2] + 'ascendingdoublevector' i.e. [1 2 3 4 5], but not [1 3 2 4 5] + 'ascendingdoublebivector' i.e. [1 2], but not [2 1] + 'doublematrix' + 'numericscalar' + 'numericvector' + 'numericmatrix' + 'charcell' + + For allowedval you can specify a single value or a cell-array + with multiple values. + + This function will give an error or it returns the input configuration + structure or cell-array without modifications. A match on any of the + allowed types and any of the allowed values is sufficient to let this + function pass. + + See also FT_GETOPT, FT_SETOPT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_checkopt.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_clusterplot` + +```{text} + FT_CLUSTERPLOT plots a series of topographies with highlighted clusters. + + Use as + ft_clusterplot(cfg, stat) + where the input data is obtained from FT_TIMELOCKSTATISTICS or FT_FREQSTATISTICS. + + The configuration options can be + cfg.alpha = number, highest cluster p-value to be plotted max 0.3 (default = 0.05) + cfg.highlightseries = 1x5 cell-array, highlight option series with 'on', 'labels' or 'numbers' (default {'on', 'on', 'on', 'on', 'on'} for p < [0.01 0.05 0.1 0.2 0.3] + cfg.highlightsymbolseries = 1x5 vector, highlight marker symbol series (default ['*', 'x', '+', 'o', '.'] for p < [0.01 0.05 0.1 0.2 0.3] + cfg.highlightsizeseries = 1x5 vector, highlight marker size series (default [6 6 6 6 6] for p < [0.01 0.05 0.1 0.2 0.3]) + cfg.highlightcolorpos = color of highlight marker for positive clusters (default = [0 0 0]) + cfg.highlightcolorneg = color of highlight marker for negative clusters (default = [0 0 0]) + cfg.subplotsize = layout of subplots ([h w], default [3 5]) + cfg.saveaspng = string, filename of the output figures (default = 'no') + cfg.visible = string, 'on' or 'off' whether figure will be visible (default = 'on') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + cfg.toi = vector, or 'all' (default) indicates which time + points (or frequency bins) are to be plotted. If specified as 'all' only the + data points with identified clusters are plotted + + You can also specify most configuration options that apply to FT_TOPOPLOTER or FT_TOPOPLOTTFR, + except for cfg.xlim, any of the highlight options, cfg.comment and cfg.commentpos. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_TOPOPLOTTFR, FT_TOPOPLOTER, FT_MOVIEPLOTTFR, FT_MOVIEPLOTER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_clusterplot.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_colormap` + +```{text} + FT_COLORMAP is a wrapper function with the same usage as the normal COLORMAP + function, but it also knows about the colormaps from BREWERMAP and some colormaps + from MATPLOTLIB. The recommended colormaps include 'parula', 'cividis', 'balance', + and '*RdBu'. + + Use as + ft_colormap(name) + ft_colormap(name, n) + ft_colormap(handle, name) + ft_colormap(handle, name, n) + + The name is a string that specifies the colormap (see below). The optional handle + can be used to specify the current figure (which is the default, see GCF) or the + current axes (see GCA). The optional parameter n determines the number of steps or + unique colors in the map (by default 64). + + The colormaps from MATLAB include 'parula', 'jet', 'hsv', 'hot', 'cool', 'spring', + 'summer', 'autumn', 'winter', 'gray', 'bone', 'copper', 'pink', 'lines', + 'colorcube', 'prism', and 'flag'. + + The colormaps from MATPLOTLIB include 'cividis', 'inferno', 'magma', 'plasma', + 'tab10', 'tab20', 'tab20b', 'tab20c', 'twilight', and 'viridis'. + + The colormaps from BREWERMAP include 'BrBG', 'PRGn', 'PiYG', 'PuOr', 'RdBu', + 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'Accent', 'Dark2', 'Paired', 'Pastel1', + 'Pastel2', 'Set1', 'Set2', 'Set3', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', + 'Greys', 'OrRd', 'Oranges', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', + 'YlGn', 'YlGnBu', 'YlOrBr', and 'YlOrRd', plus their reverse when prefixed with '*'. + + The colormaps from CMOCEAN include 'thermal', 'haline', 'solar', 'ice', 'gray', + 'oxy', 'deep', 'dense', 'algae', 'matter', 'turbid', 'speed', 'amp', 'tempo', + 'rain', 'phase', 'topo', 'balance', 'delta', 'curl', 'diff', and 'tarn'. + + The colormaps from COLORCET include 'blueternary', 'coolwarm', 'cyclicgrey', + 'depth', 'divbjy', 'fire', 'geographic', 'geographic2', 'gouldian', 'gray', + 'greenternary', 'grey', 'heat', 'phase2', 'phase4', 'rainbow', 'rainbow2', + 'rainbow3', 'rainbow4', 'redternary', 'reducedgrey', 'yellowheat', and all the ones + with symbolic names. + + To reverse any of these these colormaps you can add a minus sign in front, like + '-phase', '-balance' or '-RdBu'. + + Relevant publications: + - Crameri et al. 2020. The misuse of colour in science communication. https://doi.org/10.1038/s41467-020-19160-7 + - Cooper et al. 2021. Over the rainbow: Guidelines for meaningful use of colour maps in neurophysiology. https://doi.org/10.1016/j.neuroimage.2021.118628 + - Kovesi 2015, Good colour maps: How to design them. https://doi.org/10.48550/arXiv.1509.03700 + + See also COLORMAP, COLORMAPEDITOR, BREWERMAP, MATPLOTLIB, CMOCEAN, COLORCET + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_colormap.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_combineplanar` + +```{text} + FT_COMBINEPLANAR computes the planar gradient magnitude over both directions + combining the two gradients at each sensor to a single positive-valued number. This + can be done for single-trial/averaged planar gradient ERFs or single-trial/averaged + TFRs. + + Use as + [data] = ft_combineplanar(cfg, data) + where data contains an averaged planar-gradient ERF or single-trial or + averaged TFRs. + + The configuration can contain + cfg.method = 'sum', 'svd', 'abssvd', or 'complex' (default = 'sum') + cfg.updatesens = 'no' or 'yes' (default = 'yes') + and for timelocked input data (i.e. ERFs), the configuration can also contain + cfg.demean = 'yes' or 'no' (default = 'no') + cfg.baselinewindow = [begin end] + + 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_MEGPLANAR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_combineplanar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_compile_mex` + +```{text} + FT_COMPILE_MEX can be used for compiling most of the FieldTrip MEX files Note that + this function does not put the MEX files in the correct location in the private + folders, this is managed by a Bash script. In case you are not working with Git and + you want to recompile the mex files for your platform, you can find all mex files + for your platform and move them to a backup directory that is not on your MATLAB + path. Subsequently you can rtun this function to recompile it on your platform with + your compiler settings + + The standards procedure for compiling mex files is detailed on + http://www.fieldtriptoolbox.org/development/guidelines/code#compiling_mex_files + + Please note that this script does NOT set up your MEX environment for you, so in + case you haven't selected the C compiler on Windows yet, you need to type 'mex + -setup' first to choose either the LCC, Borland or Microsoft compiler. If you want + to use MinGW, you also need to install Gnumex (http://gnumex.sourceforget.net), + which comes with its own procedure for setting up the MEX environment. + + The logic in this script is to first build a list of files that actually need + compilation for the particular platform that MATLAB is running on, and then to go + through that list. Functions are added to the list by giving their destination + directory and (relative to that) the name of the source file (without the .c). + Optionally, you can specify a list of platform this file needs to be compiled on + only, and a list of platforms where you don't compile it on. Finally, you can give + extra arguments to the MEX command, e.g., for including other c-sources or giving + compiler flags. + + See also MEX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_compile_mex.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_compile_standalone` + +```{text} + FT_COMPILE_STANDALONE compiles the FieldTrip functions along with + the standalone entry function into a compiled executable. + + The compiled executable includes + - all main FieldTrip m-files + - all main FieldTrip m-files dependencies for as long as these + dependencies are in the fieldtrip modules and external toolboxes + on the path, MATLAB built-in, or toolbox/(stats/images/signal) + functions + + See also FT_STANDALONE, FT_COMPILE_MEX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_compile_standalone.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_componentanalysis` + +```{text} + FT_COMPONENTANALYSIS performs independent component analysis or other + spatio-temporal decompositions of EEG or MEG data. This function computes + the topography and timecourses of the components. The output of this + function can be further analyzed with FT_TIMELOCKANALYSIS or + FT_FREQANALYSIS. + + Use as + [comp] = ft_componentanalysis(cfg, data) + where cfg is a configuration structure and the input data is obtained from + FT_PREPROCESSING or from FT_TIMELOCKANALYSIS. + + The configuration should contain + cfg.method = 'runica', 'fastica', 'binica', 'pca', 'svd', 'jader', + 'varimax', 'dss', 'cca', 'sobi', 'white' or 'csp' + (default = 'runica') + cfg.channel = cell-array with channel selection (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.split = cell-array of channel types between which covariance + is split, it can also be 'all' or 'no' (default = 'no') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.numcomponent = 'all' or number (default = 'all') + cfg.demean = 'no' or 'yes', whether to demean the input data (default = 'yes') + cfg.updatesens = 'no' or 'yes' (default = 'yes') + cfg.feedback = 'no', 'text', 'textbar', 'gui' (default = 'text') + + The runica method supports the following method-specific options. The + values that these options can take can be found with HELP RUNICA. + cfg.runica.extended + cfg.runica.pca + cfg.runica.sphering + cfg.runica.weights + cfg.runica.lrate + cfg.runica.block + cfg.runica.anneal + cfg.runica.annealdeg + cfg.runica.stop + cfg.runica.maxsteps + cfg.runica.bias + cfg.runica.momentum + cfg.runica.specgram + cfg.runica.posact + cfg.runica.verbose + cfg.runica.logfile + cfg.runica.interput + + The fastica method supports the following method-specific options. The + values that these options can take can be found with HELP FASTICA. + cfg.fastica.approach + cfg.fastica.numOfIC + cfg.fastica.g + cfg.fastica.finetune + cfg.fastica.a1 + cfg.fastica.a2 + cfg.fastica.mu + cfg.fastica.stabilization + cfg.fastica.epsilon + cfg.fastica.maxNumIterations + cfg.fastica.maxFinetune + cfg.fastica.sampleSize + cfg.fastica.initGuess + cfg.fastica.verbose + cfg.fastica.displayMode + cfg.fastica.displayInterval + cfg.fastica.firstEig + cfg.fastica.lastEig + cfg.fastica.interactivePCA + cfg.fastica.pcaE + cfg.fastica.pcaD + cfg.fastica.whiteSig + cfg.fastica.whiteMat + cfg.fastica.dewhiteMat + cfg.fastica.only + + The binica method supports the following method-specific options. The + values that these options can take can be found with HELP BINICA. + cfg.binica.extended + cfg.binica.pca + cfg.binica.sphering + cfg.binica.lrate + cfg.binica.blocksize + cfg.binica.maxsteps + cfg.binica.stop + cfg.binica.weightsin + cfg.binica.verbose + cfg.binica.filenum + cfg.binica.posact + cfg.binica.annealstep + cfg.binica.annealdeg + cfg.binica.bias + cfg.binica.momentum + + The dss method requires the following method-specific option and supports + a whole lot of other options. The values that these options can take can + be found with HELP DSS_CREATE_STATE. + cfg.dss.denf.function + cfg.dss.denf.params + + The sobi method supports the following method-specific options. The + values that these options can take can be found with HELP SOBI. + cfg.sobi.n_sources + cfg.sobi.p_correlations + + The csp method implements the common-spatial patterns method. For CSP, the + following specific options can be defined: + cfg.csp.classlabels = vector that assigns a trial to class 1 or 2. + cfg.csp.numfilters = the number of spatial filters to use (default: 6). + + The icasso method implements icasso. It runs fastica a specified number of + times, and provides information about the stability of the components found + The following specific options can be defined, see ICASSOEST: + cfg.icasso.mode + cfg.icasso.Niter + + Instead of specifying a component analysis method, you can also specify + a previously computed unmixing matrix, which will be used to estimate the + component timecourses in this data. This requires + cfg.unmixing = NxN unmixing matrix + cfg.topolabel = Nx1 cell-array with the channel labels + + You may specify a particular seed for random numbers called by + rand/randn/randi, or the random state used by a previous call to this + function to replicate results. For example: + cfg.randomseed = integer seed value of user's choice + cfg.randomseed = comp.cfg.callinfo.randomseed (from previous call) + + 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_TOPOPLOTIC, FT_REJECTCOMPONENT, FASTICA, RUNICA, BINICA, SVD, + JADER, VARIMAX, DSS, CCA, SOBI, ICASSO + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_componentanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_compute_leadfield` + +```{text} + FT_COMPUTE_LEADFIELD computes a forward solution for a dipole in a a volume + conductor model. The forward solution is expressed as the leadfield matrix + (Nchan*3), where each column corresponds with the potential or field distributions + on all sensors for one of the x,y,z-orientations of the dipole. + + Use as + [lf] = ft_compute_leadfield(dippos, sens, headmodel, ...) + with input arguments + dippos = position dipole (1*3 or Ndip*3) + sens = structure with gradiometer or electrode definition + headmodel = structure with volume conductor definition + + The headmodel represents a volume conductor model, its contents + depend on the type of model. The sens structure represents a sensor + array, i.e. EEG electrodes or MEG gradiometers. + + It is possible to compute a simultaneous forward solution for EEG and MEG + by specifying sens and grad as two cell-arrays, e.g. + sens = {senseeg, sensmeg} + headmodel = {voleeg, volmeg} + This results in the computation of the leadfield of the first element of + sens and headmodel, followed by the second, etc. The leadfields of the + different imaging modalities are subsequently concatenated. + + Additional input arguments can be specified as key-value pairs, supported + optional arguments are + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + The leadfield weight may be used to specify a (normalized) corresponding surface + area for each dipole, e.g. when the dipoles represent a folded cortical surface + with varying triangle size. + + Depending on the specific input arguments for the sensor and volume, this function + will select the appropriate low-level EEG or MEG forward model. The leadfield + matrix for EEG will have an average reference over all the electrodes. + + The supported forward solutions for MEG are + infinite homogenous medium + single sphere (Cuffin and Cohen, 1977) + multiple spheres with one sphere per channel (Huang et al, 1999) + realistic single shell using superposition of basis functions (Nolte, 2003) + leadfield interpolation using a precomputed sourcemodel + boundary element method (BEM) + + The supported forward solutions for EEG are + infinite homogenous medium + infinite halfspace homogenous medium + single sphere + multiple concentric spheres (up to 4 spheres) + leadfield interpolation using a precomputed sourcemodel + boundary element method (BEM) + finite element method (FEM) + + See also FT_PREPARE_VOL_SENS, FT_HEADMODEL_ASA, FT_HEADMODEL_BEMCP, + FT_HEADMODEL_CONCENTRICSPHERES, FT_HEADMODEL_DIPOLI, FT_HEADMODEL_HALFSPACE, + FT_HEADMODEL_INFINITE, FT_HEADMODEL_LOCALSPHERES, FT_HEADMODEL_OPENMEEG, + FT_HEADMODEL_SINGLESHELL, FT_HEADMODEL_SINGLESPHERE, + FT_HEADMODEL_HALFSPACE, FT_HEADMODEL_DUNEURO + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_compute_leadfield.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_conjunctionanalysis` + +```{text} + FT_CONJUNCTIONANALYSIS finds the minimum statistic common across two or + more contrasts, i.e. data following ft_xxxstatistics. Furthermore, it + finds the overlap of sensors/voxels that show statistically significant + results (a logical AND on the mask fields). + + Alternatively, it finds minimalistic mean power values in the + input datasets. Here, a type 'relative change' baselinecorrection + prior to conjunction is advised. + + Use as + [stat] = ft_conjunctionanalysis(cfg, stat1, stat2, .., statN) + + where the input data is the result from either FT_TIMELOCKSTATISTICS, + FT_FREQSTATISTICS, or FT_SOURCESTATISTICS + + No configuration options are yet implemented. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_conjunctionanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_cancorr` + +```{text} + FT_CONNECTIVITY_CANCORR computes the canonical correlation or canonical coherence + between multiple variables. Canonical correlation analysis (CCA) is a way of + measuring the linear relationship between two multidimensional variables. It finds + two bases, one for each variable, that are optimal with respect to correlations + and, at the same time, it finds the corresponding correlations. + + Use as + [R] = ft_connectivity_cancorr(inputdata, ...) + + The input data should be a covariance or cross-spectral density array organized as + Channel x Channel + or + Channel x Channel (x Frequency) + + The output R represents the max(indices)*max(indices) canonical correlation matrix + or canonical coherence matrix. + + Additional optional input arguments come as key-value pairs: + 'indices' = 1xNchan vector with indices of the groups to which the channels belong, + e.g. [1 1 2 2] for a 2-by-2 connectivity between 2 planar MEG channels + 'realflag' = boolean flag whether to use the real-valued part only for the determination + of the rotation (default = false) + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_cancorr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_corr` + +```{text} + FT_CONNECTIVITY_CORR computes correlation, coherence or a related quantity from a + data-matrix containing a covariance or cross-spectral density. This implements the + methods as described in the following papers: + + Coherence: Rosenberg et al, The Fourier approach to the identification of + functional coupling between neuronal spike trains. Prog Biophys Molec + Biol 1989; 53; 1-31 + + Partial coherence: Rosenberg et al, Identification of patterns of + neuronal connectivity - partial spectra, partial coherence, and neuronal + interactions. J. Neurosci. Methods, 1998; 83; 57-72 + + Phase locking value: Lachaux et al, Measuring phase sychrony in brain + signals. Human Brain Mapping, 1999; 8; 194-208. + + Imaginary part of coherency: Nolte et al, Identifying true brain + interaction from EEG data using the imaginary part of coherence. Clinical + Neurophysiology, 2004; 115; 2292-2307 + + Use as + [c, v, n] = ft_connectivity_corr(inputdata, ...) + + The input data should be a covariance or cross-spectral density array organized as + Repetitions x Channel x Channel (x Frequency) (x Time) + or + Repetitions x Channelcombination (x Frequency) (x Time) + + If the input already contains an average, the first dimension must be singleton. + Furthermore, the input data can be complex-valued cross spectral densities, or + real-valued covariance estimates. If the former is the case, the output will be + coherence (or a derived metric), if the latter is the case, the output will be the + correlation coefficient. + + The output represents + c = the correlation/coherence + v = variance estimate, this can only be computed if the data contains leave-one-out samples + n = the number of repetitions in the input data + + Additional optional input arguments come as key-value pairs: + 'dimord' = string, specifying how the input matrix should be interpreted + 'hasjack' = boolean flag that specifies whether the repetitions represent leave-one-out samples + 'complex' = 'abs', 'angle', 'real', 'imag', 'complex', 'logabs' for post-processing of coherency + 'powindx' = required if the input data contain linearly indexed channel pairs. This + should be an Nx2 matrix indexing on each row for the respective channel + pair the indices of the corresponding auto-spectra. + 'pownorm' = boolean flag that specifies whether normalisation with the product + of the power should be performed (thus should be true when + correlation/coherence is requested, and false when covariance + or cross-spectral density is requested). + 'feedback' = 'none', 'text', 'textbar', 'dial', 'etf', 'gui' type of feedback showing progress of computation, see FT_PROGRESS + + Partialisation can be performed when the input data is (chan x chan). The following + option needs to be specified: + 'pchanindx' = index-vector to the channels that need to be partialised + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_corr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_csd2transfer` + +```{text} + FT_CONNECTIVITY_CSD2TRANSFER computes the transfer-function from frequency domain + data using the Wilson-Burg algorithm. The transfer function can be used for the + computation of directional measures of connectivity, such as Granger causality, + partial directed coherence, or directed transfer functions. + + Use as + [output] = ft_connectivity_csd2transfer(freq, ...) + + The input variable freq should be a FieldTrip data structure containing frequency + domain data containing the cross-spectral density computed between all pairs of + channels, thus containing a 'dimord' of 'chan_chan_freq(_time)'. + + Additional optional input arguments come as key-value pairs: + numiteration = scalar value (default: 100) the number of iterations + channelcmb = Nx2 cell-array listing the channel pairs for the spectral + factorization. If not defined or empty (default), a + full multivariate factorization is performed, otherwise + a multiple pairwise factorization is done. + tol = scalar value (default: 1e-18) tolerance limit truncating + the iterations + sfmethod = 'multivariate', or 'bivariate' + stabilityfix = false, or true. zigzag-reduction by means of tapering of the + intermediate time domain representation when computing the + plusoperator + + The code for the Wilson-Burg algorithm has been very generously provided by Dr. + Mukesh Dhamala, and Prof. Mingzhou Ding and his group, and has been adjusted for + efficiency. If you use this code for studying directed interactions, please cite + the following references: + - M.Dhamala, R.Rangarajan, M.Ding, Physical Review Letters 100, 018701 (2008). + - M.Dhamala, R.Rangarajan, M.Ding, Neuroimage 41, 354 (2008). + + See also FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_csd2transfer.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_dtf` + +```{text} + FT_CONNECTIVITY_DTF computes the directed transfer function. + + Use as + [d, v, n] = ft_connectivity_dtf(inputdata, ...) + + The input should be a spectral transfer matrix organized as + Nrpt x Nchan x Nchan x Nfreq (x Ntime) + where Nrpt can be 1. + + The output represents + d = partial directed coherence matrix Nchan x Nchan x Nfreq (x Ntime). + If multiple observations in the input, the average is returned. + v = variance of d across observations. + n = number of observations. + + Typically, nrpt should be 1 where the spectral transfer matrix is computed across + observations. When nrpt>1 and hasjack=true, the input is assumed to contain the + leave-one-out estimates of the spectral transfer matrix, thus a more reliable + estimate of the relevant quantities. + + Additional optional input arguments come as key-value pairs: + 'hasjack' = boolean, specifying whether the input contains leave-one-outs, + required for correct variance estimate (default = false) + 'crsspctrm' = matrix containing the cross-spectral density. If this + matrix is defined, the function returns the ddtf, which + requires an estimation of partial coherence from this matrix. + 'invfun' = 'inv' (default) or 'pinv', the function used to invert the + crsspctrm matrix to obtain the partial coherence. Pinv is + useful if the data are poorly-conditioned. + 'feedback' = 'none', 'text', 'textbar', 'dial', 'etf', 'gui' type of feedback showing progress of computation, see FT_PROGRESS + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_dtf.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_granger` + +```{text} + FT_CONNECTIVITY_GRANGER computes spectrally resolved granger causality. This + implementation is loosely based on the code used in Brovelli, et. al., PNAS 101, + 9849-9854 (2004). + + Use as + [granger, v, n] = ft_connectivity_granger(H, Z, S, ...) + + The input data should be + H = spectral transfer matrix, Nrpt x Nchan x Nchan x Nfreq (x Ntime), + or Nrpt x Nchancmb x Nfreq (x Ntime). Nrpt can be 1. + Z = the covariance matrix of the noise, Nrpt x Nchan x Nchan (x Ntime), + or Nrpt x Nchancmb (x Ntime). + S = the cross-spectral density matrix with the same dimensionality as H. + + Additional optional input arguments come as key-value pairs: + 'dimord' = required string specifying how to interpret the input data + supported values are 'rpt_chan_chan_freq(_time) and + 'rpt_chan_freq(_time), 'rpt_pos_pos_freq(_time)' and + 'rpt_pos_freq(_time)' + 'method' = 'granger' (default), or 'instantaneous', or 'total' + 'hasjack' = boolean, specifying whether the input contains leave-one-outs, + required for correct variance estimate (default = false) + 'powindx' = is a variable determining the exact computation, see below + + If the inputdata is such that the channel-pairs are linearly indexed, granger + causality is computed per quadruplet of consecutive entries, where the convention + is as follows: + + H(:, (k-1)*4 + 1, :, :, :) -> 'chan1-chan1' + H(:, (k-1)*4 + 2, :, :, :) -> 'chan1->chan2' + H(:, (k-1)*4 + 3, :, :, :) -> 'chan2->chan1' + H(:, (k-1)*4 + 4, :, :, :) -> 'chan2->chan2' + + The same holds for the Z and S matrices. + + Pairwise block-granger causality can be computed when the inputdata has + dimensionality Nchan x Nchan. In that case 'powindx' should be specified, as a 1x2 + cell-array indexing the individual channels that go into each 'block'. + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_granger.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_mim` + +```{text} + FT_CONNECTIVITY_MIM computes the multivariate interaction measure from a + data-matrix containing the cross-spectral density. This implements the method + described in Ewald et al., Estimating true brain connectivity from EEG/MEG data + invariant to linear and static trasformations in sensor space. Neuroimage, 2012; + 476:488. + + Use as + [m] = hcp_connectivity_mim(inputdata, ...) + + The input data should be an array organized as + Channel x Channel x Frequency + + The output m contains the newChannel x newChannel x Frequency connectivity measure, + with newChannel equal to max(indices). + + Additional optional input arguments come as key-value pairs: + 'indices' = 1xN vector with indices of the groups to which the channels belong, + e.g. [1 1 2 2] for a 2-by-2 connectivity between 2 planar MEG channels. + + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_mim.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_mutualinformation` + +```{text} + FT_CONNECTIVITY_MUTUALINFORMATION computes mutual information using either the + information breakdown toolbox (ibtb), as described in Magri et al., BMC + Neuroscience 2009, 1471-2202, or Robin Ince's Gaussian copula based parametric + approach (gcmi). + + Use as + mi = ft_connectivity_mutualinformation(inputdata, ...) + + The input data should be a Nchan x Nobservations matrix. + + The output mi contains the estimated mutual information between all channels and + the reference channels. + + Additional input arguments come as key-value pairs: + method = string, 'ibtb' or 'gcmi' (default = 'gcmi') + + The default method has changed from 'ibtb' to 'gcmi' in December 2022. The former method + is based on an external toolbox that is not actively supported anymore. Moreover, the + Gaussian-Copula based Mutual Information does not depend on a binning strategy, and may + provide reasonable results also in the presence of low amounts of data. The change in + default reflects the default defined in ft_connectivityanalysis. + + Additional input arguments for the 'ibtb' method: + 'histmethod' = The way that histograms are generated from the data. Possible values + are 'eqpop' (default), 'eqspace', 'ceqspace', 'gseqspace'. + See the help of the 'binr' function in the ibtb toolbox for more information. + 'numbin' = scalar value. The number of bins used to create the histograms needed for + the entropy computations + 'opts' = structure that is passed on to the 'information' function in the ibtb + toolbox. See the help of that function for more information. + 'refindx' = scalar value or 'all'. The channel that is used as 'reference channel'. + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_mutualinformation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_pdc` + +```{text} + FT_CONNECTIVITY_PDC computes partial directed coherence. This function implements + the metrices described in Baccala et al., Biological Cybernetics 2001, 84(6), + 463-74. and in Baccala et al., 15th Int.Conf.on DSP 2007, 163-66. + + The implemented algorithm has been tested against the implementation in the + SIFT-toolbox. It yields numerically identical results to what is known there as + 'nPDC' (for PDC) and 'GPDC' for generalized pdc. + + Use as + [p, v, n] = ft_connectivity_pdc(inputdata, ...) + + The input data should be a spectral transfer matrix organized as + Nrpt x Nchan x Nchan x Nfreq (x Ntime), + where Nrpt can be 1. + + Additional optional input arguments come as key-value pairs: + 'hasjack' = 0 (default) is a boolean specifying whether the input + contains leave-one-outs, required for correct variance + estimate + 'invfun' = 'inv' (default) or 'pinv', the function used to invert the + transfer matrix to obtain the fourier transform of the + MVAR coefficients. Use 'pinv' if the data are + poorly-conditioned. + 'noisecov' = matrix containing the covariance of the residuals of the + MVAR model. If this matrix is defined, the function + returns the generalized partial directed coherence. + 'feedback' = 'none', 'text', 'textbar', 'dial', 'etf', 'gui' type of feedback showing progress of computation, see FT_PROGRESS + + Output arguments: + p = partial directed coherence matrix Nchan x Nchan x Nfreq (x Ntime). + If multiple observations in the input, the average is returned. + v = variance of p across observations. + n = number of observations. + + Typically, nrpt should be 1 (where the spectral transfer matrix is + computed across observations. When nrpt>1 and hasjack is true the input + is assumed to contain the leave-one-out estimates of H, thus a more + reliable estimate of the relevant quantities. + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_pdc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_plm` + +```{text} + FT_CONNECTIVITY_PLM computes the phase linearity measurement from a cell array of + time-domain data, where each cell is an epoch. This implements the metric described + in Baselice et al. "Phase Linearity Measurement: a novel index for brain functional + connectivity", IEEE Transactions on Medical Imaging, 2018. + + Use as + [p] = ft_connectivity_plm(inputdata, ...) + + The input data input should be organized as a cell-array, one element for each + epoch/repetition. Each cell should be a matrix of of nchan x nsamples values. + + Additional optional input arguments come as key-value pairs: + 'bandwidth' = scalar, half-bandwidth parameter: the frequency range across which to integrate + 'fsample' = sampling frequency, needed to convert bandwidth to number of bins + + The output p contains the phase linearity measurement in the [0, 1] interval. It is + organized as a 3D matrix of Nrpt x Nchan x Nchan dimensions. + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_plm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_powcorr_ortho` + +```{text} + FT_CONNECTIVITY_POWCORR_ORTHO computes power correlation after removing + the zero-lag contribution on a trial-by-trial basis, according to Hipp's + Nature Neuroscience paper. + + Use as + [c] = ft_connectivity_powcorr(inputdata, ...) + + Where the input is a Nchan*Nrpt matrix containing the complex-valued amplitude + and phase information at a given frequency. + + The output c is a Nchan*Nref matrix that contain the power correlation for all + channels orthogonalised relative to the reference channel in the first Nref + columns, and the power correlation for the reference channels orthogonalised + relative to the channels in the second Nref columns. + + Additional optional input arguments come as key-value pairs: + 'refindx' = index/indices of the channels that serve as a reference channel (default is all) + 'tapvec' = vector with the number of tapers per trial + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_powcorr_ortho.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_ppc` + +```{text} + FT_CONNECTIVITY_PPC computes pairwise phase consistency or weighted pairwise phase + consistency from a data-matrix containing a cross-spectral density. This implements + the method described in Vinck M, van Wingerden M, Womelsdorf T, Fries P, Pennartz + CM. The pairwise phase consistency: a bias-free measure of rhythmic neuronal + synchronization. Neuroimage. 2010 May 15;51(1):112-22. + + Use as + [c, v, n] = ft_connectivity_ppc(inputdata, ...) + + Where the input data input should be organized as: + Repetitions x Channel x Channel (x Frequency) (x Time) + or + Repetitions x Channelcombination (x Frequency) (x Time) + + The first dimension should contain repetitions and should not contain an average + already. Also, it should not consist of leave-one-out averages. + + The output c contains the ppc, v is a leave-one-out variance estimate which is only + computed if dojack = 1,and n is the number of repetitions in the input data. + + Additional optional input arguments come as key-value pairs: + 'dojack' = boolean specifying whether the repetitions represent leave-one-out samples + 'weighted' = boolean, whether to compute unweighted ppc or weighted ppc, the weighting + is according to the magnitude of the cross-spectrum + 'feedback' = 'none', 'text', 'textbar', 'dial', 'etf', 'gui' type of feedback showing progress of computation, see FT_PROGRESS + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_ppc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_psi` + +```{text} + FT_CONNECTIVITY_PSI computes the phase slope index from a data-matrix containing + the cross-spectral density. This implements the method described in Nolte et al., + Robustly estimating the flow direction of information in complex physical systems. + Physical Review Letters, 2008; 100; 234101. + + Use as + [c, v, n] = ft_connectivity_psi(inputdata, ...) + + Where the input data input should be organized as + Repetitions x Channel x Channel (x Frequency) (x Time) + or + Repetitions x Channelcombination (x Frequency) (x Time) + + The first dimension should be singleton if the input already contains an + average. + + The output p contains the phase slope index, v is a variance estimate which only + can be computed if the data contains leave-one-out samples, and n is the number of + repetitions in the input data. If the phase slope index is positive, then the first + chan (1st dim) becomes more leading (or less lagged) with higher frequency, + indicating that it is causally driving the second channel (2nd dim). + + Additional optional input arguments come as key-value pairs: + 'nbin' = scalar, half-bandwidth parameter: the number of frequency bins across which to integrate + 'hasjack' = boolean, specifying whether the repetitions represent leave-one-out samples (allowing for a variance estimate) + 'feedback' = 'none', 'text', 'textbar', 'dial', 'etf', 'gui' type of feedback showing progress of computation, see FT_PROGRESS + 'dimord' = string, specifying how the input matrix should be interpreted + 'powindx' = ? + 'normalize' = ? + + See also CONNECTIVITY, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_psi.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivity_wpli` + +```{text} + FT_CONNECTIVITY_WPLI computes the weighted phase lag index from a data matrix + containing the cross-spectral density. This implements the method described in + Vinck M, Oostenveld R, van Wingerden M, Battaglia F, Pennartz CM. An improved index + of phase-synchronization for electrophysiological data in the presence of + volume-conduction, noise and sample-size bias. Neuroimage. 2011 Apr + 15;55(4):1548-65. + + Use as + [wpi, v, n] = ft_connectivity_wpli(inputdata, ...) + + The input data input should contain cross-spectral densities organized as: + Repetitions x Channel x Channel (x Frequency) (x Time) + or + Repetitions x Channelcombination (x Frequency) (x Time) + + Alternatively, the input data can contain fourier coefficients organized + as: + Repetitions_tapers x Channel (x Frequency) (x Time) + + The first dimension of the input data matrix should contain repetitions and should not + contain an average already. Also, the input should not consist of leave-one-out averages. + + The output wpli contains the wpli, v is a leave-one-out variance estimate + which is only computed if dojack=true, and n is the number of repetitions + in the input data. + + Additional optional input arguments come as key-value pairs: + 'dojack' = boolean, compute a variance estimate based on + leave-one-out, only supported when input data is a + bivariate cross-spectral density + 'debias' = boolean, compute debiased wpli or not + 'feedback' = 'none', 'text', 'textbar', 'dial', 'etf', 'gui' type of feedback + showing progress of computation, see FT_PROGRESS + 'isunivariate' = boolean, compute CSD on fly (saves memory with many trials) + 'cumtapcnt' = vector that contains the cumulative taper counter, defining how + tapers should be combined to define repetitions. If not + defined (or empty), it will be ones(size(input,1),1), + i.e. each slice of the matrix is considered a repetition. + This option is only function in case isunivariate = true + + See also FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/connectivity/ft_connectivity_wpli.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivityanalysis` + +```{text} + FT_CONNECTIVITYANALYSIS computes various measures of connectivity between + MEG/EEG channels or between source-level signals. + + Use as + stat = ft_connectivityanalysis(cfg, data) + stat = ft_connectivityanalysis(cfg, timelock) + stat = ft_connectivityanalysis(cfg, freq) + stat = ft_connectivityanalysis(cfg, source) + where the first input argument is a configuration structure (see below) + and the second argument is the output of FT_PREPROCESSING, + FT_TIMELOCKANLAYSIS, FT_FREQANALYSIS, FT_MVARANALYSIS or FT_SOURCEANALYSIS. + + The different connectivity metrics are supported only for specific + datatypes (see below). + + The configuration structure has to contain + cfg.method = string, can be + 'amplcorr', amplitude correlation, support for freq and source data + 'coh', coherence, support for freq, freqmvar and source data. + For partial coherence also specify cfg.partchannel, see below. + For imaginary part of coherency or coherency also specify + cfg.complex, see below. + 'csd', cross-spectral density matrix, can also calculate partial + csds - if cfg.partchannel is specified, support for freq + and freqmvar data + 'dtf', directed transfer function, support for freq and freqmvar data + 'granger', granger causality, support for freq and freqmvar data + 'pdc', partial directed coherence, support for freq and freqmvar data + 'plv', phase-locking value, support for freq and freqmvar data + 'powcorr', power correlation, support for freq and source data + 'powcorr_ortho', power correlation with single trial + orthogonalisation, support for source data + 'ppc' pairwise phase consistency + 'psi', phaseslope index, support for freq and freqmvar data + 'wpli', weighted phase lag index (signed one, still have to + take absolute value to get indication of strength of + interaction. Note that this measure has a positive + bias. Use wpli_debiased to avoid this. + 'wpli_debiased' debiased weighted phase lag index (estimates squared wpli) + 'wppc' weighted pairwise phase consistency + 'corr' Pearson correlation, support for timelock or raw data + 'laggedcoherence', lagged coherence estimate + 'plm' phase linearity measurement + 'mim' multivariate interaction measure, support for freq data + 'cancoh' canonical coherence, support for freq data + + Additional configuration options are + cfg.channel = Nx1 cell-array containing a list of channels which are + used for the subsequent computations. This only has an effect + when the input data is univariate. See FT_CHANNELSELECTION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_connectivityanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivityplot` + +```{text} + FT_CONNECTIVITYPLOT plots channel-level frequency resolved connectivity. The + data are rendered in a square grid of subplots, each subplot containing the + connectivity spectrum between the two respective channels. + + Use as + ft_connectivityplot(cfg, data) + where the first input argument is a configuration structure (see below) + and the input data is a structure obtained from FT_CONNECTIVITYANALYSIS + using a frequency-domain connectivity metric. Consequently the input data + should have a dimord of 'chan_chan_freq', or 'chan_chan_freq_time'. + + The configuration can have the following options + cfg.parameter = string, the functional parameter to be plotted (default = 'cohspctrm') + cfg.xlim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [xmin xmax] (default = 'maxmin') + cfg.ylim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [ymin ymax] (default = 'maxmin') + cfg.zlim = plotting limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.channel = list of channels to be included for the plotting (default = 'all'), see FT_CHANNELSELECTION for details + + See also FT_CONNECTIVITYANALYSIS, FT_CONNECTIVITYSIMULATION, FT_MULTIPLOTCC, FT_TOPOPLOTCC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_connectivityplot.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_connectivitysimulation` + +```{text} + FT_CONNECTIVITYSIMULATION simulates channel-level time-series data with a + specified connectivity structure. This function returns an output data + structure that resembles the output of FT_PREPROCESSING. + + Use as + [data] = ft_connectivitysimulation(cfg) + which will return a raw data structure that resembles the output of + FT_PREPROCESSING. + + The configuration structure should contain + cfg.method = string, can be 'linear_mix', 'mvnrnd', 'ar', 'ar_reverse' (see below) + cfg.nsignal = scalar, number of signals + cfg.ntrials = scalar, number of trials + cfg.triallength = in seconds + cfg.fsample = in Hz + + Method 'linear_mix' implements a linear mixing with optional time shifts + where the number of unobserved signals can be different from the number + of observed signals + + Required configuration options: + cfg.mix = matrix, [nsignal x number of unobserved signals] + specifying the mixing from the unobserved signals to + the observed signals, or + = matrix, [nsignal x number of unobserved signals x number of + samples] specifying the mixing from the + unobserved signals to the observed signals which + changes as a function of time within the trial + = cell-arry, [1 x ntrials] with each cell a matrix as + specified above, when a trial-specific mixing is + required + cfg.delay = matrix, [nsignal x number of unobserved signals] + specifying the time shift (in samples) between the + unobserved signals and the observed signals + + Optional configuration options + cfg.bpfilter = 'yes' (or 'no') + cfg.bpfreq = [bplow bphigh] (default: [15 25]) + cfg.demean = 'yes' (or 'no') + cfg.baselinewindow = [begin end] in seconds, the default is the complete trial + cfg.absnoise = scalar (default: 1), specifying the standard deviation of + white noise superimposed on top of the simulated signals + cfg.randomseed = 'yes' or a number or vector with the seed value (default = 'yes') + + Method 'mvnrnd' implements a linear mixing with optional timeshifts in + where the number of unobserved signals is equal to the number of observed + signals. This method used the MATLAB function mvnrnd. The implementation + is a bit ad-hoc and experimental, so users are discouraged to apply it. + The time shift occurs only after the linear mixing, so the effect of the + parameters on the simulation is not really clear. This method will be + disabled in the future. + + Required configuration options + cfg.covmat = covariance matrix between the signals + cfg.delay = delay vector between the signals in samples + + Optional configuration options + cfg.bpfilter = 'yes' (or 'no') + cfg.bpfreq = [bplow bphigh] (default: [15 25]) + cfg.demean = 'yes' (or 'no') + cfg.baselinewindow = [begin end] in seconds, the default is the complete trial + cfg.absnoise = scalar (default: 1), specifying the standard + deviation of white noise superimposed on top + of the simulated signals + + Method 'ar' implements a multivariate autoregressive model to generate + the data. + + Required configuration options + cfg.params = matrix, [nsignal x nsignal x number of lags] specifying the + autoregressive coefficient parameters. A non-zero + element at cfg.params(i,j,k) means a + directional influence from signal j onto + signal i (at lag k). + cfg.noisecov = matrix, [nsignal x nsignal] specifying the covariance + matrix of the innovation process + + Method 'ar_reverse' implements a multivariate autoregressive + autoregressive model to generate the data, where the model coefficients + are reverse-computed, based on the interaction pattern specified. + + Required configuration options + cfg.coupling = nxn matrix, specifying coupling strength, rows causing + column + cfg.delay = nxn matrix, specifying the delay, in seconds, from one + signal's spectral component to the other signal, rows + causing column + cfg.ampl = nxn matrix, specifying the amplitude + cfg.bpfreq = nxnx2 matrix, specifying the lower and upper frequencies + of the bands that are transmitted, rows causing column + + The generated signals will have a spectrum that is 1/f + additional + band-limited components, as specified in the configuration. + + See also FT_FREQSIMULATION, FT_DIPOLESIMULATION, FT_SPIKESIMULATION, + FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_connectivitysimulation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_convert_coordsys` + +```{text} + FT_CONVERT_COORDSYS changes the coordinate system of the input object to the + specified coordinate system. The coordinate system of the input object is + determined from the 'coordsys' field in the input data, or needs to be determined + and specified interactively by the user. + + Use as + [output] = ft_convert_coordsys(input, target) + [output] = ft_convert_coordsys(input, target, method) + [output] = ft_convert_coordsys(input, target, method, template) + to determine and convert the coordinate system. + + With the optional method input argument you can determine whether to use SPM for an + affine or non-linear transformation. + method = 0: only an approximate coregistration (default for non-MRI data) + method = 1: an approximate coregistration, followed by spm_affreg + method = 2: an approximate coregistration, followed by spm_normalise (default for MRI data) + + The following input data structures are supported + electrode or gradiometer array, see FT_DATATYPE_SENS + volume conduction model, see FT_DATATYPE_HEADMODEL + source model, see FT_DATATYPE_SOURCE and FT_PREPARE_SOURCEMODEL + anatomical mri, see FT_DATATYPE_VOLUME + segmented mri, see FT_DATATYPE_SEGMENTATION + anatomical or functional atlas, see FT_READ_ATLAS + + Recognized and supported coordinate systems are 'ctf', 'bti', '4d', 'yokogawa', + 'eeglab', 'neuromag', 'itab', 'acpc', 'spm', 'mni', 'fsaverage', 'tal', 'scanras', + 'scanlps', 'dicom'. + + Furthermore, supported coordinate systems that do not specify the origin are 'ras', + 'als', 'lps', etc. See https://www.fieldtriptoolbox.org/faq/coordsys for more + details. + + Note that the conversion will be an automatic and approximate conversion, not + taking into account differences in individual anatomies/differences in conventions + where to put the fiducials. + + See also FT_DETERMINE_COORDSYS, FT_DETERMINE_UNITS, FT_CONVERT_UNITS, FT_PLOT_AXES, FT_PLOT_XXX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_convert_coordsys.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_convert_units` + +```{text} + FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit. + The units of the input object is determined from the structure field + object.unit, or is estimated based on the spatial extend of the structure, + e.g. a volume conduction model of the head should be approximately 20 cm large. + + Use as + [output] = ft_convert_units(input, target) + + The following input data structures are supported + electrode or gradiometer array, see FT_DATATYPE_SENS + volume conductor, see FT_DATATYPE_HEADMODEL + anatomical mri, see FT_DATATYPE_VOLUME + segmented mri, see FT_DATATYPE_SEGMENTATION + source model, see FT_DATATYPE_SOURCE and FT_PREPARE_SOURCEMODEL + + The possible target units are 'm', 'cm ' or 'mm'. If no target units are specified, + this function will only determine the geometrical units of the input object. + + See also FT_DETERMINE_UNITS, FT_DETERMINE_COORDSYS, FT_CONVERT_COORDSYS, FT_PLOT_AXES, FT_PLOT_XXX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_convert_units.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_create_buffer` + +```{text} + FT_CREATE_BUFFER starts the thread with the TCP server attached to the local + MATLAB instance. The TCP server will listen to the specified network + port, and accept incoming read and write requests. + + Use as + ft_create_buffer(port) + where port is the TCP port to which the server listens. The default port + number is 1972. + + See also FT_DESTROY_BUFFER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_create_buffer.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_crossfrequencyanalysis` + +```{text} + FT_CROSSFREQUENCYANALYSIS performs cross-frequency analysis + + Use as + crossfreq = ft_crossfrequencyanalysis(cfg, freq) + crossfreq = ft_crossfrequencyanalysis(cfg, freqlo, freqhi) + + The input data should be organised in a structure as obtained from the + FT_FREQANALYSIS function. The configuration should be according to + + cfg.freqlow = scalar or vector, selection of frequencies for the low frequency data + cfg.freqhigh = scalar or vector, selection of frequencies for the high frequency data + + Channel selection can be specified according to whether one wants to perform within- or + cross-channel analysis. + + For within-channel analysis (default), you should specifies only a single channel selection: + cfg.channel = cell-array with selection of channels, see FT_CHANNELSELECTION + In this case, the output "dimord" will be "chan_freqlow_freqhigh" + + For cross-channel analysis, you should specifies two channel selections: + cfg.chanlow = cell-array with selection of channels for the phase providing channels from the + freqlow data argument, with wildcards allowed, see FT_CHANNELSELECTION + cfg.chanhigh = cell-array with selection of channels for the amplitude providing channels from the + freqhigh data argument, with wildcards allowed, see FT_CHANNELSELECTION + In this case, the output "dimord" will be "chancmb_freqlow_freqhigh" and "label" + field will be replaced with "labelcmb" (corresponding to the dimension "chancmb") + describing the pairs of channel combinations as + {'chanlow01' 'chanhigh01' + 'chanlow01' 'chanhigh02' + ... + 'chanlow02' 'chanhigh01' + 'chanlow02' 'chanhigh02' + ... + } + N.B.: The order of channels corresponds to their order in the original "label" field + + Various metrics for cross-frequency coupling have been introduced in a number of + scientific publications, but these do not use a consistent method naming scheme, + nor implement it in exactly the same way. The particular implementation in this + code tries to follow the most common format, generalizing where possible. If you + want details about the algorithms, please look into the code. + cfg.method = string, can be + 'coh' - coherence + 'plv' - phase locking value + 'mvl' - mean vector length + 'mi' - modulation index + 'pac' - phase amplitude coupling + + The modulation index and phase amplitude coupling implement + Tort A. B. L., Komorowski R., Eichenbaum H., Kopell N. (2010). Measuring Phase-Amplitude + Coupling Between Neuronal Oscillations of Different Frequencies. J Neurophysiol 104: + 1195?1210. doi:10.1152/jn.00106.2010 + + cfg.keeptrials = string, can be 'yes' or 'no' + + See also FT_FREQANALYSIS, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_crossfrequencyanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_databrowser` + +```{text} + FT_DATABROWSER can be used for visual inspection of data. Artifacts that were + detected by artifact functions (see FT_ARTIFACT_xxx functions where xxx is the type + of artifact) are marked. Additionally data pieces can be marked and unmarked as + artifact by manual selection. The output cfg contains the updated specification of + the artifacts. + + Use as + [cfg] = ft_databrowser(cfg) + [cfg] = ft_databrowser(cfg, data) + If you only specify the configuration structure, it should contain the name of the + dataset on your hard disk (see below). If you specify input data, it should be a + data structure as obtained from FT_PREPROCESSING or from FT_COMPONENTANALYSIS. + + If you want to browse data that is on disk, you have to specify + cfg.dataset = string with the filename + Instead of specifying the dataset, you can also explicitely specify the name of the + file containing the header information and the name of the file containing the + data, using + cfg.datafile = string with the filename + cfg.headerfile = string with the filename + + The following configuration options are supported: + cfg.ylim = vertical scaling, can be 'maxmin', 'maxabs' or [ymin ymax] (default = 'maxabs') + cfg.zlim = color scaling to apply to component topographies, 'minmax', 'maxabs' (default = 'maxmin') + cfg.blocksize = duration in seconds for cutting continuous data in segments + cfg.trl = structure that defines the data segments of interest, only applicable for trial-based data + cfg.continuous = 'yes' or 'no', whether the data should be interpreted as continuous or trial-based + cfg.allowoverlap = 'yes' or 'no', whether data that is overlapping in multiple trials is allowed (default = 'no') + cfg.channel = cell-array with channel labels, see FT_CHANNELSELECTION + cfg.channelclamped = cell-array with channel labels, that when using the 'vertical' viewmode will always be shown at the bottom. This is useful for showing ECG/EOG channels along with the other channels + cfg.compscale = string, 'global' or 'local', defines whether the colormap for the topographic scaling is applied per topography or on all visualized components (default = 'local') + cfg.viewmode = string, 'vertical', 'butterfly', or 'component' for visualizing ICA/PCA topographies together with the timecourses (default = 'vertical') + cfg.plotlabels = 'yes', 'no' or 'some', whether to plot channel labels in vertical viewmode. The option 'some' plots one label for every ten channels, which is useful if there are many channels (default = 'some') + cfg.plotevents = 'no' or 'yes', whether to plot event markers (default = 'yes') + cfg.ploteventlabels = 'type=value', 'colorvalue' (default = 'type=value') + cfg.eventcolor = string with line colors or Nx3 color map, colors used for plotting the different types of events (default is automatic) + cfg.artifactcolor = string with line colors or Nx3 color map, colors used for plotting the different types of artifacts (default is automatic) + cfg.artfctdef.xxx.artifact = Nx2 matrix with artifact segments see FT_ARTIFACT_xxx functions + cfg.selectfeature = string, name of feature to be selected/added (default = 'visual') + cfg.selectmode = 'markartifact', 'markpeakevent', 'marktroughevent' (default = 'markartifact') + cfg.colorgroups = 'sequential', 'allblack', 'labelcharN' (N = Nth character in label), 'chantype' or a vector with the length of the number of channels defining the groups (default = 'sequential') + cfg.linecolor = string with line colors or Nx3 color map (default = customized lines map with 15 colors) + cfg.linewidth = linewidth in points (default = 0.5) + cfg.linestyle = linestyle/marker type, see options of the PLOT function (default = '-') + cfg.verticalpadding = number or 'auto', padding to be added to top and bottom of plot to avoid channels largely dissappearing when viewmode = 'vertical'/'component' (default = 'auto'). The padding is expressed as a proportion of the total height added to the top and bottom. The setting 'auto' determines the padding depending on the number of channels that are being plotted. + cfg.selfun = string, name of function that is evaluated using the right-click context menu. The selected data and cfg.selcfg are passed on to this function. + cfg.selcfg = configuration options for function in cfg.selfun + cfg.seldat = 'selected' or 'all', specifies whether only the currently selected or all channels will be passed to the selfun (default = 'selected') + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.visible = string, 'on' or 'off' whether figure will be visible (default = 'on') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + + The following options for the scaling of the EEG, EOG, ECG, EMG, MEG and NIRS channels + is optional and can be used to bring the absolute numbers of the different + channel types in the same range (e.g. fT and uV). The channel types are determined + from the input data using FT_CHANNELSELECTION. + cfg.eegscale = number, scaling to apply to the EEG channels prior to display + cfg.eogscale = number, scaling to apply to the EOG channels prior to display + cfg.ecgscale = number, scaling to apply to the ECG channels prior to display + cfg.emgscale = number, scaling to apply to the EMG channels prior to display + cfg.megscale = number, scaling to apply to the MEG channels prior to display + cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor) + cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor) + cfg.nirsscale = number, scaling to apply to the NIRS channels prior to display + cfg.mychanscale = number, scaling to apply to the channels specified in cfg.mychan + cfg.mychan = Nx1 cell-array with selection of channels + cfg.chanscale = Nx1 vector with scaling factors, one per channel specified in cfg.channel + + You can specify preprocessing options that are to be applied to the data prior to + display. Most options from FT_PREPROCESSING are supported. They should be specified + in the sub-structure cfg.preproc like these examples + cfg.preproc.lpfilter = 'no' or 'yes' lowpass filter (default = 'no') + cfg.preproc.lpfreq = lowpass frequency in Hz + cfg.preproc.demean = 'no' or 'yes', whether to apply baseline correction (default = 'no') + cfg.preproc.detrend = 'no' or 'yes', remove linear trend from the data (done per trial) (default = 'no') + cfg.preproc.baselinewindow = [begin end] in seconds, the default is the complete trial (default = 'all') + + In case of component viewmode, a layout is required. If no layout is specified, an + attempt is made to construct one from the sensor definition that is present in the + data or specified in the configuration. + cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + Additional plotting options for the component viewmode: + cfg.gridscale = scalar, number of points along both directions for interpolation (default = 45 here) + cfg.shading = string, 'none', 'flat', 'interp' (default = 'flat') + cfg.interplimits = string, 'sensors' or 'mask' (default here = 'mask') + cfg.interpolation = string, 'nearest', 'linear', 'natural', 'cubic' or 'v4' (default = 'v4') + cfg.contournum = topoplot contour lines + + The default font size might be too small or too large, depending on the number of + channels. You can use the following options to change the size of text inside the + figure and along the axes. + cfg.fontsize = number, fontsize inside the figure (default = 0.03) + cfg.fontunits = string, can be 'normalized', 'points', 'pixels', 'inches' or 'centimeters' (default = 'normalized') + cfg.axisfontsize = number, fontsize along the axes (default = 10) + cfg.axisfontunits = string, can be 'normalized', 'points', 'pixels', 'inches' or 'centimeters' (default = 'points') + + When visually selection data, a right-click will bring up a context-menu containing + functions to be executed on the selected data. You can use your own function using + cfg.selfun and cfg.selcfg. You can use multiple functions by giving the names/cfgs + as a cell-array. + + In butterfly and vertical mode, you can use the "identify" button to reveal the name of a + channel. Please be aware that it searches only vertically. This means that it will + return the channel with the amplitude closest to the point you have clicked at the + specific time point. This might be counterintuitive at first. + + The "cfg.artfctdef" structure in the output cfg is comparable to the configuration + used by the artifact detection functions like FT_ARTIFACT_ZVALUE and in + FT_REJECTARTIFACT. It contains for each artifact type an Nx2 matrix in which the + first column corresponds to the begin samples of an artifact period, the second + column contains the end samples of the artifact periods. + + In case the databrowser crashes and you cannot close the window, use delete(gcf) to + get rid of the figure. + + See also FT_PREPROCESSING, FT_REJECTARTIFACT, FT_ARTIFACT_EOG, FT_ARTIFACT_MUSCLE, + FT_ARTIFACT_JUMP, FT_ARTIFACT_MANUAL, FT_ARTIFACT_THRESHOLD, FT_ARTIFACT_CLIP, + FT_ARTIFACT_ECG, FT_COMPONENTANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_databrowser.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype` + +```{text} + FT_DATATYPE determines the type of data represented in a FieldTrip data structure + and returns a string with raw, freq, timelock source, comp, spike, source, volume, + dip, montage, event. + + Use as + [type, dimord] = ft_datatype(data) + [bool] = ft_datatype(data, desired) + + See also FT_DATATYPE_COMP, FT_DATATYPE_FREQ, FT_DATATYPE_MVAR, + FT_DATATYPE_SEGMENTATION, FT_DATATYPE_PARCELLATION, FT_DATATYPE_SOURCE, + FT_DATATYPE_TIMELOCK, FT_DATATYPE_DIP, FT_DATATYPE_HEADMODEL, + FT_DATATYPE_RAW, FT_DATATYPE_SENS, FT_DATATYPE_SPIKE, FT_DATATYPE_VOLUME + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_comp` + +```{text} + FT_DATATYPE_COMP describes the FieldTrip MATLAB structure for comp data + + The comp data structure represents time-series channel-level data that has + been decomposed or unmixed from the channel level into its components or + "blind sources", for example using ICA (independent component analysis) or + PCA. This data structure is usually generated with the FT_COMPONENTANALYSIS + function. + + An example of a decomposed raw data structure with 100 components that resulted from + a 151-channel MEG recording is shown here: + + topo: [151x100 double] the component topographies + unmixing: [100x151 double] the component unmixing matrix + topolabel: {151x1 cell} the channel labels (e.g. 'MRC13') + label: {100x1 cell} the component labels (e.g. 'runica001') + time: {1x10 cell} the time axis [1*Ntime double] per trial + trial: {1x10 cell} the numeric data [151*Ntime double] per trial + grad: [1x1 struct] information about the sensor array (for EEG it is called elec) + cfg: [1x1 struct] the configuration used by the function that generated this data structure + + The only difference to the raw data structure is that the comp structure contains + the additional fields unmixing, topo and topolabel. Besides representing the time + series information as a raw data structure (see FT_DATATYPE_RAW), it is also + possible for time series information to be represented as timelock or freq + structures (see FT_DATATYPE_TIMELOCK or FT_DATATYPE_FREQ). + + Required fields: + - unmixing, topo, topolabel + + Optional fields: + - cfg, all fields from FT_DATATYPE_RAW, FT_DATATYPE_TIMELOCK or FT_DATATYPE_FREQ + + Historical fields: + - offset, fsample + + Revision history: + (2014) The combination of comp with raw, timelock or freq has been defined explicitly. + + (2011) The unmixing matrix has been added to the component data structure. + + (2003) The initial version was defined + + See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, FT_DATATYPE_FREQ, + FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, FT_DATATYPE_SPIKE, + FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_comp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_dip` + +```{text} + FT_DATATYPE_DIP descripts the FieldTrip MATLAB structure for dip data + + The dip structure represents a dipole model that has been fitted to + ERP or ERF data using a non-linear optimization approach. It is + usually generated by the FT_DIPOLEFITTING function. + + FIXME more information should be added here + + See also FT_DATATYPE, FT_DATATYPE_SOURCE, FT_DATATYPE_VOLUME + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_dip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_freq` + +```{text} + FT_DATATYPE_FREQ describes the FieldTrip MATLAB structure for freq data + + The freq data structure represents frequency or time-frequency decomposed + channel-level data. This data structure is usually generated with the + FT_FREQANALYSIS function. + + An example of a freq data structure containing the powerspectrum for 306 channels + and 120 frequencies is + + dimord: 'chan_freq' defines how the numeric data should be interpreted + powspctrm: [306x120 double] the power spectrum + label: {306x1 cell} the channel labels + freq: [1x120 double] the frequencies expressed in Hz + cfg: [1x1 struct] the configuration used by the function that generated this data structure + + An example of a freq data structure containing the time-frequency resolved + spectral estimates of power (i.e. TFR) for 306 channels, 120 frequencies + and 60 timepoints is + + dimord: 'chan_freq_time' defines how the numeric data should be interpreted + powspctrm: [306x120x60 double] the power spectrum + label: {306x1 cell} the channel labels + freq: [1x120 double] the frequencies, expressed in Hz + time: [1x60 double] the time, expressed in seconds + cfg: [1x1 struct] the configuration used by the function that generated this data structure + + Required fields: + - freq, dimord, label or labelcmb + + Optional fields: + - powspctrm, fouriesspctrm, csdspctrm, cohspctrm, time, grad, elec, cumsumcnt, cumtapcnt, trialinfo + + Deprecated fields: + - + + Obsoleted fields: + - + + Revision history: + + (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS + for further information. + + (2008) The presence of labelcmb in case of crsspctrm became optional, + from now on the crsspctrm can also be represented as Nchan * Nchan. + + (2006) The fourierspctrm field was added as alternative to powspctrm and + crsspctrm. The fields foi and toi were renamed to freq and time. + + (2003v2) The fields sgn and sgncmb were renamed into label and labelcmb. + + (2003v1) The initial version was defined. + + See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, FT_DATATYPE_FREQ, + FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, FT_DATATYPE_SPIKE, + FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_freq.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_headmodel` + +```{text} + FT_DATATYPE_HEADMODEL describes the FieldTrip MATLAB structure for a volume + conduction model of the head that can be used for forward computations of the EEG + potentials or the MEG fields. The volume conduction model represents the + geometrical and the conductive properties of the head. These determine how the + secondary (or impressed) currents flow and how these contribute to the model + potential or field. + + A large number of forward solutions for the EEG and MEG are supported in FieldTrip, + each with its own specification of the MATLAB structure that describes the volume + conduction model of th ehead. It would be difficult to list all the possibilities + here. One common feature is that the volume conduction model should specify its + type, and that preferably it should specify the geometrical units in which it is + expressed (for example in mm, cm or m). + + An example of an EEG volume conduction model with 4 concentric spheres is: + + headmodel = + r: [86 88 94 100] + c: [0.33 1.79 0.042 0.33] + o: [0 0 0] + type: 'concentricspheres' + unit: 'mm' + + An example of an MEG volume conduction model with a single sphere fitted to + the scalp with its center 4 cm above the line connecting the ears is: + + headmodel = + r: [12] + o: [0 0 4] + type: 'singlesphere' + unit: 'cm' + + For each of the methods XXX for the volume conduction model, a corresponding + function FT_HEADMODEL_XXX exists that contains all specific details and + references to literature that describes the implementation. + + Required fields: + - type + + Optional fields: + - unit + + Deprecated fields: + - inner_skull_surface, source_surface, skin_surface, source, skin + + Obsoleted fields: + - + + Revision history: + + (2015/latest) Use the field name "pos" instead of "pnt" for vertex positions. + + (2014) All numeric values are represented in double precision. + + (2013) Always use the field "cond" for conductivity. + + (2012) Use consistent names for the volume conductor type in the structure, the + documentation and for the actual implementation, e.g. bem_openmeeg -> openmeeg, + fem_simbio -> simbio, concentric -> concentricspheres. Deprecated the fields + that indicate the index of the innermost and outermost surfaces. + + See also FT_PREPARE_HEADMODEL, FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, + FT_DATATYPE_FREQ, FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, + FT_DATATYPE_SPIKE, FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_headmodel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_mvar` + +```{text} + FT_DATATYPE_MVAR describes the FieldTrip MATLAB structure for multi-variate + autoregressive model data. + + The mvar datatype represents multivariate model estimates in the time- or + in the frequency-domain. This is usually obtained from FT_MVARANALYSIS, + optionally in combination with FT_FREQANALYSIS. + + The following is an example of sensor level MVAR model data in the time domain + + dimord: 'chan_chan_lag' defines how the numeric data should be interpreted + label: {3x1 cell} the channel labels + coeffs: [3x3x5 double] numeric data (MVAR model coefficients 3 channels x 3 channels x 5 time lags) + noisecov: [3x3 double] more numeric data (covariance matrix of the noise residuals 3 channels x 3 channels) + dof: 500 + fsampleorig: 200 + cfg: [1x1 struct] + + The following is an example of sensor-level MVAR model data in the frequency domain + + dimord: 'chan_chan_freq' defines how the numeric data should be interpreted + label: {3x1 cell} the channel labels + freq: [1x101 double] the frequencies, expressed in Hz + transfer: [3x3x101 double] + itransfer: [3x3x101 double] + noisecov: [3x3 double] + crsspctrm: [3x3x101 double] + dof: 500 + cfg: [1x1 struct] + + Required fields: + - label, dimord, freq + + Optional fields: + - too many to mention + + Deprecated fields: + - + + Obsoleted fields: + - + + Revision history: + + (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS + for further information. + + (2008) The initial version was defined. + + See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, FT_DATATYPE_FREQ, + FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, FT_DATATYPE_SPIKE, + FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_mvar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_parcellation` + +```{text} + FT_DATATYPE_PARCELLATION describes the FieldTrip MATLAB structure for parcellated + cortex-based data and atlases. A parcellation can either be indexed or probabilistic + (see below). + + A parcellation describes the tissue types for each of the surface elements. + Parcellations are often, but not always labeled. A parcellatoin can be used to + estimate the activity from MEG data in a known region of interest. A surface-based + atlas is basically a very detailed parcellation with an anatomical label for each + vertex. + + An example of a surface based Brodmann parcellation looks like this + + pos: [8192x3] positions of the vertices forming the cortical sheet + tri: [16382x3] triangles of the cortical sheet + coordsys: 'ctf' the (head) coordinate system in which the vertex positions are expressed + unit: 'mm' the units in which the coordinate system is expressed + brodmann: [8192x1 uint8] values from 1 to N, the value 0 means unknown + brodmannlabel: {Nx1 cell} + + An alternative representation of this parcellation is + + pos: [8192x3] positions of the vertices forming the cortical sheet + tri: [16382x3] triangles of the cortical sheet + coordsys: 'ctf' the (head) coordinate system in which the vertex positions are expressed + unit: 'mm' the units in which the coordinate system is expressed + Brodmann_Area_1: [8192x1 logical] binary map representing the voxels belonging to the specific area + Brodmann_Area_2: [8192x1 logical] binary map representing the voxels belonging to the specific area + Brodmann_Area_3: [8192x1 logical] binary map representing the voxels belonging to the specific area + ... + + The examples above demonstrate that a parcellation can be indexed, i.e. consisting of + subsequent integer numbers (1, 2, ...) or probabilistic, consisting of real numbers + ranging from 0 to 1 that represent probabilities between 0% and 100%. An extreme case + is one where the probability is either 0 or 1, in which case the probability can be + represented as a binary or logical array. + + The only difference to the source data structure is that the parcellation structure + contains the additional fields xxx and xxxlabel. See FT_DATATYPE_SOURCE for further + details. + + Required fields: + - pos + + Optional fields: + - any field with dimensions that are consistent with pos + - unit, coordsys, fid, tri + + Deprecated fields: + - none + + Obsoleted fields: + - none + + Revision history: + (2012/latest) The initial version was defined in accordance with the representation of + a voxel-based segmentation. + + See also FT_DATATYPE, FT_DATATYPE_SOURCE, FT_DATATYPE_SEGMENTATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_parcellation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_raw` + +```{text} + FT_DATATYPE_RAW describes the FieldTrip MATLAB structure for raw data + + The raw datatype represents sensor-level time-domain data typically + obtained after calling FT_DEFINETRIAL and FT_PREPROCESSING. It contains + one or multiple segments of data, each represented as Nchan X Ntime + arrays. + + An example of a raw data structure with 151 MEG channels is + + label: {151x1 cell} the channel labels represented as a cell-array of strings + time: {1x266 cell} the time axis [1*Ntime double] per trial + trial: {1x266 cell} the numeric data as a cell array, with a matrix of [151*Ntime double] per trial + sampleinfo: [266x2 double] the begin and endsample of each trial relative to the recording on disk + trialinfo: [266x1 double] optional trigger or condition codes for each trial + hdr: [1x1 struct] the full header information of the original dataset on disk + grad: [1x1 struct] information about the sensor array (for EEG it is called elec) + cfg: [1x1 struct] the configuration used by the function that generated this data structure + + Required fields: + - time, trial, label + + Optional fields: + - sampleinfo, trialinfo, grad, elec, opto, hdr, cfg + + Deprecated fields: + - fsample + + Obsoleted fields: + - offset + + Revision history: + + (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS + for further information. + + (2010v2) The trialdef field has been replaced by the sampleinfo and + trialinfo fields. The sampleinfo corresponds to trl(:,1:2), the trialinfo + to trl(4:end). + + (2010v1) In 2010/Q3 it shortly contained the trialdef field which was a copy + of the trial definition (trl) is generated by FT_DEFINETRIAL. + + (2007) It used to contain the offset field, which corresponds to trl(:,3). + Since the offset field is redundant with the time axis, the offset field is + from now on not present any more. It can be recreated if needed. + + (2003) The initial version was defined + + See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_TIMELOCK, FT_DATATYPE_FREQ, + FT_DATATYPE_SPIKE, FT_DATATYPE_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_raw.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_segmentation` + +```{text} + FT_DATATYPE_SEGMENTATION describes the FieldTrip MATLAB structure for segmented + voxel-based data and atlasses. A segmentation can either be indexed or + probabilistic (see below). + + A segmentation is a volumetric description which is usually derived from an + anatomical MRI, which describes for each voxel the tissue type. It for example + distinguishes between white matter, grey matter, csf, skull and skin. It is mainly + used for masking in visualization, construction of volume conduction models and for + construction of cortical sheets. An volume-based atlas is basically a very detailed + segmentation with an anatomical label for each voxel. + + For example, the AFNI TTatlas+tlrc segmented brain atlas (which can be created + with FT_READ_ATLAS) looks like this + + dim: [161 191 141] the size of the 3D volume in voxels + transform: [4x4 double] affine transformation matrix for mapping the voxel coordinates to head coordinate system + coordsys: 'tal' the transformation matrix maps the voxels into this (head) coordinate system + unit: 'mm' the units in which the coordinate system is expressed + brick0: [161x191x141 uint8] integer values from 1 to N, the value 0 means unknown + brick1: [161x191x141 uint8] integer values from 1 to M, the value 0 means unknown + brick0label: {Nx1 cell} + brick1label: {Mx1 cell} + + An example segmentation with binary values that can be used for construction of a + BEM volume conduction model of the head looks like this + + dim: [256 256 256] the dimensionality of the 3D volume + transform: [4x4 double] affine transformation matrix for mapping the voxel coordinates to head coordinate system + coordsys: 'ctf' the transformation matrix maps the voxels into this (head) coordinate system + unit: 'mm' the units in which the coordinate system is expressed + brain: [256x256x256 logical] binary map representing the voxels which belong to the brain + skull: [256x256x256 logical] binary map representing the voxels which belong to the skull + scalp: [256x256x256 logical] binary map representing the voxels which belong to the scalp + + An example of a whole-brain anatomical MRI that was segmented using FT_VOLUMESEGMENT + looks like this + + dim: [256 256 256] the size of the 3D volume in voxels + transform: [4x4 double] affine transformation matrix for mapping the voxel coordinates to head coordinate system + coordsys: 'ctf' the transformation matrix maps the voxels into this (head) coordinate system + unit: 'mm' the units in which the coordinate system is expressed + gray: [256x256x256 double] probabilistic map of the gray matter + white: [256x256x256 double] probabilistic map of the white matter + csf: [256x256x256 double] probabilistic map of the cerebrospinal fluid + + The examples above demonstrate that a segmentation can be indexed, i.e. consisting + of subsequent integer numbers (1, 2, ...) or probabilistic, consisting of real + numbers ranging from 0 to 1 that represent probabilities between 0% and 100%. An + extreme case is one where the probability is either 0 or 1, in which case the + probability can be represented as a binary or logical array. + + The only difference to the volume data representation is that the segmentation + structure contains the additional fields xxx and xxxlabel. See FT_DATATYPE_VOLUME + for further details. + + Required fields: + - dim, transform + + Optional fields: + - brain, skull, scalp, gray, white, csf, or any other field with dimensions that are consistent with dim + - unit, coordsys, fid + + Deprecated fields: + - none + + Obsoleted fields: + - none + + Revision history: + (2012/latest) The explicit distunction between the indexed and probabilistic + representation was made. For the indexed representation the additional + xxxlabel cell-array was introduced. + + (2005) The initial version was defined. + + See also FT_DATATYPE, FT_DATATYPE_VOLUME, FT_DATATYPE_PARCELLATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_segmentation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_sens` + +```{text} + FT_DATATYPE_SENS describes the FieldTrip structure that represents an MEG, EEG, + sEEG, ECoG, or NIRS sensor array. This structure is commonly called "grad" for MEG, + "elec" for EEG and intranial EEG, "opto" for NIRS, or in general "sens" if it could + be any one. + + For all sensor types a distinction should be made between the channel (i.e. the + output of the transducer that is A/D converted) and the sensor, which may have some + spatial extent. For example in MEG gradiometers are comprised of multiple coils and + with EEG you can have a bipolar channel, where the position of the channel can be + represented as in between the position of the two electrodes. + + The structure for MEG gradiometers and/or magnetometers contains + sens.label = Mx1 cell-array with channel labels + sens.chanpos = Mx3 matrix with channel positions + sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation + sens.coilpos = Nx3 matrix with coil positions + sens.coilori = Nx3 matrix with coil orientations + sens.tra = MxN matrix to combine coils into channels + sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE + and optionally + sens.chanposold = Mx3 matrix with original channel positions (in case sens.chanpos has been updated to contain NaNs, e.g. after FT_COMPONENTANALYSIS) + sens.chanoriold = Mx3 matrix with original channel orientations + sens.labelold = Mx1 cell-array with original channel labels + + The structure for EEG, sEEG or ECoG channels contains + sens.label = Mx1 cell-array with channel labels + sens.chanpos = Mx3 matrix with channel positions (often the same as electrode positions) + sens.elecpos = Nx3 matrix with electrode positions + sens.tra = MxN matrix to combine electrodes into channels + In case sens.tra is not present in the EEG sensor array, the channels + are assumed to be average referenced. + + The structure for NIRS channels contains + sens.label = Mx1 cell-array with channel labels + sens.chanpos = Mx3 matrix with position of the channels (usually halfway the transmitter and receiver) + sens.optopos = Nx3 matrix with the position of individual optodes + sens.optotype = Nx1 cell-array with information about the type of optode (receiver or transmitter) + sens.optolabel = Nx1 cell-array with optode labels + sens.wavelength = 1xK vector of all wavelengths that were used + sens.tra = MxN matrix that specifies for each of the M channels which of the N optodes transmits at which wavelength (positive integer from 1 to K), or receives (negative ingeger from 1 to K) + + The following fields apply to MEG, EEG, sEEG and ECoG + sens.chantype = Mx1 cell-array with the type of the channel, see FT_CHANTYPE + sens.chanunit = Mx1 cell-array with the units of the channel signal, e.g. 'V', 'fT' or 'T/cm', see FT_CHANUNIT + + Optional fields: + type, unit, fid, chantype, chanunit, coordsys + + Historical fields: + pnt, pos, ori, pnt1, pnt2, fiberpos, fibertype, fiberlabel, transceiver, transmits, laserstrength + + Revision history: + (2020/latest) Updated the specification of the NIRS sensor definition. + Dropped the laserstrength and renamed transmits into tra for consistency. + + (2019/latest) Updated the specification of the NIRS sensor definition. + Use "opto" instead of "fibers", see http://bit.ly/33WaqWU for details. + + (2016) The chantype and chanunit have become required fields. + Original channel details are specified with the suffix "old" rather than "org". + All numeric values are represented in double precision. + It is possible to convert the amplitude and distance units (e.g. from T to fT and + from m to mm) and it is possible to express planar and axial gradiometer channels + either in units of amplitude or in units of amplitude/distance (i.e. proper + gradient). + + (2011v2) The chantype and chanunit have been added for MEG. + + (2011v1) To facilitate determining the position of channels (e.g. for plotting) + in case of balanced MEG or bipolar EEG, an explicit distinction has been made + between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos + (for EEG). The pnt and ori fields are removed. + + (2010) Added support for bipolar or otherwise more complex linear combinations + of EEG electrodes using sens.tra, similar to MEG. + + (2009) Noise reduction has been added for MEG systems in the balance field. + + (2006) The optional fields sens.type and sens.unit were added. + + (2003) The initial version was defined, which looked like this for EEG + sens.pnt = Mx3 matrix with electrode positions + sens.label = Mx1 cell-array with channel labels + and like this for MEG + sens.pnt = Nx3 matrix with coil positions + sens.ori = Nx3 matrix with coil orientations + sens.tra = MxN matrix to combine coils into channels + sens.label = Mx1 cell-array with channel labels + + See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD, + BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_sens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_source` + +```{text} + FT_DATATYPE_SOURCE describes the FieldTrip MATLAB structure for data that is + represented at the source level. This is typically obtained with a beamformer of + minimum-norm source reconstruction using FT_SOURCEANALYSIS. + + An example of a source structure obtained after performing DICS (a frequency domain + beamformer scan) is shown here + + pos: [6732x3 double] positions at which the source activity could have been estimated + inside: [6732x1 logical] boolean vector that indicates at which positions the source activity was estimated + dim: [xdim ydim zdim] if the positions can be described as a 3D regular grid, this contains the + dimensionality of the 3D volume + cumtapcnt: [120x1 double] information about the number of tapers per original trial + time: 0.100 the latency at which the activity is estimated (in seconds) + freq: 30 the frequency at which the activity is estimated (in Hz) + pow: [6732x120 double] the estimated power at each source position + powdimord: 'pos_rpt' defines how the numeric data has to be interpreted, + in this case 6732 dipole positions x 120 repetitions (i.e. trials) + cfg: [1x1 struct] the configuration used by the function that generated this data structure + + Required fields: + - pos + + Optional fields: + - inside, pow, coh, eta, mom, ori, leadfield, filter, or any other field with dimensions that are consistent with pos or dim + - dim, transform, unit, coordsys, time, freq, cumtapcnt, dimord + + Deprecated fields: + - method, outside + + Obsoleted fields: + - xgrid, ygrid, zgrid, transform, latency, frequency + + Revision history: + + (2014) The subfields in the avg and trial fields are now present in the + main structure, e.g. source.avg.pow is now source.pow. Furthermore, the + inside is always represented as logical vector. + + (2011) The source representation should always be irregular, i.e. not + a 3-D volume, contain a "pos" field and not contain a "transform". + + (2010) The source structure should contain a general "dimord" or specific + dimords for each of the fields. The source reconstruction in the avg and + trial substructures has been moved to the toplevel. + + (2007) The xgrid/ygrid/zgrid fields have been removed, because they are + redundant. + + (2003) The initial version was defined + + See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, FT_DATATYPE_FREQ, + FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, FT_DATATYPE_SPIKE, + FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_source.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_spike` + +```{text} + FT_DATATYPE_SPIKE describes the FieldTrip MATLAB structure for spike data + + Spike data is obtained using FT_READ_SPIKE to read files from a Plexon, + Neuralynx or other animal electrophysiology data acquisition system. It + is characterised as a sparse point-process, i.e. each neuronal firing is + only represented as the time at which the firing happened. Optionally, + the spike waveform can also be represented. Using this waveform, the + neuronal firing events can be sorted into their single units. + + A required characteristic of the SPIKE structure is a cell-array with the + label of the (single or multi) units. + + label: {'unit1' 'unit2' 'unit3'} + + The fields of the SPIKE structure that contain the specific information + per spike depends on the available information. A relevant distinction + can be made between the representation of raw spikes that are not related + to the temporal structure of the experimental design (i.e trials), and + the data representation in which the spikes are related to the trial. + + For a continuous recording the SPIKE structure must contain a cell-array + with the raw timestamps as recorded by the hardware system. As example, + the original content of the .timestamp field can be + + timestamp: {[1x504 uint64] [1x50 uint64] [1x101 uint64]} + + An optional field that is typically obtained from the raw recording + contains the waveforms for every unit and label as a cell-array. For + example, the content of this field may be + + waveform: {[1x32x504 double] [1x32x50 double] [1x32x101 double]} + + If the data has been organised to reflect the temporal structure of the + experiment (i.e. the trials), the SPIKE structure should contain a + cell-array with the spike times relative to an experimental trigger. The + FT_SPIKE_MAKETRIALS function can be used to reorganise the SPIKE + structure such that the spike times are expressed relative to a trigger + instead of relative to the acquisition devices internal timestamp clock. + The time field then contains only those spikes that occurred within one of + the trials . The spike times are now expressed on seconds relative to the + trigger. + + time: {[1x504 double] [1x50 double] [1x101 double]} + + In addition, for every spike we register in which trial the spike was + recorded: + + trial: {[1x504 double] [1x50 double] [1x101 double]} + + To fully reconstruct the structure of the spike-train, it is required + that the exact start- and end-point of the trial (in seconds) is + represented. This is specified in a nTrials x 2 matrix. + + trialtime: [100x2 double] + + As an example, FT_SPIKE_MAKETRIALS could result in the following + SPIKE structure that represents the spikes of three units that were + observed in 100 trials: + + label: {'unit1' 'unit2' 'unit3'} + timestamp: {[1x504 double] [1x50 double] [1x101 double]} + timestampdimord: '{chan}_spike' + time: {[1x504 double] [1x50 double] [1x101 double]} + trial: {[1x504 double] [1x50 double] [1x101 double]} + trialtime: [100x2 double] + sampleinfo: [100x2 double] + waveform: {[1x32x504 double] [1x32x50 double] [1x32x101 double]} + waveformdimord: '{chan}_lead_time_spike' + + For analysing the relation between the spikes and the local field + potential (e.g. phase-locking), the SPIKE structure can have additional + fields such as fourierspctrm, lfplabel, freq and fourierspctrmdimord. + + For example, from the structure above we may obtain + + label: {'unit1' 'unit2' 'unit3'} + time: {[1x504 double] [1x50 double] [1x101 double]} + trial: {[1x504 double] [1x50 double] [1x101 double]} + trialtime: [100x2 double] + timestamp: {[1x504 double] [1x50 double] [1x101 double]} + timestampdimord: '{chan}_spike' + waveform: {[1x32x504 double] [1x32x50 double] [1x32x101 double]} + waveformdimord: '{chan}_lead_time_spike' + fourierspctrm: {504x2x20, 50x2x20, 101x2x20} + fourierspctrmdimord: '{chan}_spike_lfplabel_freq' + lfplabel: {'lfpchan1', 'lfpchan2'} + freq: [1x20 double] + + Required fields: + - label + - timestamp + + Optional fields: + - time, trial, trialtime + - timestampdimord + - unit, unitdimord + - waveform, waveformdimord + - fourierspctrm, fourierspctrmdimord, freq, lfplabel (these are extra outputs from FT_SPIKETRIGGEREDSPECTRUM and FT_SPIKE_TRIGGEREDSPECTRUM) + - hdr + - cfg + + Deprecated fields: + - origtime, origtrial + + Obsoleted fields: + - + + Revision history: + + (2020/latest) Add an explicit xxxdimord for each of the known fields. + + (2012) Changed the dimensionality of the waveform to allow both + stereotrode and tetrode data to be represented. + + (2011) Defined a consistent spike data representation that can + also contain the Fourier spectrum and other fields. Use the xxxdimord + to indicate the dimensions of the field. + + (2010) Introduced the time and the trialtime fields. + + (2007) Introduced the spike data representation. + + See also FT_DATATYPE, FT_DATATYPE_RAW, FT_DATATYPE_FREQ, FT_DATATYPE_TIMELOCK + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_spike.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_timelock` + +```{text} + FT_DATATYPE_TIMELOCK describes the FieldTrip MATLAB structure for timelock data + + The timelock data structure represents averaged or non-averaged event-releted + potentials (ERPs, in case of EEG) or ERFs (in case of MEG). This data structure is + usually generated with the FT_TIMELOCKANALYSIS or FT_TIMELOCKGRANDAVERAGE function. + + An example of a timelock structure containing the ERF for 151 channels MEG data is + + dimord: 'chan_time' defines how the numeric data should be interpreted + avg: [151x600 double] the average values of the activity for 151 channels x 600 timepoints + var: [151x600 double] the variance of the activity for 151 channels x 600 timepoints + label: {151x1 cell} the channel labels (e.g. 'MRC13') + time: [1x600 double] the timepoints in seconds + grad: [1x1 struct] information about the sensor array (for EEG data it is called elec) + cfg: [1x1 struct] the configuration used by the function that generated this data structure + + Required fields: + - label, dimord, time + + Optional fields: + - avg, var, dof, cov, trial, trialinfo, sampleinfo, grad, elec, opto, cfg + + Deprecated fields: + - + + Obsoleted fields: + - fsample + + Revision history: + + (2017/latest) The data structure cannot contain an average and simultaneously single + trial information any more, i.e. avg/var/dof and trial/individual are mutually exclusive. + + (2011v2) The description of the sensors has changed, see FT_DATATYPE_SENS + for further information. + + (2011) The field 'fsample' was removed, as it was redundant. + + (2003) The initial version was defined. + + See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_FREQ, FT_DATATYPE_RAW + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_timelock.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_datatype_volume` + +```{text} + FT_DATATYPE_VOLUME describes the FieldTrip MATLAB structure for volumetric data + such as an anatomical MRI. + + The volume data structure represents data on a regular volumetric 3-D grid, like an + anatomical MRI, a functional MRI, etc. It can also represent a source reconstructed + estimate of the activity measured with MEG. In this case the source reconstruction + is estimated or interpolated on the regular 3-D dipole grid (like a box). + + An example volume structure is + anatomy: [181x217x181 double] the numeric data, in this case anatomical information + dim: [181 217 181] the dimensionality of the 3D volume + transform: [4x4 double] 4x4 homogenous transformation matrix, specifying the transformation from voxel coordinates to head or world coordinates + unit: 'mm' geometrical units of the coordinate system + coordsys: 'ctf' description of the coordinate system + + Required fields: + - transform, dim + + Optional fields: + - anatomy, prob, stat, grey, white, csf, or any other field with dimensions that are consistent with dim + - unit, coordsys, fid + + Deprecated fields: + - dimord + + Obsoleted fields: + - none + + Revision history: + + (2014) The subfields in the avg and trial fields are now present in the + main structure, e.g. source.avg.pow is now source.pow. Furthermore, the + inside is always represented as logical array. + + (2012b) Ensure that the anatomy-field (if present) does not contain + infinite values. + + (2012) A placeholder 2012 version was created that ensured the axes + of the coordinate system to be right-handed. This actually never + has made it to the default version. An executive decision regarding + this has not been made as far as I (JM) am aware, and probably it's + a more principled approach to keep the handedness free, so don't mess + with it here. However, keep this snippet of code for reference. + + (2011) The dimord field was deprecated and we agreed that volume + data should be 3-dimensional and not N-dimensional with arbitrary + dimensions. In case time-frequency recolved data has to be represented + on a 3-d grid, the source representation should be used. + + (2010) The dimord field was added by some functions, but not by all + + (2003) The initial version was defined + + See also FT_DATATYPE, FT_DATATYPE_DIP, FT_DATATYPE_SOURCE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_datatype_volume.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_debug` + +```{text} + FT_DEBUG prints a debug message on screen, depending on the verbosity + settings of the calling high-level FieldTrip function. + + Use as + ft_debug(...) + with arguments similar to fprintf, or + ft_debug(msgId, ...) + with arguments similar to warning. + + You can switch of all messages using + ft_debug off + or for specific ones using + ft_debug off msgId + + To switch them back on, you would use + ft_debug on + or for specific ones using + ft_debug on msgId + + Messages are only printed once per timeout period using + ft_debug timeout 60 + ft_debug once + or for specific ones using + ft_debug once msgId + + You can see the most recent messages and identifier using + ft_debug last + + You can query the current on/off/once state for all messages using + ft_debug query + + See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_debug.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_defacemesh` + +```{text} + FT_DEFACEMESH allows you to de-identify a scalp surface mesh by erasing specific + regions, such as the face and ears. The interactive graphical user interface allows + you to position a box over the anatomical data inside which all vertices will be + removed. You might have to call this function multiple times when both face and + ears need to be removed. Following defacing, you should check the result with + FT_PLOT_MESH. + + Use as + mesh = ft_defacemesh(cfg, mesh) + + The configuration can contain the following options + cfg.method = string, specification of the shape that is used + as a boundary for exclusion, can be either 'box' or 'plane' (default = 'box') + cfg.translate = initial position of the center of the box, or a point on the plane (default = [0 0 0]) + cfg.scale = initial size of the box along each dimension (default is automatic) + cfg.rotate = initial rotation of the box, or the plane (default = [0 0 0]) + cfg.selection = which vertices to keep, can be 'inside' or 'outside' (default = 'outside') + + See also FT_ANONYMIZEDATA, FT_DEFACEVOLUME, FT_ANALYSISPIPELINE, FT_PLOT_MESH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_defacemesh.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_defacevolume` + +```{text} + FT_DEFACEVOLUME allows you to de-identify an anatomical MRI by erasing specific + regions, such as the face and ears. The interactive graphical user interface allows + you to position a box over the anatomical data inside which all anatomical voxel + values will be replaced by zero. You might have to call this function multiple + times when both face and ears need to be removed. Following defacing, you should + check the result with FT_SOURCEPLOT. + + Use as + mri = ft_defacevolume(cfg, mri) + + The configuration can contain the following options + cfg.method = 'box', 'plane', 'spm' (default = 'box') + + If you specify the box method, the following options apply + cfg.translate = initial position of the center of the box, or a point + on the plane, (default = [0 0 0]) + cfg.scale = initial size of the box along each dimension (default is automatic) + cfg.rotate = initial rotation of the box, or the plane (default = [0 0 0]) + cfg.selection = which voxels to keep, can be 'inside' or 'outside' (default = 'outside') + cfg.smooth = 'no' or the FWHM of the gaussian kernel in voxels (default = 'no') + cfg.keepbrain = 'no' or 'yes', segment and retain the brain (default = 'no') + cfg.feedback = 'no' or 'yes', whether to provide graphical feedback (default = 'no') + + If you specify no smoothing, the selected area will be zero-masked. If you + specify a certain amount of smoothing (in voxels FWHM), the selected area will + be replaced by a smoothed version of the data. + + The spm method does not have any options, it uses SPM_DEFACE from the + SPM12 toolbox. + + See also FT_ANONYMIZEDATA, FT_DEFACEMESH, FT_ANALYSISPIPELINE, FT_SOURCEPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_defacevolume.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_defaults` + +```{text} + FT_DEFAULTS (ending with "s") sets some general settings in the global variable + ft_default (without the "s") and takes care of the required path settings. You can + call this function in your startup.m script. This function is also called at the + begin of all FieldTrip functions. + + The global configuration defaults are stored in the global "ft_default" structure. + The ft_checkconfig function that is called by many FieldTrip functions will merge + these global configuration defaults with the cfg ctructure that you pass to + the FieldTrip function that you are calling. + + The global options and their default values are + ft_default.checkconfig = string, can be 'pedantic', 'loose', 'silent' (default = 'loose') + ft_default.checkpath = string, can be 'pedantic', 'once', 'no' (default = 'pedantic') + ft_default.checksize = number in bytes, can be inf (default = 1e5) + ft_default.checkstring = string, can be 'yes' or 'no' (default = 'yes'), convert "strings" in cfg to 'chars' + ft_default.showlogo = string, can be 'yes' or 'no' (default = 'yes') + ft_default.showcallinfo = string, can be 'yes' or 'no' (default = 'yes') + ft_default.trackcallinfo = string, can be 'yes' or 'no' (default = 'yes') + ft_default.trackusage = false, or string with salt for one-way encryption of identifying information (by default this is enabled and an automatic salt is created) + ft_default.trackdatainfo = string, can be 'yes' or 'no' (default = 'no') + ft_default.keepprevious = string, can be 'yes' or 'no' (default = 'yes') + ft_default.outputfilepresent = string, can be 'keep', 'overwrite', 'error' (default = 'overwrite') + ft_default.debug = string, can be 'display', 'displayonerror', 'displayonsuccess', 'save', 'saveonerror', saveonsuccess' or 'no' (default = 'no') + ft_default.toolbox.signal = string, can be 'compat' or 'matlab' (default is automatic, see below) + ft_default.toolbox.stats = string, can be 'compat' or 'matlab' (default is automatic, see below) + ft_default.toolbox.images = string, can be 'compat' or 'matlab' (default is automatic, see below) + ft_default.reproducescript = string, directory to which the script and intermediate data are written (default = []) + + If you want to overrule these default settings, you can add something like this in your startup.m script + ft_defaults + global ft_default + ft_default.option1 = value1 + ft_default.option2 = value2 + + The toolbox option for signal, stats and images allows you to specify whether you + want to use the original version from MathWorks or a compatible drop-in to be used. + When you use the Radboud University license server, i.e. at the Donders, the + default is 'compat'. This has the advantage that you do not need a license for + these toolboxes; we do not have that many licenses and parallel computations on our + Donders compute cluster would otherwise use all licenses. In all other cases, the + default is 'matlab' when the toolbox is available, and 'compat' when it is not + available. + + See also FT_HASTOOLBOX, FT_CHECKCONFIG, FT_TRACKUSAGE, LICENSE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_defaults.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_definetrial` + +```{text} + FT_DEFINETRIAL defines the trials or segments of data that will be used for further + processing and analysis, i.e. the pieces of data that will be read in by + FT_PREPROCESSING. Trials are defined by their begin and end sample in the data file + and each trial has an offset that defines where the relative t=0 point (usually the + sample at which the trigger is detected) is for that trial or segment. + + Use as + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.trialdef = structure with the details of trial definition, see below + cfg.trialfun = string with the function name, see below (default = 'ft_trialfun_general') + cfg.representation = 'numeric' or 'table', determines how the trial definition is returned (default is automatic) + and furthermore + cfg.dataset = string with the filename + or + cfg.headerfile = string with the filename + cfg.datafile = string with the filename + and optionally + cfg.headerformat = string, see FT_FILETYPE (default is automatic) + cfg.dataformat = string, see FT_FILETYPE (default is automatic) + cfg.eventformat = string, see FT_FILETYPE (default is automatic) + + In general, a call to FT_DEFINETRIAL results in the trial definition "trl" being + added to the output configuration. The trials are defined on the basis of events or + triggers by a user-specified MATLAB function that is subsequently referred to as + the trial function. The user can specify their own custom function tailored to the + experimental paradigm, or use one of the default trial functions (see below). + + Simple trial definitions (for example based on a single trigger) are supported by + FT_TRIALFUN_GENERAL, which is specified as the default. It supports the following + options + cfg.trialdef.eventtype = string, or cell-array with strings + cfg.trialdef.eventvalue = number, string, or list with numbers or strings + cfg.trialdef.prestim = number, latency in seconds (optional) + cfg.trialdef.poststim = number, latency in seconds (optional) + + To read all data from a continuous file in a single or in multiple segments, + FT_TRIALFUN_GENERAL understands the following options + cfg.trialdef.triallength = duration in seconds (can also be 1 or Inf) + cfg.trialdef.ntrials = number of trials (can also be 1 or Inf) + cfg.trialdef.overlap = number between 0 and 1 (exclusive) specifying the fraction of overlap between snippets (0 = no overlap) + + To display a list with the events in your data on screen, you can use + FT_TRIALFUN_SHOW. This is useful for diagnostics; no actual trials will be defined. + + To display a graphical user interface dialog that allows you to select events of + interest, you can use FT_TRIALFUN_GUI. + + The trial definition "trl" is an Nx3 matrix or table, where N is the number of + trials. The first column contains the sample-indices of the start of each trial + relative to the start of the raw data, the second column contains the sample + indices of the end of each trial, and the third column contains the offset of the + trigger with respect to the trial. An offset of 0 means that the first sample of + the trial corresponds to the trigger. A positive offset indicates that the first + sample is later than the trigger, and a negative offset indicates that the trial + begins before the trigger. + + Besides the required three columns in the trial definition "trl" that represent + start, end and offset, it can have contain additional columns . These additional + columns can be used by a custom trialfun to provide information about each trial, + such as trigger codes, response latencies, trial type, and response correctness. + After FT_PREPROCESSING these additional columns of the "trl" matrix will be + represented in the "trialinfo" field. + + If FT_TRIALFUN_GENERAL or FT_TRIALFUN_GUI has been used to generate the "trl" + matrix or table, the function may return a fourth column that refers to the + event-code for the corresponding trial. Whether or not this column is returned + depends on the acquisition system. In general, this fourth column is generated by + default if the event codes are represented numerically, or as a string starting + with 'S' or 'R' (for BrainVision data). + + If you need to define the segments of interest on the basis of a conditional + sequence of events (e.g. stimulus trigger followed by a correct response) or on + basis of some signal feature that needs to be detected in the data, you should + supply in cfg.trialfun the name of a function that you wrote yourself and that + FT_DEFINETRIAL will call. The function receives the cfg structure as input and + should return a NxM matrix in the same format as "trl" as the output. You can add + extra custom fields to cfg.trialdef to pass to your own trialfun. See below for + pointers to some examples. + + See also FT_PREPROCESSING, FT_READ_HEADER, FT_READ_EVENT, FT_TRIALFUN_GENERAL, + FT_TRIALFUN_GUI, FT_TRIALFUN_SHOW, FT_TRIALFUN_BIDS, FT_TRIALFUN_EXAMPLE1, + FT_TRIALFUN_EXAMPLE2 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_definetrial.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_amm` + +```{text} + FT_DENOISE_AMM implements an adaptive multipole modelling based + projection algorithm to suppress interference outside an ellipsoid + spanned by an MEG array. It is based on: REFERENCE. + + Use as + dataout = ft_denoise_amm(cfg, datain) + where cfg is a configuration structure that contains + cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'), see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.pertrial = 'no', or 'yes', compute the temporal projection per trial (default = 'no') + cfg.demean = 'yes', or 'no', demean the data per epoch (default = 'yes') + cfg.updatesens = 'yes', or 'no', update the sensor array with the spatial projector + cfg.amm = structure with parameters that determine the behavior of the algorithm + cfg.amm.order_in = scalar. Order of the spheroidal harmonics basis that spans the in space (default = 9) + cfg.amm.order_out = scalar. Order of the spheroidal harmonics basis that spans the out space (default = 2) + cfg.amm.reducerank + cfg.amm.thr + + The implementation is based on Tim Tierney's code written for spm + + See also FT_DENOISE_PCA, FT_DENOISE_SYNTHETIC, FT_DENOISE_TSR, FT_DENOISE_DSSP, FT_DENOISE_HFC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_amm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_dssp` + +```{text} + FT_DENOISE_DSSP implements a dual signal subspace projection algorithm + to suppress interference outside a predefined source region of + interest. It is based on: Sekihara et al. J. Neural Eng. 2016 13(3), and + Sekihara et al. J. Neural Eng. 2018 15(3). + + Use as + dataout = ft_denoise_dssp(cfg, datain) + where cfg is a configuration structure that contains + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.pertrial = 'no', or 'yes', compute the temporal projection per trial (default = 'no') + cfg.sourcemodel = structure, source model with precomputed leadfields, see FT_PREPARE_LEADFIELD + cfg.demean = 'yes', or 'no', demean the data per epoch (default = 'yes') + cfg.dssp = structure with parameters that determine the behavior of the algorithm + cfg.dssp.n_space = 'all', or scalar. Number of dimensions for the + initial spatial projection. + cfg.dssp.n_in = 'all', or scalar. Number of dimensions of the + subspace describing the field inside the ROI. + cfg.dssp.n_out = 'all', or scalar. Number of dimensions of the + subspace describing the field outside the ROI. + cfg.dssp.n_intersect = scalar (default = 0.9). Number of dimensions (if + value is an integer>=1), or threshold for the + included eigenvalues (if value<1), determining + the dimensionality of the intersection. + + See also FT_DENOISE_PCA, FT_DENOISE_SYNTHETIC, FT_DENOISE_TSR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_dssp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_hfc` + +```{text} + FT_DENOISE_HFC implements harmonic field correction, which models external + interference on the recordings as a harmonic magnetic field. It is particulaly + useful for MEG data with low channel numbers, such as OPM data. + + The homogenous field correction method implements Tierney et al. (2021) NIMG, + https://doi.org/10.1016/j.neuroimage.2021.118484. + + The harmonic expansion method implements Tierney et al. (2022) NIMG, + https://doi.org/10.1016/j.neuroimage.2022.119338. + + Use as + data = ft_denoise_hfc(cfg,data) + + Where cfg is a configuration structure that contains: + cfg.channel = channels for HFC (default = 'all') + cfg.order = number, spherical harmonic order (default = 1) + order = 1 is a homogenous field + order = 2 includes gradients + order = 3 includes quadratic terms, etc. + cfg.trials = which trials do you want to denoise? (default = 'all') + cfg.updatesens = do you want to update sensor info with projector? (default = 'yes') + cfg.feedback = do you want feedback (default = 'yes') + cfg.residualcheck = do you want to check channel residuals (default = 'yes') + cfg.residualthresh = number in pT, what level of residual signal is fine for quality assurance (default = 50) + + See also FT_DENOISE_SYNTHETIC, FT_DENOISE_PCA, FT_DENOISE_DSSP, FT_DENOISE_TSP + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_hfc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_pca` + +```{text} + FT_DENOISE_PCA performs a principal component analysis (PCA) on specified reference + channels and subtracts the projection of the data of interest onto this orthogonal + basis from the data of interest. This is the algorithm which is applied by BTi/4D to + compute noise cancellation weights on a dataset of interest. This function has been + designed for BTi/4D MEG data, but can also be applied to data from other MEG systems. + + Use as + [dataout] = ft_denoise_pca(cfg, data) + or as + [dataout] = ft_denoise_pca(cfg, data, refdata) + where "data" is a raw data structure that was obtained with FT_PREPROCESSING. If + you specify the additional input "refdata", the specified reference channels for + the regression will be taken from this second data structure. This can be useful + when reference-channel specific preprocessing needs to be done (e.g. low-pass + filtering). + + The output structure dataout contains the denoised data in a format that is + consistent with the output of FT_PREPROCESSING. + + The configuration should contain + cfg.refchannel = the channels used as reference signal (default = 'MEGREF') + cfg.channel = the channels to be denoised (default = 'MEG') + cfg.truncate = optional truncation of the singular value spectrum (default = 'no') + cfg.zscore = standardise reference data prior to PCA (default = 'no') + cfg.pertrial = 'no' (default) or 'yes'. Regress out the references on a per trial basis + cfg.trials = list of trials that are used (default = 'all') + cfg.updatesens = 'no' or 'yes' (default = 'yes') + + if cfg.truncate is integer n > 1, n will be the number of singular values kept. + if 0 < cfg.truncate < 1, the singular value spectrum will be thresholded at the + fraction cfg.truncate of the largest singular value. + + See also FT_PREPROCESSING, FT_DENOISE_SYNTHETIC, FT_DENOISE_SSP + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_pca.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_prewhiten` + +```{text} + FT_DENOISE_PREWHITEN applies a spatial prewhitening operation to the data using the + inverse noise covariance matrix. The consequence is that all channels are expressed + in singnal-to-noise units, causing different channel types to be comparable. This + ensures equal weighting in source estimation on data with different channel types. + + Use as + dataout = ft_denoise_prewhiten(cfg, datain, noise) + where the datain is the original data from FT_PREPROCESSING and + noise should contain the estimated noise covariance from + FT_TIMELOCKANALYSIS. + + The configuration structure can contain + cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all') + cfg.split = cell-array of channel types between which covariance is split, it can also be 'all' or 'no' + cfg.lambda = scalar, or string, regularization parameter for the inverse + cfg.kappa = scalar, truncation parameter for the inverse + + The channel selection relates to the channels that are pre-whitened using the same + selection of channels in the noise covariance. All channels present in the input + data structure will be present in the output, including trigger and other auxiliary + channels. + + See also FT_DENOISE_SYNTHETIC, FT_DENOISE_PCA, FT_DENOISE_DSSP, FT_DENOISE_TSP + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_prewhiten.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_ssp` + +```{text} + FT_DENOISE_SSP projects out topographies based on ambient noise on + Neuromag/Elekta/MEGIN systems. These topographies are estimated during maintenance + visits from the engineers of MEGIN + + Use as + [data] = ft_denoise_ssp(cfg, data) + where data should come from FT_PREPROCESSING and the configuration + should contain + cfg.ssp = 'all' or a cell array of SSP names to apply (default = 'all') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.updatesens = 'no' or 'yes' (default = 'yes') + + 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_PREPROCESSING, FT_DENOISE_SYNTHETIC, FT_DENOISE_PCA + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_ssp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_sss` + +```{text} + FT_DENOISE_SSS implements an spherical harmonics based + projection algorithm to suppress interference outside an sphere + spanned by an MEG array. It is based on: REFERENCE. + + Use as + dataout = ft_denoise_sss(cfg, datain) + where cfg is a configuration structure that contains + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.pertrial = 'no', or 'yes', compute the temporal projection per trial (default = 'no') + cfg.demean = 'yes', or 'no', demean the data per epoch (default = 'yes') + cfg.updatesens = 'yes', or 'no', update the sensor array with the spatial projector + cfg.sss = structure with parameters that determine the behavior of the algorithm + cfg.sss.order_in = scalar. Order of the spherical harmonics basis that spans the in space (default = 8) + cfg.sss.order_out = scalar. Order of the spherical harmonics basis that spans the out space (default = 3) + + The implementation is based on Tim Tierney's code written for spm + + See also FT_DENOISE_PCA, FT_DENOISE_SYNTHETIC, FT_DENOISE_TSR, FT_DENOISE_DSSP, FT_DENOISE_HFC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_sss.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_synthetic` + +```{text} + FT_DENOISE_SYNTHETIC computes CTF higher-order synthetic gradients for + preprocessed data and for the corresponding gradiometer definition. + + Use as + [data] = ft_denoise_synthetic(cfg, data) + where data should come from FT_PREPROCESSING and the configuration should contain + cfg.gradient = 'none', 'G1BR', 'G2BR' or 'G3BR' specifies the gradiometer + type to which the data should be changed + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.updatesens = 'no' or 'yes' (default = 'yes') + + 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_PREPROCESSING, FT_DENOISE_PCA, FT_DENOISE_SSP + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_synthetic.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_denoise_tsr` + +```{text} + FT_DENOISE_TSR performs a regression analysis, using a (time-shifted set + of) reference signal(s) as independent variable. It is a generic + implementation of the method described by De Cheveigne + (https://doi.org/10.1016/j.jneumeth.2007.06.003), or can be + used to compute temporal-response-functions (see e.g. Crosse + (https://doi.org/10.3389/fnhum.2016.00604)), or + spatial filters based on canonical correlation (see Thielen + (https://doi.org/10.1371/journal.pone.0133797)) + + Use as + [dataout] = ft_denoise_tsr(cfg, data) + [dataout] = ft_denoise_tsr(cfg, data, refdata) + where "data" is a raw data structure that was obtained with FT_PREPROCESSING. If + you specify the additional input "refdata", the specified reference channels for + the regression will be taken from this second data structure. This can be useful + when reference-channel specific preprocessing needs to be done (e.g. low-pass + filtering). + + The output structure dataout contains the denoised data in a format consistent + with the output of FT_PREPROCESSING. + + The configuration options are: + cfg.refchannel = the channels used as reference signal (default = 'MEGREF'), see FT_SELECTDATA + cfg.channel = the channels to be denoised (default = 'all'), see FT_SELECTDATA + cfg.method = string, 'mlr', 'cca', 'pls', 'svd', option specifying the criterion for the regression + (default = 'mlr') + cfg.reflags = integer array, specifying temporal lags (in msec) by which to shift refchannel + with respect to data channels + cfg.trials = integer array, trials to be used in regression, see FT_SELECTDATA + cfg.testtrials = cell-array or string, trial indices to be used as test folds in a cross-validation scheme + (numel(cfg.testrials == number of folds)) + cfg.nfold = scalar, indicating the number of test folds to + use in a cross-validation scheme + cfg.standardiserefdata = string, 'yes' or 'no', whether or not to standardise reference data + prior to the regression (default = 'no') + cfg.standardisedata = string, 'yes' or 'no', whether or not to standardise dependent variable + prior to the regression (default = 'no') + cfg.demeanrefdata = string, 'yes' or 'no', whether or not to make + reference data zero mean prior to the regression (default = 'no') + cfg.demeandata = string, 'yes' or 'no', whether or not to make + dependent variable zero mean prior to the regression (default = 'no') + cfg.threshold = integer array, ([1 by 2] or [1 by numel(cfg.channel) + numel(cfg.reflags)]), + regularization or shrinkage ('lambda') parameter to be loaded on the diagonal of the + penalty term (if cfg.method == 'mlrridge' or 'mlrqridge') + cfg.updatesens = string, 'yes' or 'no' (default = 'yes') + cfg.perchannel = string, 'yes' or 'no', or logical, whether or not to perform estimation of beta weights + separately per channel + cfg.output = string, 'model' or 'residual' (defaul = 'model'), + specifies what is outputed in .trial field in + cfg.performance = string, 'pearson' or 'r-squared' (default = + 'pearson'), indicating what performance metric is outputed in .weights(k).performance + field of for the k-th fold + cfg.covmethod = string, 'finite', or 'overlapfinite' (default + = 'finite'), compute covariance for the auto + terms on the finite datapoints per channel, or + only on the datapoints that are finite for the + cross terms. If there is a large number of + unshared nans across datasets, and if this number + is large in comparison to the total number of + datapoints the 'finite' method may become unstable. + + If cfg.threshold is 1 x 2 integer array, the cfg.threshold(1) parameter scales + uniformly in the dimension of predictor variable and cfg.threshold(2) in the + space of response variable. + + See also FT_PREPROCESSING, FT_DENOISE_SYNTHETIC, FT_DENOISE_PCA + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_denoise_tsr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_destroy_buffer` + +```{text} + FT_DESTROY_BUFFER stops the thread with the TCP server attached to + the local MATLAB instance and removes all data from memory. + + Use as + ft_destroy_buffer + + See also FT_CREATE_BUFFER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_destroy_buffer.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_detect_movement` + +```{text} + FT_SACCADE_DETECTION performs detection of movements such as saccades and + microsaccades, but also joystick movements, from time series data over multiple + trials. Different methods for detecting movements are implemented, which are + described in detail below: + + VELOCITY2D - detects micro/saccades using a two-dimensional (2D) velocity according + to "Engbert R, Kliegl R (2003) Vision Res 43:1035-1045". The vertical and the + horizontal eyetracker time series (for one eye) are transformed into velocities and + microsaccades are indentified as "outlier" eye movements that exceed a given + threshold for velocity and duration. This method has the additional options + cfg.velocity2D.kernel = vector 1 x nsamples, kernel to compute velocity (default = [1 1 0 -1 -1].*(data.fsample/6); + cfg.velocity2D.demean = 'no' or 'yes', whether to apply centering correction (default = 'yes') + cfg.velocity2D.mindur = minimum microsaccade durantion in samples (default = 3); + cfg.velocity2D.velthres = threshold for velocity outlier detection (default = 6); + + CLUSTERING - detects movements according to "Otero-Millan et al., (2014) J Vis 14". + + Use as + [cfg, movement] = ft_detect_movement(cfg, data) + where the input data should be organised in a structure as obtained from the + FT_PREPROCESSING function. + + The configuration can contain the following options + cfg.method = string representing the method for movement detection + 'velocity2D' detects microsaccades using the 2D velocity + 'clustering' use unsupervised clustering method to detect microsaccades + cfg.channel = Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details, (default = 'all') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + + The output argument "movement" is a Nx3 matrix. The first and second columns + specify the begining and end samples of a movement period (saccade, joystick, ...), + and the third column contains the peak velocity/acceleration movement. The thrid + column allows to convert movements into spike data representation, making it + compatible with the spike toolbox functions. + + 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_DATABROWSER, FT_DATATYPE_SPIKE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_detect_movement.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_determine_coordsys` + +```{text} + FT_DETERMINE_COORDSYS plots a geometrical object, allowing you to perform + a visual check on the coordinatesystem, the units and on the anatomical + labels for the coordinate system axes. + + Use as + [dataout] = ft_determine_coordsys(datain, ...) + where the input data structure can be either + - an anatomical MRI + - a cortical or head surface mesh + - an electrode, gradiometer or optode definition + - a volume conduction model of the head + or most other FieldTrip structures that represent geometrical information. + + Additional optional input arguments should be specified as key-value pairs + and can include + interactive = string, 'yes' or 'no' (default = 'yes') + axisscale = scaling factor for the reference axes and sphere (default = 1) + clim = lower and upper anatomical MRI limits (default = [0 1]) + + This function will pop up a figure that allows you to check whether the + alignment of the object relative to the coordinate system axes is correct + and what the anatomical labels of the coordinate system axes are. You + should switch on the 3D rotation option in the figure panel to rotate and + see the figure from all angles. To change the anatomical labels of the + coordinate system, you should press the corresponding keyboard button. + + Recognized and supported coordinate systems are 'ctf', 'bti', '4d', 'yokogawa', + 'eeglab', 'neuromag', 'itab', 'acpc', 'spm', 'mni', 'fsaverage', 'tal', 'scanras', + 'scanlps', 'dicom'. + + Furthermore, supported coordinate systems that do not specify the origin are 'ras', + 'als', 'lps', etc. See https://www.fieldtriptoolbox.org/faq/coordsys for more + details. + + See also FT_CONVERT_COORDSYS, FT_DETERMINE_UNITS, FT_CONVERT_UNITS, FT_PLOT_AXES, FT_PLOT_XXX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_determine_coordsys.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_determine_units` + +```{text} + FT_DETERMINE_UNITS tries to determine the units of a geometrical object by + looking at its size and by relating this to the approximate size of the + human head according to the following table: + from 0.050 to 0.500 -> meter + from 0.500 to 5.000 -> decimeter + from 5.000 to 50.000 -> centimeter + from 50.000 to 500.000 -> millimeter + + Use as + [output] = ft_determine_units(input) + + The following input data structures are supported + electrode or gradiometer array, see FT_DATATYPE_SENS + volume conduction model, see FT_DATATYPE_HEADMODEL + source model, see FT_DATATYPE_SOURCE and FT_PREPARE_SOURCEMODEL + anatomical mri, see FT_DATATYPE_VOLUME + segmented mri, see FT_DATATYPE_SEGMENTATION + anatomical or functional atlas, see FT_READ_ATLAS + + This function will add the field 'unit' to the output data structure with the + possible values 'm', 'cm ' or 'mm'. + + See also FT_CONVERT_UNITS, FT_DETERMINE_COODSYS, FT_CONVERT_COORDSYS, FT_PLOT_AXES, FT_PLOT_XXX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_determine_units.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_dipolefitting` + +```{text} + FT_DIPOLEFITTING perform grid search and non-linear fit with one or multiple + dipoles and try to find the location where the dipole model is best able + to explain the measured EEG or MEG topography. + + This function will initially scan the whole brain with a single dipole on + a regular coarse grid, and subsequently start at the most optimal location + with a non-linear search. Alternatively you can specify the initial + location of the dipole(s) and the non-linear search will start from there. + + Use as + [source] = ft_dipolefitting(cfg, data) + + The configuration has the following general fields + cfg.numdipoles = number, default is 1 + cfg.symmetry = 'x', 'y' or 'z' symmetry for two dipoles, can be empty (default = []) + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.gridsearch = 'yes' or 'no', perform global grid search for initial + guess for the dipole parameters (default = 'yes') + cfg.nonlinear = 'yes' or 'no', perform nonlinear search for optimal + dipole parameters (default = 'yes') + + If a grid search is performed, a source model needs to be specified. This should either be + specified as cfg.sourcemodel (see below), or as a set of parameters to define a 3-D regular grid. + In the latter case, a complete grid is constructed using FT_PREPARE_SOURCEMODEL. The specification + of a regular 3-D grid, aligned with the axes of the head coordinate system, can be obtained with + cfg.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto') + cfg.resolution = number (e.g. 1 cm) + If the source model destribes a triangulated cortical sheet, it is described as + cfg.sourcemodel.pos = N*3 matrix with the vertex positions of the cortical sheet + cfg.sourcemodel.tri = M*3 matrix that describes the triangles connecting the vertices + Alternatively the position of the dipoles at locations of interest can be + user-specified, for example obtained from an anatomical or functional MRI + cfg.sourcemodel.pos = N*3 matrix with position of each source + cfg.sourcemodel.inside = N*1 vector with boolean value whether grid point is inside brain (optional) + cfg.sourcemodel.dim = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional) + + If you do not start with a grid search, you have to give a starting location + for the nonlinear search + cfg.dip.pos = initial dipole position, matrix of Ndipoles x 3 + + The conventional approach is to fit dipoles to event-related averages, which + within FieldTrip can be obtained from the FT_TIMELOCKANALYSIS or from + the FT_TIMELOCKGRANDAVERAGE function. This has the additional options + cfg.latency = [begin end] in seconds or 'all' (default = 'all') + cfg.model = 'moving' or 'regional' + A moving dipole model has a different position (and orientation) for each + timepoint, or for each component. A regional dipole model has the same + position for each timepoint or component, and a different orientation. + + You can also fit dipoles to the spatial topographies of an independent + component analysis, obtained from the FT_COMPONENTANALYSIS function. + This has the additional options + cfg.component = array with numbers (can be empty -> all) + + You can also fit dipoles to the spatial topographies that are present + in the data in the frequency domain, which can be obtained using the + FT_FREQANALYSIS function. This has the additional options + cfg.frequency = single number (in Hz) + + Low level details of the fitting can be specified in the cfg.dipfit structure + cfg.dipfit.display = level of display, can be 'off', 'iter', 'notify' or 'final' (default = 'iter') + cfg.dipfit.optimfun = function to use, can be 'fminsearch' or 'fminunc' (default is determined automatic) + cfg.dipfit.maxiter = maximum number of function evaluations allowed (default depends on the optimfun) + cfg.dipfit.checkinside = boolean, check that the dipole remains in the source compartment (default = false) + + Optionally, you can modify the leadfields by reducing the rank, i.e. remove the weakest orientation + cfg.reducerank = 'no', or number (default = 3 for EEG, 2 for MEG) + cfg.backproject = 'yes' or 'no', determines when reducerank is applied whether the + lower rank leadfield is projected back onto the original linear + subspace, or not (default = 'yes') + + The volume conduction model of the head should be specified as + cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL + + The EEG or MEG sensor positions can be present in the data or can be specified as + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + + 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_SOURCEANALYSIS, FT_PREPARE_LEADFIELD, FT_PREPARE_HEADMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_dipolefitting.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_dipolesimulation` + +```{text} + FT_DIPOLESIMULATION simulates channel-level time-series data that consists of the + the spatial distribution of the the field or potential of one or multiple dipoles. + + Use as + data = ft_dipolesimulation(cfg) + which will return a raw data structure that resembles the output of + FT_PREPROCESSING. + + The dipoles position and orientation have to be specified with + cfg.sourcemodel.pos = [Rx Ry Rz] (size Nx3) + cfg.sourcemodel.mom = [Qx Qy Qz] (size 3xN) + cfg.sourcemodel.unit = string, can be 'mm', 'cm', 'm' (default is automatic) + + The timecourse of the dipole activity is given as a cell-array with one + dipole signal per trial + cfg.sourcemodel.signal = cell-array with one dipole signal per trial + or by specifying the parameters of a sine-wave signal + cfg.sourcemodel.frequency = in Hz + cfg.sourcemodel.phase = in radians + cfg.sourcemodel.amplitude = per dipole + + The number of trials and the time axes of the trials can be specified by + cfg.fsample = simulated sample frequency (default = 1000) + cfg.trllen = length of simulated trials in seconds (default = 1) + cfg.numtrl = number of simulated trials (default = 10) + cfg.baseline = number (default = 0.3) + or by + cfg.time = cell-array with one time axis per trial, for example obtained from an existing dataset + + Random white noise can be added to the data in each trial, either by + specifying an absolute or a relative noise level + cfg.relnoise = add noise with level relative to data signal + cfg.absnoise = add noise with absolute level + cfg.randomseed = 'yes' or a number or vector with the seed value (default = 'yes') + + Optional input arguments are + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.dipoleunit = units for dipole amplitude (default nA*m) + cfg.chanunit = Nx1 cell-array with units for the channel data + + Optionally, you can modify the leadfields by reducing the rank, i.e. remove the weakest orientation + cfg.reducerank = 'no', or number (default = 3 for EEG, 2 for MEG) + cfg.backproject = 'yes' or 'no', determines when reducerank is applied whether the + lower rank leadfield is projected back onto the original linear + subspace, or not (default = 'yes') + + The volume conduction model of the head should be specified as + cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL + + The EEG or MEG sensor positions should be specified as + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + + See also FT_SOURCEANALYSIS, FT_DIPOLEFITTING, FT_TIMELOCKSIMULATION, + FT_FREQSIMULATION, FT_CONNECTIVITYSIMULATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_dipolesimulation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_documentationconfiguration` + +```{text} + FT_DOCUMENTATIONCONFIGURATION is a helper function to maintain the online + documentation of all configuration options. + + Normal users will not be calling this function, but will rather look at + http://www.fieldtriptoolbox.org/configuration where the output of this + function can be found. + + See also FT_DOCUMENTATIONREFERENCE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_documentationconfiguration.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_documentationreference` + +```{text} + FT_DOCUMENTATIONREFERENCE is a helper function to maintain the + online reference documentation. + + Normal users will not be calling this function, but will rather look at + http://www.fieldtriptoolbox.org/reference where the output of this function can + be found. + + See also FT_DOCUMENTATIONCONFIGURATION, MATLAB2MARKDOWN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_documentationreference.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_electrodeplacement` + +```{text} + FT_ELECTRODEPLACEMENT allows manual placement of electrodes on a MRI scan, CT scan + or on a triangulated surface of the head. This function supports different methods. + + VOLUME - Navigate an orthographic display of a volume (e.g. CT or MRI scan), and + assign an electrode label to the current crosshair location by clicking on a label + in the eletrode list. You can undo the selection by clicking on the same label + again. The electrode labels shown in the list can be prespecified using cfg.channel + when calling ft_electrodeplacement. The zoom slider allows zooming in at the + location of the crosshair. The intensity sliders allow thresholding the image's low + and high values. The magnet feature transports the crosshair to the nearest peak + intensity voxel, within a certain voxel radius of the selected location. The labels + feature displays the labels of the selected electrodes within the orthoplot. The + global feature allows toggling the view between all and near-crosshair + markers. The scan feature allows toggling between scans when another scan + is given as input. + + HEADSHAPE - Navigate a triangulated scalp (for EEG) or brain (for ECoG) surface, + and assign an electrode location by clicking on the surface. The electrode is + placed on the triangulation itself. + + 1020 - Starting from a triangulated scalp surface and the nasion, inion, left and + right pre-auricular points, this automatically constructs and follows contours over + the surface according to the 5% system. Electrodes are placed at certain relative + distances along these countours. This is an extension of the 10-20 standard + electrode placement system and includes the 20%, 10% and 5% locations. See + "Oostenveld R, Praamstra P. The five percent electrode system for high-resolution + EEG and ERP measurements. Clin Neurophysiol. 2001 Apr;112(4):713-9" for details. + + SHAFT - This is for placing electrodes along a linear sEEG shaft. The tip of the + shaft corresponding to the first electrode, another point along the shaft, and the + distance between the electrodes should be specified. If the shaft is not straight + but curved, you should specify multiple (at least two) points along the shaft, + i.e., specify cfg.shaft.along as an Nx3 array for N points along the shaft. The + number of electrodes to be distributed along the shaft is determined from cfg.channel. + + GRID - This is for placing electrodes on a regular MxN ECoG grid. Each of the four + cornerpoints of the grid must be specified, along with the dimensions of the grid. + Following piecewise linear placement of the electrodes on the grid, you can use + FT_ELECTRODEREALIGN with cfg.method='project' to project them to the curved brain + surface. + + Use as + [elec] = ft_electrodeplacement(cfg, mri) + [elec] = ft_electrodeplacement(cfg, ct) + [elec] = ft_electrodeplacement(cfg, mri, ct, ..) + where the second and subsequent input arguments should be one or multiple + anatomical MRIs and/or CTs, or + [elec] = ft_electrodeplacement(cfg, headshape) + where the input headshape should be a surface triangulation. + + The configuration can contain the following options + cfg.method = string representing the method for placing the electrodes + 'volume' interactively locate electrodes on three orthogonal slices of a volumetric MRI or CT scan + 'headshape' interactively locate electrodes on a head surface + '1020' automatically locate electrodes on a head surface according to the 10-20 system + 'shaft' automatically locate electrodes along a linear sEEG shaft + 'grid' automatically locate electrodes on a MxN ECoG grid + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default = 'opengl') + + The following options apply to the 'volume' method + cfg.parameter = string, field in data (default = 'anatomy' if present in data) + cfg.channel = Nx1 cell-array with selection of channels (default = {'1' '2' ...}) + cfg.elec = struct containing previously placed electrodes (this overwrites cfg.channel) + cfg.clim = color range of the data (default = [0 1], i.e. the full range) + cfg.magtype = string representing the 'magnet' type used for placing the electrodes + 'peakweighted' place electrodes at weighted peak intensity voxel (default) + 'troughweighted' place electrodes at weighted trough intensity voxel + 'peak' place electrodes at peak intensity voxel (default) + 'trough' place electrodes at trough intensity voxel + 'weighted' place electrodes at center-of-mass + cfg.magradius = number representing the radius for the cfg.magtype based search (default = 3) + + The following options apply to the '1020' method + cfg.fiducial.nas = 1x3 vector with coordinates + cfg.fiducial.ini = 1x3 vector with coordinates + cfg.fiducial.lpa = 1x3 vector with coordinates + cfg.fiducial.rpa = 1x3 vector with coordinates + cfg.feedback = string, can be 'yes' or 'no' for detailed feedback (default = 'yes') + + The following options apply to the 'shaft' method + cfg.shaft.tip = 1x3 position of the electrode at the tip of the shaft + cfg.shaft.along = 1x3 or Nx3 positions along the shaft + cfg.shaft.distance = scalar, distance between electrodes + + The following options apply to the 'grid' method + cfg.grid.corner1 = 1x3 position of the upper left corner point + cfg.grid.corner2 = 1x3 position of the upper right corner point + cfg.grid.corner3 = 1x3 position of the lower left corner point + cfg.grid.corner4 = 1x3 position of the lower right corner point + + In the interactive 'headshape' and 'volume' methods you can click once on an + already assigned electrode to jump to that electrode position and you can click + twice to remove the assigned electrode position. + + See also FT_ELECTRODEREALIGN, FT_VOLUMEREALIGN, FT_VOLUMESEGMENT, FT_PREPARE_MESH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_electrodeplacement.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_electroderealign` + +```{text} + FT_ELECTRODEREALIGN rotates, translates, scales and warps electrode positions. The + default is to only rotate and translate, i.e. to do a rigid body transformation in + which only the coordinate system is changed. With the right settings if can apply + additional deformations to the input sensors (e.g. scale them to better fit the + skin surface). The different methods are described in detail below. + + INTERACTIVE - You can display the skin surface together with the electrode or + gradiometer positions, and manually (using the graphical user interface) adjust the + rotation, translation and scaling parameters, so that the electrodes correspond + with the skin. + + FIDUCIAL - You can apply a rigid body realignment based on three fiducial + locations. After realigning, the fiducials in the input electrode set (typically + nose, left and right ear) are along the same axes as the fiducials in the template + electrode set. + + TEMPLATE - You can apply a spatial transformation/deformation that automatically + minimizes the distance between the electrodes or gradiometers and a template or + sensor array. The warping methods use a non-linear search to minimize the distance + between the input sensor positions and the corresponding template sensors. + + HEADSHAPE - You can apply a spatial transformation/deformation that automatically + minimizes the distance between the electrodes and the head surface. The warping + methods use a non-linear search to minimize the distance between the input sensor + positions and the projection of the electrodes on the head surface. + + PROJECT - This projects each of the electrodes to the nearest point on the + head surface mesh. + + MOVEINWARD - This moves all electrodes inward according to their normals. + + MNI - This transforms the electrodes nonlinearly using the same transformation of + the individual anatomical MRI to the MNI template. + + Use as + [elec_realigned] = ft_electroderealign(cfg) + with the electrode or gradiometer details in the configuration, or as + [elec_realigned] = ft_electroderealign(cfg, elec_orig) + with the electrode or gradiometer definition as 2nd input argument. + + The configuration can contain the following options + cfg.method = string representing the method for aligning or placing the electrodes + 'interactive' realign manually using a graphical user interface + 'fiducial' realign using three fiducials (e.g. NAS, LPA and RPA) + 'template' realign the electrodes to match a template set + 'headshape' realign the electrodes to fit the head surface + 'project' projects electrodes onto the head surface + 'moveinward' moves electrodes inward along their normals + 'mni' transforms electrodes from individual subject to MNI space + cfg.warp = string describing the spatial transformation for the template and headshape methods + 'rigidbody' apply a rigid-body warp (default) + 'globalrescale' apply a rigid-body warp with global rescaling + 'traditional' apply a rigid-body warp with individual axes rescaling + 'nonlin1' apply a 1st order non-linear warp + 'nonlin2' apply a 2nd order non-linear warp + 'nonlin3' apply a 3rd order non-linear warp + 'nonlin4' apply a 4th order non-linear warp + 'nonlin5' apply a 5th order non-linear warp + 'dykstra2012' back-project ECoG onto the cortex using energy minimzation + 'hermes2010' back-project ECoG onto the cortex along the local norm vector + 'fsaverage' surface-based realignment with FreeSurfer fsaverage brain (left->left or right->right) + 'fsaverage_sym' surface-based realignment with FreeSurfer fsaverage_sym left hemisphere (left->left or right->left) + 'fsinflated' surface-based realignment with FreeSurfer individual subject inflated brain (left->left or right->right) + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.keepchannel = string, 'yes' or 'no' (default = 'no') + cfg.fiducial = cell-array with the name of three fiducials used for realigning (default = {'nasion', 'lpa', 'rpa'}) + cfg.casesensitive = 'yes' or 'no', determines whether string comparisons between electrode labels are case sensitive (default = 'yes') + cfg.feedback = 'yes' or 'no' (default = 'no') + + The electrode positions can be present in the 2nd input argument or can be specified as + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + + If you want to realign the EEG electrodes using anatomical fiducials, you should + specify the target location of the three fiducials, e.g. + cfg.target.pos(1,:) = [110 0 0] % location of the nose + cfg.target.pos(2,:) = [0 90 0] % location of the left ear + cfg.target.pos(3,:) = [0 -90 0] % location of the right ear + cfg.target.label = {'NAS', 'LPA', 'RPA'} + + If you want to align EEG electrodes to a single or multiple template electrode sets + (which will be averaged), you should specify the template electrode sets either as + electrode structures (i.e. when they are already read in memory) or their file + names using + cfg.target = single electrode set that serves as standard + or + cfg.target{1..N} = list of electrode sets that will be averaged + + If you want to align EEG electrodes to the head surface, you should specify the head surface as + cfg.headshape = a filename containing headshape, a structure containing a + single triangulated boundary, or a Nx3 matrix with surface + points + + If you want to align ECoG electrodes to the pial surface, you first need to compute + the cortex hull with FT_PREPARE_MESH. Then use either the algorithm described in + Dykstra et al. (2012, Neuroimage) or in Hermes et al. (2010, J Neurosci methods) to + snap the electrodes back to the cortical hull, e.g. + cfg.method = 'headshape' + cfg.warp = 'dykstra2012', or 'hermes2010' + cfg.headshape = a filename containing headshape, a structure containing a + single triangulated boundary, or a Nx3 matrix with surface + points + cfg.feedback = 'yes' or 'no' (default), feedback of the iteration procedure + + Additional configuration options for cfg.warp='dykstra2012' + cfg.maxiter = number (default: 50), maximum number of optimization iterations + cfg.pairmethod = 'pos' (default) or 'label', the method for electrode + pairing on which the deformation energy is based + cfg.isodistance = 'yes', 'no' (default) or number, to enforce isotropic + inter-electrode distances (pairmethod 'label' only) + cfg.deformweight = number (default: 1), weight of deformation relative + to shift energy cost (lower increases grid flexibility) + + If you want to move the electrodes inward, you should specify + cfg.moveinward = number, the distance that the electrode should be moved + inward (negative numbers result in an outward move) + + If you want to align ECoG electrodes to the freesurfer average brain, you should + specify the path to your headshape (e.g., lh.pial), and ensure you have the + corresponding registration file (e.g., lh.sphere.reg) in the same directory. + Moreover, the path to the local freesurfer home is required. Note that, because the + electrodes are being aligned to the fsaverage brain, the corresponding brain should + be also used when plotting the data, i.e. use freesurfer/subjects/fsaverage/surf/lh.pial + rather than surface_pial_left.mat + cfg.method = 'headshape' + cfg.warp = 'fsaverage' + cfg.headshape = string, filename containing subject headshape (e.g. ) + cfg.fshome = string, path to freesurfer + + If you want to transform electrodes from individual subject coordinates to MNI + space, you should specify the following + cfg.mri = structure with the individual anatomical MRI relative to which electrodes are specified, or the filename of the MRI, see FT_READ_MRI + cfg.templatemri = string, filename of the MNI template (default = 'T1.mnc' for SPM2 or 'T1.nii' for SPM8 and SPM12) + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + cfg.spmmethod = string, 'old', 'new' or 'mars', see FT_VOLUMENORMALISE + cfg.nonlinear = string, 'yes' or 'no', see FT_VOLUMENORMALISE + + See also FT_READ_SENS, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN, + FT_DETERMINE_COORDSYS, FT_PREPARE_MESH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_electroderealign.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_electrodermalactivity` + +```{text} + FT_ELECTRODERMALACTIVITY estimates the electrodermal activity from a recording of + the electric resistance of the skin. + + Use as + eda = ft_electrodermalactivity(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + The configuration structure has the following options + cfg.channel = selected channel for processing, see FT_CHANNELSELECTION + cfg.feedback = 'yes' or 'no' + cfg.medianwindow = scalar, length of window for median filter in seconds (default = 8) + + After using this function you can use FT_REDEFINETRIAL and FT_TIMELOCKANLAYSIS to + investigate electrodermal responses (EDRs) to stimulation. You can use + FT_ARTIFACT_THRESHOLD to determine the timing and frequency of nonspecific EDRs. + + See https://doi.org/10.1111/j.1469-8986.2012.01384.x "Publication recommendations + for electrodermal measurements" by the SPR for an introduction in electrodermal + methods and for recommendations. + + See also FT_HEARTRATE, FT_HEADMOVEMENT, FT_REGRESSCONFOUND + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_electrodermalactivity.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_error` + +```{text} + FT_ERROR prints an error message on screen, just like the standard ERROR function. + + Use as + ft_error(...) + with arguments similar to fprintf, or + ft_error(msgId, ...) + with arguments similar to error. + + See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_error.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_estimate_units` + +```{text} + FT_ESTIMATE_UNITS tries to determine the units of a geometrical object by + looking at its size and by relating this to the approximate size of the + human head according to the following table: + from 0.050 to 0.500 -> meter + from 0.500 to 5.000 -> decimeter + from 5.000 to 50.000 -> centimeter + from 50.000 to 500.000 -> millimeter + + Use as + unit = ft_estimate_units(size) + + This function will return one of the following strings + 'm' + 'cm' + 'mm' + + See also FT_CONVERT_UNITS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_estimate_units.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_eventtiminganalysis` + +```{text} + FT_EVENTTIMINGANALYSIS computes a model of single trial event- related activity, + by estimating per trial the latency (and amplitude) of event-related signal + components. + + Use as + [dataout] = ft_eventtiminganalysis(cfg, data) + where data is single-channel raw data as obtained by FT_PREPROCESSING + and cfg is a configuration structure according to + + cfg.method = method for estimating event-related activity + 'aseo', analysis of single-trial ERP and ongoing + activity (according to Xu et al, 2009) + 'gbve', graph-based variability estimation + (according to Gramfort et al, IEEE TBME 2009) + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.output = 'model', or 'residual', which returns the modelled data, + or the residuals. + + Method specific options are specified in the appropriate substructure. + + For the ASEO method, the following options can be specified: + cfg.aseo.noiseEstimate = 'non-parametric' or 'parametric', estimate noise + using parametric or non-parametric (default) method + cfg.aseo.tapsmofrq = value, smoothing parameter of noise for + nonparametric estimation (default = 5) + cfg.aseo.jitter = value, time jitter in initial timewindow + estimate (in seconds). default 0.050 seconds + cfg.aseo.numiteration = value, number of iteration (default = 1) + cfg.aseo.initlatency = Nx2 matrix, initial set of latencies in seconds of event- + related components, give as [comp1start, comp1end; + comp2start, comp2end] (default not + specified). For multiple channels it should + be a cell-array, one matrix per channel + Alternatively, rather than specifying a (set of latencies), one can also + specify: + + cfg.aseo.initcomp = vector, initial estimate of the waveform + components. For multiple channels it should + be a cell-array, one matrix per channel. + + For the GBVE method, the following options can be specified: + cfg.gbve.sigma = vector, range of sigma values to explore in + cross-validation loop (default: 0.01:0.01:0.2) + cfg.gbve.distance = scalar, distance metric to use as + evaluation criterion, see plugin code for + more informatoin + cfg.gbve.alpha = vector, range of alpha values to explor in + cross-validation loop (default: [0 0.001 0.01 0.1]) + cfg.gbve.exponent = scalar, see plugin code for information + cfg.gbve.use_maximum = boolean, (default: 1) consider the positive going peak + cfg.gbve.show_pca = boolean, see plugin code (default 0) + cfg.gbve.show_trial_number = boolean, see plugin code (default 0) + cfg.gbve.verbose = boolean (default: 1) + cfg.gbve.disp_log = boolean, see plugin code (default 0) + cfg.gbve.latency = vector [min max], latency range in s + (default: [-inf inf]) + cfg.gbve.xwin = scalar smoothing parameter for moving + average smoothing (default: 1), see + eeglab's movav function for more + information. + + 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_SINGLETRIALANALYSIS_ASEO + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_eventtiminganalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_examplefunction` + +```{text} + FT_EXAMPLEFUNCTION demonstrates to new developers how a FieldTrip function should look like + + Use as + outdata = ft_examplefunction(cfg, indata) + where indata is <> + and cfg is a configuration structure that should contain + + <> + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_examplefunction.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_fetch_data` + +```{text} + FT_FETCH_DATA mimics the behavior of FT_READ_DATA, but for a FieldTrip + raw data structure instead of a file on disk. + + Use as + [dat] = ft_fetch_data(data, ...) + + See also FT_READ_DATA, FT_FETCH_HEADER, FT_FETCH_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_fetch_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_fetch_event` + +```{text} + FT_FETCH_EVENT mimics the behavior of FT_READ_EVENT, but for a FieldTrip + raw data structure instead of a file on disk. + + Use as + event = ft_fetch_event(data) + + See also FT_READ_EVENT, FT_FETCH_HEADER, FT_FETCH_DATA + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_fetch_event.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_fetch_header` + +```{text} + FT_FETCH_HEADER mimics the behavior of FT_READ_HEADER, but for a FieldTrip + raw data structure instead of a file on disk. + + Use as + hdr = ft_fetch_header(data) + + See also FT_READ_HEADER, FT_FETCH_DATA, FT_FETCH_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_fetch_header.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_filetype` + +```{text} + FT_FILETYPE determines the filetype of many EEG/MEG/MRI data files by + looking at the name, extension and optionally (part of) its contents. + It tries to determine the global type of file (which usually + corresponds to the manufacturer, the recording system or to the + software used to create the file) and the particular subtype (e.g. + continuous, average). + + Use as + type = ft_filetype(filename) + type = ft_filetype(dirname) + + This gives you a descriptive string with the data type, and can be + used in a switch-statement. The descriptive string that is returned + usually is something like 'XXX_YYY'/ where XXX refers to the + manufacturer and YYY to the type of the data. + + Alternatively, use as + flag = ft_filetype(filename, type) + flag = ft_filetype(dirname, type) + This gives you a boolean flag (0 or 1) indicating whether the file + is of the desired type, and can be used to check whether the + user-supplied file is what your subsequent code expects. + + Alternatively, use as + flag = ft_filetype(dirlist, type) + where the dirlist contains a list of files contained within one + directory. This gives you a boolean vector indicating for each file + whether it is of the desired type. + + Most filetypes of the following manufacturers and/or software programs are recognized + - 4D/BTi + - AFNI + - ASA + - Analyse + - Analyze/SPM + - BESA + - Bioimage Suite *.mgrid + - BrainSuite + - BrainVisa + - BrainVision + - Curry + - Dataq + - EDF + - EEProbe + - Elektra/Neuromag + - EEGsynth *.tsv + - FreeSurfer + - LORETA + - Localite + - MINC + - Neuralynx + - Neuroscan + - Nihon Koden *.m00 + - OpenVibe MATLAB files *.mat + - Plexon + - SR Research Eyelink + - SensoMotoric Instruments (SMI) *.txt + - Tobii *.tsv + - Stanford *.ply + - Tucker Davis Technology + - CTF + - Yokogawa & Ricoh + - nifti, gifti + - Nicolet *.e (currently from Natus, formerly Carefusion, Viasys and Taugagreining. Also known as Oxford/Teca/Medelec Valor Nervus) + - Biopac *.acq + - AnyWave *.ades + - Qualisys *.tsv + - Mrtrix *.mif + - MAUS *.TextGrid + - Neurodata Without Borders *.nwb + - PhysioNet *.hea and *.dat + - NIRx *.tpl, *.wl1 and *.wl2 + - York Instruments *.meghdf5 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_filetype.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_filter_event` + +```{text} + FT_FILTER_EVENT does what its name implies + + Use as + event = ft_filter_event(event, ...) + + The optional arguments should come in key-value pairs and determine the + filter characteristics: + type = cell-array with strings + value = numeric array + sample = numeric array + timestamp = numeric array + offset = numeric array + duration = numeric array + minsample = value + maxsample = value + minduration = value + maxduration = value + mintimestamp = value + maxtimestamp = value + minnumber = value, applies only if event.number is present + maxnmumber = value, applies only if event.number is present + + See also FT_READ_EVENT, FT_WRITE_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_filter_event.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_findcfg` + +```{text} + FT_FINDCFG searches for an element in the cfg structure + or in the nested previous cfgs + + Use as + val = ft_findcfg(cfg, var) + where the name of the variable should be specified as string. + + e.g. + trl = ft_findcfg(cfg, 'trl') + event = ft_findcfg(cfg, 'event') + + See also FT_GETOPT, FT_CFG2KEYVAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_findcfg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_flush_data` + +```{text} + FT_FLUSH_DATA removes all data from the data queue + + Use as + ft_flush_data(filename, ...) + + See also FT_FLUSH_HEADER, FT_FLUSH_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_flush_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_flush_event` + +```{text} + FT_FLUSH_EVENT removes all events from the event queue + + Use as + ft_flush_event(filename, ...) + + See also FT_FLUSH_HEADER, FT_FLUSH_DATA + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_flush_event.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_flush_header` + +```{text} + FT_FLUSH_HEADER removes the header information from the data queue + this also removes all data associated with the specific header. + + Use as + ft_flush_header(filename, ...) + + See also FT_FLUSH_DATA, FT_FLUSH_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_flush_header.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqanalysis` + +```{text} + FT_FREQANALYSIS performs frequency and time-frequency analysis + on time series data over multiple trials + + Use as + [freq] = ft_freqanalysis(cfg, data) + + The input data should be organised in a structure as obtained from + FT_PREPROCESSING or FT_MVARANALYSIS. The configuration depends on the + type of computation that you want to perform. + + The configuration should contain: + cfg.method = different methods of calculating the spectra + 'mtmfft', analyses an entire spectrum for the entire data + length, implements multitaper frequency transformation. + 'mtmconvol', implements multitaper time-frequency + transformation based on multiplication in the + frequency domain. + 'wavelet', implements wavelet time frequency + transformation (using Morlet wavelets) based on + multiplication in the frequency domain. + 'tfr', implements wavelet time frequency + transformation (using Morlet wavelets) based on + convolution in the time domain. + 'mvar', does a fourier transform on the coefficients + of an estimated multivariate autoregressive model, + obtained with FT_MVARANALYSIS. In this case, the + output will contain a spectral transfer matrix, + the cross-spectral density matrix, and the + covariance matrix of the innovation noise. + 'superlet', combines Morlet-wavelet based + decompositions, see below. + 'irasa', implements Irregular-Resampling Auto-Spectral + Analysis (IRASA), to separate the fractal components + from the periodicities in the signal. + 'hilbert', implements the filter-Hilbert method, see + below. + cfg.output = 'pow' return the power-spectra + 'powandcsd' return the power and the cross-spectra + 'fourier' return the complex Fourier-spectra + 'fractal' (when cfg.method = 'irasa'), return the + fractal component of the spectrum (1/f) + 'original' (when cfg.method = 'irasa'), return the + full power spectrum + 'fooof' returns a smooth power-spectrum, + based on a parametrization of a mixture of aperiodic and periodic + components (only works with cfg.method = 'mtmfft') + 'fooof_aperiodic' returns a power-spectrum with the + fooof based estimate of the aperiodic part of the signal. + 'fooof_peaks' returns a power-spectrum with the fooof + based estimate of the aperiodic signal removed, + it's expressed as + 10^(log10(fooof)-log10(fooof_aperiodic)) + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.channelcmb = Mx2 cell-array with selection of channel pairs (default = {'all' 'all'}), + see FT_CHANNELCOMBINATION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.keeptrials = 'yes' or 'no', return individual trials or average (default = 'no') + cfg.keeptapers = 'yes' or 'no', return individual tapers or average (default = 'no') + cfg.pad = number, 'nextpow2', or 'maxperlen' (default), length + in seconds to which the data can be padded out. The + padding will determine your spectral resolution. If you + want to compare spectra from data pieces of different + lengths, you should use the same cfg.pad for both, in + order to spectrally interpolate them to the same + spectral resolution. The new option 'nextpow2' rounds + the maximum trial length up to the next power of 2. By + using that amount of padding, the FFT can be computed + more efficiently in case 'maxperlen' has a large prime + factor sum. + cfg.padtype = string, type of padding (default 'zero', see + ft_preproc_padding) + cfg.polyremoval = number (default = 0), specifying the order of the + polynome which is fitted and subtracted from the time + domain data prior to the spectral analysis. For + example, a value of 1 corresponds to a linear trend. + The default is a mean subtraction, thus a value of 0. + If no removal is requested, specify -1. + see FT_PREPROC_POLYREMOVAL for details + + + METHOD SPECIFIC OPTIONS AND DESCRIPTIONS + + MTMFFT performs frequency analysis on any time series trial data using a + conventional single taper (e.g. Hanning) or using the multiple tapers based on + discrete prolate spheroidal sequences (DPSS), also known as the Slepian + sequence. + cfg.taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') + For cfg.output='powandcsd', you should specify the channel combinations + between which to compute the cross-spectra as cfg.channelcmb. Otherwise + you should specify only the channels in cfg.channel. + cfg.foilim = [begin end], frequency band of interest + OR + cfg.foi = vector 1 x numfoi, frequencies of interest + cfg.tapsmofrq = number, the amount of spectral smoothing through + multi-tapering. Note that 4 Hz smoothing means + plus-minus 4 Hz, i.e. a 8 Hz smoothing box. + + MTMCONVOL performs time-frequency analysis on any time series trial data using + the 'multitaper method' (MTM) based on Slepian sequences as tapers. + Alternatively, you can use conventional tapers (e.g. Hanning). + cfg.tapsmofrq = vector 1 x numfoi, the amount of spectral smoothing + through multi-tapering. Note that 4 Hz smoothing means + plus-minus 4 Hz, i.e. a 8 Hz smoothing box. + cfg.foi = vector 1 x numfoi, frequencies of interest + cfg.taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') + For cfg.output='powandcsd', you should specify the channel combinations + between which to compute the cross-spectra as cfg.channelcmb. Otherwise + you should specify only the channels in cfg.channel. + cfg.t_ftimwin = vector 1 x numfoi, length of time window (in seconds) + cfg.toi = vector 1 x numtoi, the times on which the analysis + windows should be centered (in seconds), or a string + such as '50%' or 'all'. Both string options + use all timepoints available in the data, but 'all' + centers a spectral estimate on each sample, whereas + the percentage specifies the degree of overlap between + the shortest time windows from cfg.t_ftimwin. + + WAVELET performs time-frequency analysis on any time series trial data using the + 'wavelet method' based on Morlet wavelets. Using mulitplication in the frequency + domain instead of convolution in the time domain. + cfg.foi = vector 1 x numfoi, frequencies of interest + OR + cfg.foilim = [begin end], frequency band of interest + cfg.toi = vector 1 x numtoi, the times on which the analysis + windows should be centered (in seconds) + cfg.width = 'width', or number of cycles, of the wavelet (default = 7) + cfg.gwidth = determines the length of the used wavelets in standard + deviations of the implicit Gaussian kernel and should + be chosen >= 3; (default = 3) + + The standard deviation in the frequency domain (sf) at frequency f0 is + defined as: sf = f0/width + The standard deviation in the temporal domain (st) at frequency f0 is + defined as: st = 1/(2*pi*sf) + + SUPERLET performs time-frequency analysis on any time series trial data using the + 'superlet method' based on a frequency-wise combination of Morlet wavelets of varying cycle + widths (see Moca et al. 2021, https://doi.org/10.1038/s41467-020-20539-9). + cfg.foi = vector 1 x numfoi, frequencies of interest + OR + cfg.foilim = [begin end], frequency band of interest + cfg.toi = vector 1 x numtoi, the times on which the analysis + windows should be centered (in seconds) + cfg.width = 'width', or number of cycles, of the base wavelet (default = 3) + cfg.gwidth = determines the length of the used wavelets in standard + deviations of the implicit Gaussian kernel and should + be chosen >= 3; (default = 3) + cfg.combine = 'additive', 'multiplicative' (default = 'multiplicative') + determines if cycle numbers of wavelets comprising a superlet + are chosen additively or multiplicatively + cfg.order = vector 1 x numfoi, superlet order, i.e. number of combined + wavelets, for individual frequencies of interest. + + The standard deviation in the frequency domain (sf) at frequency f0 is + defined as: sf = f0/width + The standard deviation in the temporal domain (st) at frequency f0 is + defined as: st = 1/(2*pi*sf) + + HILBERT performs time-frequency analysis on any time series data using a frequency specific + bandpass filter, followed by the Hilbert transform. + cfg.foi = vector 1 x numfoi, frequencies of interest + cfg.toi = vector 1 x numtoi, the time points for which the estimates will be returned (in seconds) + cfg.width = scalar, or vector (default: 1), specifying the half bandwidth of the filter; + cfg.edgartnan = 'no' (default) or 'yes', replace filter edges with nans, works only for finite impulse response (FIR) filters, and + requires a user specification of the filter order + + For the bandpass filtering the following options can be specified, the default values are as in FT_PREPROC_BANDPASSFILTER, for more + information see the help of FT_PREPROCESSING + cfg.bpfilttype + cfg.bpfiltord = (optional) scalar, or vector 1 x numfoi; + cfg.bpfiltdir + cfg.bpinstabilityfix + cfg.bpfiltdf + cfg.bpfiltwintype + cfg.bpfiltdev + + TFR performs time-frequency analysis on any time series trial data using the + 'wavelet method' based on Morlet wavelets. Using convolution in the time domain + instead of multiplication in the frequency domain. + cfg.foi = vector 1 x numfoi, frequencies of interest + OR + cfg.foilim = [begin end], frequency band of interest + cfg.width = 'width', or number of cycles, of the wavelet (default = 7) + cfg.gwidth = determines the length of the used wavelets in standard + deviations of the implicit Gaussian kernel and should + be choosen >= 3; (default = 3) + + + 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_FREQSTATISTICS, FT_FREQDESCRIPTIVES, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqanalysis_mvar` + +```{text} + FT_FREQANALYSIS_MVAR performs frequency analysis on + mvar data, by fourier transformation of the coefficients. The output + contains cross-spectral density, spectral transfer matrix, and the + covariance of the innovation noise. The dimord = 'chan_chan(_freq)(_time) + + The function is stand-alone, but is typically called through + FT_FREQANALYSIS, specifying cfg.method = 'mvar'. + + Use as + [freq] = ft_freqanalysis(cfg, data), with cfg.method = 'mvar' + + or + + [freq] = ft_freqanalysis_mvar(cfg, data) + + The input data structure should be a data structure created by + FT_MVARANALYSIS, i.e. a data-structure of type 'mvar'. + + The configuration can contain: + cfg.foi = vector with the frequencies at which the spectral quantities + are estimated (in Hz). Default: 0:1:Nyquist + cfg.feedback = 'none', or any of the methods supported by FT_PROGRESS, + for providing feedback to the user in the command + window. + + 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_MVARANALYSIS, FT_DATATYPE_MVAR, FT_PROGRESS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqanalysis_mvar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqbaseline` + +```{text} + FT_FREQBASELINE performs baseline normalization for time-frequency data + + Use as + [freq] = ft_freqbaseline(cfg, freq) + where the freq data comes from FT_FREQANALYSIS and the configuration + should contain + cfg.baseline = [begin end] (default = 'no'), alternatively an + Nfreq x 2 matrix can be specified, that provides + frequency specific baseline windows. + cfg.baselinetype = 'absolute', 'relative', 'relchange', 'normchange', 'db', 'vssum' or 'zscore' (default = 'absolute') + cfg.parameter = field for which to apply baseline normalization, or + cell-array of strings to specify multiple fields to normalize + (default = 'powspctrm') + + See also FT_FREQANALYSIS, FT_TIMELOCKBASELINE, FT_FREQCOMPARISON, + FT_FREQGRANDAVERAGE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqbaseline.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqdescriptives` + +```{text} + FT_FREQDESCRIPTIVES computes descriptive univariate statistics of + the frequency or time-frequency decomposition of the EEG/MEG signal, + thus the powerspectrum and its standard error. + + Use as + [freq] = ft_freqdescriptives(cfg, freq) + [freq] = ft_freqdescriptives(cfg, freqmvar) + + The data in freq should be organised in a structure as obtained from + from the FT_FREQANALYSIS or FT_MVARANALYSIS function. The output structure is comparable + to the input structure and can be used in most functions that require + a freq input. + + The configuration options are + cfg.variance = 'yes' or 'no', estimate standard error in the standard way (default = 'no') + cfg.jackknife = 'yes' or 'no', estimate standard error by means of the jack-knife (default = 'no') + cfg.keeptrials = 'yes' or 'no', estimate single trial power (useful for fourier data) (default = 'no') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.frequency = [fmin fmax] or 'all', to specify a subset of frequencies (default = 'all') + cfg.latency = [tmin tmax] or 'all', to specify a subset of latencies (default = 'all') + + A variance estimate can only be computed if results from trials and/or + tapers have been kept. + + Descriptive statistics of bivariate metrics is not computed by this function anymore. To this end you + should use FT_CONNECTIVITYANALYSIS. + + 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_FREQANALYSIS, FT_FREQSTATISTICS, FT_FREQBASELINE, FT_CONNECTIVITYANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqdescriptives.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqgrandaverage` + +```{text} + FT_FREQGRANDAVERAGE computes the average powerspectrum or time-frequency spectrum + over multiple subjects + + Use as + [grandavg] = ft_freqgrandaverage(cfg, freq1, freq2, freq3...) + + The input data freq1..N are obtained from either FT_FREQANALYSIS with + keeptrials=no or from FT_FREQDESCRIPTIVES. The configuration structure + can contain + cfg.keepindividual = 'yes' or 'no' (default = 'no') + cfg.foilim = [fmin fmax] or 'all', to specify a subset of frequencies (default = 'all') + cfg.toilim = [tmin tmax] or 'all', to specify a subset of latencies (default = 'all') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.parameter = string or cell-array of strings indicating which + parameter(s) to average. default is set to + 'powspctrm', if it is present in the data. + + 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. For this particular function, the input should be + specified as a cell-array. + + See also FT_TIMELOCKGRANDAVERAGE, FT_FREQANALYSIS, FT_FREQDESCRIPTIVES, + FT_FREQBASELINE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqgrandaverage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqinterpolate` + +```{text} + FT_FREQINTERPOLATE interpolates frequencies by looking at neighbouring + values or simply replaces a piece in the spectrum by NaN. + + Use as + freq = ft_freqinterpolate(cfg, freq) + where freq is the output of FT_FREQANALYSIS or FT_FREQDESCRIPTIVES and the + configuration may contain + cfg.method = 'nan', 'linear' (default = 'nan') + cfg.foilim = Nx2 matrix with begin and end of each interval to be + interpolated (default = [49 51; 99 101; 149 151]) + + 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_FREQANALYSIS, FT_FREQDESCRIPTIVES, FT_FREQSIMULATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqinterpolate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqsimulation` + +```{text} + FT_FREQSIMULATION simulates channel-level time-series data . The data is built up + from different frequencies and can contain a signal in which the different + frequencies interact (i.e. cross-frequency coherent). Different methods are + possible to make data with specific properties. + + Use as + [data] = ft_freqsimulation(cfg) + which will return a raw data structure that resembles the output of + FT_PREPROCESSING. + + The configuration options can include + cfg.method = The methods are explained in more detail below, but they can be + 'superimposed' simply add the contribution of the different frequencies + 'broadband' create a single broadband signal component + 'phalow_amphigh' phase of low freq correlated with amplitude of high freq + 'amplow_amphigh' amplitude of low freq correlated with amplithude of high freq + 'phalow_freqhigh' phase of low freq correlated with frequency of high signal + 'asymmetric' single signal component with asymmetric positive/negative deflections + cfg.output = which channels should be in the output data, can be 'mixed' or 'all' (default = 'all') + cfg.randomseed = 'yes' or a number or vector with the seed value (default = 'yes') + + The number of trials and the time axes of the trials can be specified by + cfg.fsample = simulated sample frequency (default = 1200) + cfg.trllen = length of simulated trials in seconds (default = 1) + cfg.numtrl = number of simulated trials (default = 1) + cfg.baseline = number (default = 0) + or by + cfg.time = cell-array with one time axis per trial, which are for example obtained from an existing dataset + + For each of the methods default parameters are configured to generate + example data, including noise. To get full control over the generated + data you should explicitely set all parameters involved in the method + of your choise. The interpretation of the following signal components + depends on the specified method: + + cfg.s1.freq = frequency of signal 1 + cfg.s1.phase = phase (in rad) relative to cosine of signal 1 (default depends on method) + = number or 'random' + cfg.s1.ampl = amplitude of signal 1 + cfg.s2.freq = frequency of signal 2 + cfg.s2.phase = phase (in rad) relative to cosine of signal 1 (default depends on method) + = number or 'random' + cfg.s2.ampl = amplitude of signal 2 + cfg.s3.freq = frequency of signal 3 + cfg.s3.phase = phase (in rad) relative to cosine of signal 1 (default depends on method) + = number or 'random' + cfg.s3.ampl = amplitude of signal 3 + cfg.s4.freq = frequency of signal 4 + cfg.s4.phase = phase (in rad) relative to cosine of signal 1 (default depends on method) + = number or 'random' + cfg.s4.ampl = amplitude of signal 4 + + cfg.n1.ampl = root-mean-square amplitude of wide-band signal prior to filtering + cfg.n1.bpfreq = [Flow Fhigh] + cfg.n2.ampl = root-mean-square amplitude of wide-band signal prior to filtering + cfg.n2.bpfreq = [Flow Fhigh] + + cfg.asymmetry = amount of asymmetry (default = 0, which is none) + cfg.noise.ampl = amplitude of noise + + + In the method 'superimposed' the signal contains just the sum of the different frequency contributions: + s1: first frequency + s2: second frequency + s3: third frequency + and the output consists of the following channels: + 1st channel: mixed signal = s1 + s2 + s3 + noise + 2nd channel: s1 + 3rd channel: s2 + 4th channel: s3 + 5th channel: noise + + In the method 'broadband' the signal contains a the superposition of two + broadband signal components, which are created by bandpass filtering a + Gaussian noise signal: + n1: first broadband signal + n2: second broadband signal + and the output consists of the following channels: + 1st channel: mixed signal = n1 + n2 + noise + 2nd channel: n1 + 3rd channel: n2 + 4th channel: noise + + In the method 'phalow_amphigh' the signal is build up of 4 components; s1, s2, s3 and noise: + s1: amplitude modulation (AM), frequency of this signal should be lower than s2 + s2: second frequency, frequncy that becomes amplitude modulated + s3: DC shift of s1, should have frequency of 0 + and the output consists of the following channels: + 1st channel: mixed signal = (s1 + s3)*s2 + noise, + 2nd channel: s1 + 3rd channel: s2 + 4th channel: s3 + 5th channel: noise + + In the method 'amplow_amphigh' the signal is build up of 5 components; s1, s2, s3, s4 and noise. + s1: first frequency + s2: second frequency + s3: DC shift of s1 and s2, should have frequency of 0 + s4: amplitude modulation (AM), frequency of this signal should be lower than s1 and s2 + and the output consists of the following channels: + 1st channel: mixed signal = (s4 + s3)*s1 + (s4 + s3)*s2 + noise, + 2nd channel: s1 + 3rd channel: s2 + 4th channel: s3 + 5th channel: noise + 6th channel: s4 + 7th channel: mixed part 1: (s4 + s3)*s1 + 8th channel: mixed part 2: (s4 + s3)*s2 + + In the method 'phalow_freqhigh' a frequency modulated signal is created. + signal is build up of 3 components; s1, s2 and noise. + s1: represents the base signal that will be modulated + s2: signal that will be used for the frequency modulation + and the output consists of the following channels: + 1st channel: mixed signal = s1.ampl * cos(ins_pha) + noise + 2nd channel: s1 + 3rd channel: s2 + 4th channel: noise + 5th channel: inst_pha_base instantaneous phase of the high (=base) frequency signal s1 + 6th channel: inst_pha_mod low frequency phase modulation, this is equal to s2 + 7th channel: inst_pha instantaneous phase, i.e. inst_pha_base + inst_pha_mod + + In the method 'asymmetric' there is only one periodic signal, but that + signal is more peaked for the positive than for the negative deflections. + The average of the signal over time is zero. + s1: represents the frequency of the base signal + and the output consists of the following channels: + 1st channel: mixed signal = asymmetric signal + noise + 2nd channel: sine wave with base frequency and phase, i.e. s1 + 3rd channel: asymmetric signal + 4th channel: noise + + See also FT_FREQANALYSIS, FT_TIMELOCKSIMULATION, FT_DIPOLESIMULATION, + FT_CONNECTIVITYSIMULATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqsimulation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_freqstatistics` + +```{text} + FT_FREQSTATISTICS computes significance probabilities and/or critical + values of a parametric statistical test or a non-parametric permutation + test. + + Use as + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + where the input data is the result from FT_FREQANALYSIS, FT_FREQDESCRIPTIVES + or from FT_FREQGRANDAVERAGE. + + The configuration can contain the following options for data selection + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.latency = [begin end] in seconds or 'all' (default = 'all') + cfg.frequency = [begin end], can be 'all' (default = 'all') + cfg.avgoverchan = 'yes' or 'no' (default = 'no') + cfg.avgovertime = 'yes' or 'no' (default = 'no') + cfg.avgoverfreq = 'yes' or 'no' (default = 'no') + cfg.parameter = string (default = 'powspctrm') + + If you specify cfg.correctm='cluster', then the following is required + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS + + Furthermore, the configuration should contain + cfg.method = different methods for calculating the significance probability and/or critical value + 'montecarlo' get Monte-Carlo estimates of the significance probabilities and/or critical values from the permutation distribution, + 'analytic' get significance probabilities and/or critical values from the analytic reference distribution (typically, the sampling distribution under the null hypothesis), + 'stats' use a parametric test from the MATLAB statistics toolbox, + 'crossvalidate' use crossvalidation to compute predictive performance + + cfg.design = Nxnumobservations: design matrix (for examples/advice, please see the Fieldtrip wiki, + especially cluster-permutation tutorial and the 'walkthrough' design-matrix section) + + The other cfg options depend on the method that you select. You + should read the help of the respective subfunction FT_STATISTICS_XXX + for the corresponding configuration options and for a detailed + explanation of each method. + + 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_FREQANALYSIS, FT_FREQDESCRIPTIVES, FT_FREQGRANDAVERAGE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_freqstatistics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_geometryplot` + +```{text} + FT_GEOMETRYPLOT plots objects in 3D, such as sensors, headmodels, sourcemodels, + headshapes, meshes, etcetera. It provides an easy-to-use wrapper for the + corresponding FT_PLOT_XXX functions. + + Use as + ft_geometryplot(cfg) + where the cfg structure contains the geometrical objects that have to be plotted + cfg.elec = structure, see FT_READ_SENS + cfg.grad = structure, see FT_READ_SENS + cfg.opto = structure, see FT_READ_SENS + cfg.headshape = structure, see FT_READ_HEADSHAPE + cfg.headmodel = structure, see FT_PREPARE_HEADMODEL and FT_READ_HEADMODEL + cfg.sourcemodel = structure, see FT_PREPARE_SOURCEMODEL + cfg.dipole = structure, see FT_DIPOLEFITTING + cfg.mri = structure, see FT_READ_MRI + cfg.mesh = structure, see FT_PREPARE_MESH + cfg.axes = string, 'yes' or 'no' (default = 'no') + + Furthermore, there are a number of general options + cfg.unit = string, 'mm', 'cm', 'm' with the geometrical units (default depends on the data) + cfg.coordsys = string, with the coordinate system (default depends on the data) + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.figurename = string, title of the figure window + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO. The OpenGL renderer is required when using opacity (default = 'opengl') + cfg.title = string, title of the plot + + You can specify the style with which the objects are displayed using + cfg.elecstyle = cell-array or structure, see below + cfg.gradstyle = cell-array or structure, see below + cfg.optostyle = cell-array or structure, see below + cfg.headshapestyle = cell-array or structure, see below + cfg.headmodelstyle = cell-array or structure, see below + cfg.sourcemodelstyle = cell-array or structure, see below + cfg.dipolestyle = cell-array or structure, see below + cfg.mristyle = cell-array or structure, see below + cfg.meshstyle = cell-array or structure, see below + + For each of the xxxstyle options, you can specify a cell-array with key value pairs + similar as in FT_INTERACTIVEREALIGN. These options will be passed on to the + corresponding FT_PLOT_XXX function. You can also specify the options as a + structure. For example, the following two specifications are equivalent + cfg.headshapestyle = {'facecolor', 'skin', 'edgecolor', 'none'}; + and + cfg.headshapestyle.facecolor = 'skin'; + cfg.headshapestyle.edgecolor = 'none'; + + In the figure with graphical user interface you will be able to adjust most of the + settings that determine how the objects are displayed. + + See also PLOTTING, FT_SOURCEPLOT, FT_INTERACTIVEREALIGN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_geometryplot.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_getopt` + +```{text} + FT_GETOPT gets the value of a specified option from a configuration structure + or from a cell-array with key-value pairs. + + Use as + val = ft_getopt(s, key, default, emptymeaningful) + where the input values are + s = structure or cell-array + key = string + default = any valid MATLAB data type (optional, default = []) + emptymeaningful = boolean value (optional, default = false) + + If the key is present as field in the structure, or as key-value pair in the + cell-array, the corresponding value will be returned. + + If the key is not present, ft_getopt will return the default, or an empty array + when no default was specified. + + If the key is present but has an empty value, then the emptymeaningful flag + specifies whether the empty value or the default value should be returned. + If emptymeaningful==true, then the empty array will be returned. + If emptymeaningful==false, then the specified default will be returned. + + See also FT_SETOPT, FT_CHECKOPT, INPUTPARSER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_getopt.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_globalmeanfield` + +```{text} + FT_GLOBALMEANFIELD calculates global mean field amplitude or power of input data + + Use as + [gmf] = ft_globalmeanfield(cfg, data) + + The data should be organised in a structure as obtained from the + FT_TIMELOCKANALYSIS function. The configuration should be according to + FT_PREPROCESSING function. The configuration should be according to + + cfg.method = string, determines whether the amplitude or power should be calculated (see below, default is 'amplitude', can be 'power') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + + This function calculates the global mean field power, or amplitude, + as described in: + Lehmann D, Skrandies W. Reference-free identification of components of + checkerboard-evoked multichannel potential fields. Electroencephalogr Clin + Neurophysiol. 1980 Jun;48(6):609-21. PubMed PMID: 6155251. + + Please note that to calculate what is clasically referred to as Global + Mean Field Power, cfg.method must be 'amplitude'. The naming implies a + squared measure but this is not the case. + + 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_TIMELOCKANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_globalmeanfield.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_hash` + +```{text} + FT_HASH computes a MD5 hash from a MATLAB variable or structure + + It will first try a hashing algorithm implemented as a mex file. + If that fails, it falls back to a slower one that is based on Java. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_hash.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_hastoolbox` + +```{text} + FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally it will + try to determine the path to the toolbox and install it automatically. + + Use as + [status] = ft_hastoolbox(toolbox, autoadd, silent) + + autoadd = -1 means that it will check and give an error when not yet installed + autoadd = 0 means that it will check and give a warning when not yet installed + autoadd = 1 means that it will check and give an error if it cannot be added + autoadd = 2 means that it will check and give a warning if it cannot be added + autoadd = 3 means that it will check but remain silent if it cannot be added + + silent = 0 means that it will give some feedback about adding the toolbox + silent = 1 means that it will not give feedback + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_hastoolbox.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headcircumference` + +```{text} + FT_HEADCIRCUMFERENCE determines the head circumference from a triangulated mesh of + the scalp in the same way as it would be measured using a measuring tape for + fitting an EEG cap. + + Use as + circumference = ft_headcircumference(cfg, mesh) + where the input mesh corresponds to the output of FT_PREPARE_MESH. + + The configuration should contain + cfg.fiducial.nas = 1x3 vector with coordinates + cfg.fiducial.ini = 1x3 vector with coordinates + cfg.fiducial.lpa = 1x3 vector with coordinates + cfg.fiducial.rpa = 1x3 vector with coordinates + cfg.feedback = string, can be 'yes' or 'no' for detailed feedback (default = 'yes') + + See also FT_ELECTRODEPLACEMENT, FT_PREPARE_MESH, FT_VOLUMESEGMENT, FT_READ_HEADSHAPE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_headcircumference.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headcoordinates` + +```{text} + FT_HEADCOORDINATES returns the homogeneous coordinate transformation matrix + that converts the specified fiducials in any coordinate system (e.g. MRI) + into the rotated and translated headcoordinate system. + + Use as + [transform, coordsys] = ft_headcoordinates(fid1, fid2, fid3, coordsys) + or + [transform, coordsys] = ft_headcoordinates(fid1, fid2, fid3, fid4, coordsys) + + Depending on the desired coordinate system, the order of the fiducials is + interpreted as follows + + fid1 = nas + fid2 = lpa + fid3 = rpa + fid4 = extra point (optional) + + fid1 = ac + fid2 = pc + fid3 = midsagittal + fid4 = extra point (optional) + + fid1 = pt1 + fid2 = pt2 + fid3 = pt3 + fid4 = extra point (optional) + + fid1 = bregma + fid2 = lambda + fid3 = midsagittal + fid4 = extra point (optional) + + The fourth argument fid4 is optional and can be specified as an an extra point + which is assumed to have a positive Z-coordinate. It will be used to ensure correct + orientation of the Z-axis (ctf, 4d, bti, eeglab, yokogawa, neuromag, itab) or + X-axis (acpc, spm, mni, tal). The specification of this extra point may result in + the handedness of the transformation to be changed, but ensures consistency with + the handedness of the input coordinate system. + + The coordsys input argument is a string that determines how the location of the + origin and the direction of the axis is to be defined relative to the fiducials: + according to CTF conventions: coordsys = 'ctf' + according to 4D conventions: coordsys = '4d' or 'bti' + according to EEGLAB conventions: coordsys = 'eeglab' + according to NEUROMAG conventions: coordsys = 'itab' + according to ITAB conventions: coordsys = 'neuromag' + according to YOKOGAWA conventions: coordsys = 'yokogawa' + according to ASA conventions: coordsys = 'asa' + according to FTG conventions: coordsys = 'ftg' + according to ACPC conventions: coordsys = 'acpc' + according to SPM conventions: coordsys = 'spm' + according to MNI conventions: coordsys = 'mni' + according to Talairach conventions: coordsys = 'tal' + according to PAXINOS conventions: coordsys = 'paxinos' + If the coordsys input argument is not specified, it will default to 'ctf'. + + The CTF, 4D, YOKOGAWA and EEGLAB coordinate systems are defined as follows: + the origin is exactly between lpa and rpa + the X-axis goes towards nas + the Y-axis goes approximately towards lpa, orthogonal to X and in the plane spanned by the fiducials + the Z-axis goes approximately towards the vertex, orthogonal to X and Y + + The TALAIRACH, SPM and ACPC coordinate systems are defined as: + the origin corresponds with the anterior commissure + the Y-axis is along the line from the posterior commissure to the anterior commissure + the Z-axis is towards the vertex, in between the hemispheres + the X-axis is orthogonal to the midsagittal-plane, positive to the right + + The NEUROMAG and ITAB coordinate systems are defined as follows: + the X-axis is from the origin towards the RPA point (exactly through) + the Y-axis is from the origin towards the nasion (exactly through) + the Z-axis is from the origin upwards orthogonal to the XY-plane + the origin is the intersection of the line through LPA and RPA and a line orthogonal to L passing through the nasion + + The ASA coordinate system is defined as follows: + the origin is at the orthogonal intersection of the line from rpa-lpa and the line through nas + the X-axis goes towards nas + the Y-axis goes through rpa and lpa + the Z-axis goes approximately towards the vertex, orthogonal to X and Y + + The FTG coordinate system is defined as: + the origin corresponds with pt1 + the x-axis is along the line from pt1 to pt2 + the z-axis is orthogonal to the plane spanned by pt1, pt2 and pt3 + + The PAXINOS coordinate system is defined as: + the origin is at bregma + the x-axis extends along the Medial-Lateral direction, with positive towards the right + the y-axis points from dorsal to ventral, i.e. from inferior to superior + the z-axis passes through bregma and lambda and points from cranial to caudal, i.e. from anterior to posterior + + See also FT_ELECTRODEREALIGN, FT_VOLUMEREALIGN, FT_INTERACTIVEREALIGN, FT_AFFINECOORDINATES, COORDSYS2LABEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_headcoordinates.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_asa` + +```{text} + FT_HEADMODEL_ASA reads a volume conduction model from an ASA *.vol + file + + ASA is commercial software (http://www.ant-neuro.com) that supports + among others the boundary element method (BEM) for EEG. This function + allows you to read an EEG BEM volume conduction model from an ASA + format file (*.vol) and use that for leadfield computations in + MATLAB. Constructing the geometry of the head model from an anatomical + MRI and the computation of the BEM system are both handled by ASA. + + Use as + headmodel = ft_headmodel_asa(filename) + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_asa.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_bemcp` + +```{text} + FT_HEADMODEL_BEMCP creates a volume conduction model of the head + using the boundary element method (BEM) for EEG. This function + takes as input the triangulated surfaces that describe the boundaries + and returns as output a volume conduction model which can be used + to compute leadfields. + + The implementation of this function is based on Christophe Phillips' + MATLAB code, hence the name "bemcp". + + Use as + headmodel = ft_headmodel_bemcp(mesh, ...) + + Optional input arguments should be specified in key-value pairs and can + include + conductivity = vector, conductivity of each compartment + checkmesh = 'yes' or 'no' + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_bemcp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_concentricspheres` + +```{text} + FT_HEADMODEL_CONCENTRICSPHERES creates a volume conduction model + of the head based on three or four concentric spheres. For a 3-sphere + model the spheres represent the skin surface, the outside of the + skull and the inside of the skull For a 4-sphere model, the surfaces + describe the skin, the outside-skull, the inside-skull and the inside of the + cerebro-spinal fluid (CSF) boundaries. + + The innermost surface is sometimes also referred to as the brain + surface, i.e. as the outside of the brain volume. + + This function takes as input a single headshape described with + points and fits the spheres to this surface. If you have a set of + points describing each surface, then this function fits the spheres + to all individual surfaces. + + Use as + headmodel = ft_headmodel_concentricspheres(mesh, ...) + + Optional input arguments should be specified in key-value pairs and can include + conductivity = vector with the conductivity of each compartment + fitind = vector with indices of the surfaces to use in fitting the center of the spheres + order = number of iterations in series expansion (default = 60) + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_concentricspheres.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_dipoli` + +```{text} + FT_HEADMODEL_DIPOLI creates a volume conduction model of the head + using the boundary element method (BEM) for EEG. This function takes + as input the triangulated surfaces that describe the boundaries and + returns as output a volume conduction model which can be used to + compute leadfields. + + This implements + Oostendorp TF, van Oosterom A. "Source parameter estimation in + inhomogeneous volume conductors of arbitrary shape." IEEE Trans + Biomed Eng. 1989 Mar;36(3):382-91. + + The implementation of this function uses an external command-line + executable with the name "dipoli" which is provided by Thom Oostendorp. + + Use as + headmodel = ft_headmodel_dipoli(mesh, ...) + + The mesh is given as a boundary or a struct-array of boundaries (surfaces) + + Optional input arguments should be specified in key-value pairs and can + include + isolatedsource = string, 'yes' or 'no' + conductivity = vector, conductivity of each compartment + tempdir = string, allows you to specify the path for the tempory files (default is automatic) + tempname = string, allows you to specify the full tempory name including path (default is automatic) + checkmesh = 'yes' or 'no' + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_dipoli.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_duneuro` + +```{text} + FT_HEADMODEL_DUNEURO creates a volume conduction model of the head + using the finite element method (FEM) for EEG and MEG. Different source models + are implemented, including the St. Venant, the subtraction and partial + integration model. This function takes as input a mesh with tetrahedral + or hexahedral elements and corresponding conductivities and returns + as output a volume conduction model which can be used to compute EEG/MEG + leadfields. + + Use as + headmodel = ft_headmodel_duneuro(mesh,'conductivity', conductivities, ...) + headmodel = ft_headmodel_duneuro(mesh,'grid_filename', grid_filename, 'tensors_filename', tensors_filename, ...) + + Required input arguments should be specified in key-value pairs and have + to include either + grid_filename = string, filename for grid in "msh" fileformat (see here: https://gmsh.info/doc/texinfo/gmsh.html#File-formats) + tensors_filename= string, filename for conductivities, txt file with conductivity values + + or + conductivity = vector, conductivity values for tissues + + Optional input arguments are passed with + duneuro_settings = (optional) struct, which can contain the following fields + + type = string, 'fitted' (default) + solver_type = string, 'cg' (default) + electrodes = string, 'closest_subentity_center' (default) + subentities = string, e.g. '1 2 3' (default) or '3' + forward = string, 'venant' (default), 'partial_integration' + intorderadd = string, e.g. '2' (default) + intorderadd_lb = string, e.g. '2' (default) + initialization = string, e.g. 'closest_vertex' (default) + numberOfMoments = string, e.g. '3' (default) + referenceLength = string, e.g. '20' (default) + relaxationFactor= string, e.g. '1e-6' (default) + restrict = string, e.g. 'true' (default) + weightingExponent= string, e.g. '1' (default) + post_process = string, e.g. 'true' (default) + subtract_mean = string, e.g. 'true' (default) + reduction = string, e.g. '1e-10' (default) + intorderadd_meg = integer, e.g.'0' (default) + mixedMoments = logical, e.g. 'true' (default) + meg_type = string, e.g. 'physical' (default) + meg_eneablecache= logical, e.g. 'false (default) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_duneuro.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_fns` + +```{text} + FT_HEADMODEL_FNS creates the volume conduction structure to be used + in the FNS forward solver. + + Use as + headmodel = ft_headmodel_fns(seg, ...) + + Optional input arguments should be specified in key-value pairs and + can include + tissuecond = matrix C [9XN tissue types]; where N is the number of + tissues and a 3x3 tensor conductivity matrix is stored + in each column. + tissue = see fns_contable_write + tissueval = match tissues of segmentation input + transform = 4x4 transformation matrix (default eye(4)) + sens = sensor information (for which ft_datatype(sens,'sens')==1) + deepelec = used in the case of deep voxel solution + tolerance = scalar (default 1e-8) + + Standard default values for conductivity matrix C are derived from + Saleheen HI, Ng KT. New finite difference formulations for general + inhomogeneous anisotropic bioelectric problems. IEEE Trans Biomed Eng. + 1997 + + Additional documentation available at: + http://hunghienvn.nmsu.edu/wiki/index.php/FNS + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_fns.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_halfspace` + +```{text} + FT_HEADMODEL_HALFSPACE creates an EEG volume conduction model that + is described with an infinite conductive halfspace. You can think + of this as a plane with on one side a infinite mass of conductive + material (e.g. water) and on the other side non-conductive material + (e.g. air). + + Use as + headmodel = ft_headmodel_halfspace(mesh, Pc, ...) + where + mesh.pos = Nx3 vector specifying N points through which a plane is fitted + Pc = 1x3 vector specifying the spatial position of a single point that + is lying in the conductive halfspace + + Additional optional arguments should be specified as key-value pairs and can include + 'sourcemodel' = string, 'monopole' or 'dipole' (default = 'dipole') + 'conductivity' = number, conductivity value of the conductive halfspace (default = 1) + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_halfspace.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_infinite` + +```{text} + FT_HEADMODEL_INFINITE returns an infinitely large homogenous + volume conduction model. For EEG the volume conductor can be used + to compute the leadfield of electric current dipoles, for MEG it + can be used for computing the leadfield of magnetic dipoles. + + Use as + headmodel = ft_headmodel_infinite; + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_infinite.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_interpolate` + +```{text} + FT_HEADMODEL_INTERPOLATE describes a volume conduction model of the head in which + subsequent leadfield computations can be performed using a simple interpolation + scheme. + + Use as + headmodel = ft_headmodel_interpolate(filename, sens, leadfield) + or + headmodel = ft_headmodel_interpolate(filename, sens, leadfield) + + The input parameters are the filename to which the model will be written, + the electrode definition (see ft_DATATYPE_SENS). The third input argument + is either a pre-computed leadfield structure from FT_PREPARE_LEADFIELD + or a the output of a previous call to FT_HEADMODEL_INTERPOLATE. + + The output volume conduction model is stored on disk in a MATLAB file together with a + number of NIFTi files. The mat file contains a structure with the following fields + headmodel.sens = structure, electrode sensor description, see FT_DATATYE_SENS + headmodel.filename = cell-array with NIFTI filenames, one file per channel + and contains + headmodel.dim = [Nx Ny Nz] vector with the number of grid points along each dimension + headmodel.transform = 4x4 homogenous transformation matrix + headmodel.unit = string with the geometrical units of the positions, e.g. 'cm' or 'mm' + to describe the source positions. + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_interpolate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_localspheres` + +```{text} + FT_HEADMODEL_LOCALSPHERES constructs a MEG volume conduction model in + with a local sphere fitted to the head or brain surface for each separate + channel + + This implements + Huang MX, Mosher JC, Leahy RM. "A sensor-weighted overlapping-sphere + head model and exhaustive head model comparison for MEG." Phys Med + Biol. 1999 Feb;44(2):423-40 + + Use as + headmodel = ft_headmodel_localspheres(mesh, grad, ...) + + Optional arguments should be specified in key-value pairs and can include + radius = number, radius of sphere within which headshape points will + be included for the fitting algorithm + maxradius = number, if for a given sensor the fitted radius exceeds + this value, the radius and origin will be replaced with the + single sphere fit + baseline = number + feedback = boolean, true or false + + See also FT_PREPARE_HEADMODEL, FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_localspheres.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_openmeeg` + +```{text} + FT_HEADMODEL_OPENMEEG creates a volume conduction model of the head using the + boundary element method (BEM). This function takes as input the triangulated + surfaces that describe the boundaries and returns as output a volume conduction + model which can be used to compute leadfields. + + This function implements + Gramfort et al. OpenMEEG: opensource software for quasistatic + bioelectromagnetics. Biomedical engineering online (2010) vol. 9 (1) pp. 45 + http://www.biomedical-engineering-online.com/content/9/1/45 + doi:10.1186/1475-925X-9-45 + and + Kybic et al. Generalized head models for MEG/EEG: boundary element method + beyond nested volumes. Phys. Med. Biol. (2006) vol. 51 pp. 1333-1346 + doi:10.1088/0031-9155/51/5/021 + + This link with FieldTrip is derived from the OpenMEEG project with contributions + from Daniel Wong and Sarang Dalal, and uses external command-line executables. + See http://openmeeg.github.io/ + + Use as + headmodel = ft_headmodel_openmeeg(bnd, ...) + + Optional input arguments should be specified in key-value pairs and can + include + conductivity = vector, conductivity of each compartment + tissue = cell-array with the tissue labels for each compartment + checkmesh = 'yes' or 'no' + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_openmeeg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_simbio` + +```{text} + FT_HEADMODEL_SIMBIO creates a volume conduction model of the head + using the finite element method (FEM) for EEG. This function takes + as input a volumetric mesh (hexahedral or tetrahedral) and + returns as output a volume conduction model which can be used to + compute leadfields. + + This implements + ... + + Use as + headmodel = ft_headmodel_simbio(mesh,'conductivity', conductivities, ...) + + The mesh is given as a volumetric mesh, using ft_datatype_parcellation + mesh.pos = vertex positions + mesh.tet/mesh.hex = list of volume elements + mesh.tissue = tissue assignment for elements + mesh.tissuelabel = labels correspondig to tissues + + Required input arguments should be specified in key-value pairs and have + to include + conductivity = vector containing tissue conductivities using ordered + corresponding to mesh.tissuelabel + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + To run this on Windows the following packages are necessary: + + Microsoft Visual C++ 2008 Redistributable + + Intel Visual Fortran Redistributables + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_simbio.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_singleshell` + +```{text} + FT_HEADMODEL_SINGLESHELL creates a volume conduction model of the + head for MEG based on a realistic shaped surface of the inside of + the skull. + + The method implemented in this function allows for a simple and + fast method for the MEG forward calculation for one shell of arbitrary + shape, based on a correction of the lead field for a spherical + volume conductor by a superposition of basis functions, gradients + of harmonic functions constructed from spherical harmonics. + + This function implements + G. Nolte, "The magnetic lead field theorem in the quasi-static + approximation and its use for magnetoencephalography forward calculation + in realistic volume conductors", Phys Med Biol. 2003 Nov 21;48(22):3637-52. + + Use as + headmodel = ft_headmodel_singleshell(mesh, ...) + + Optional input arguments should be specified in key-value pairs and can include + order = number of iterations in series expansion (default = 10) + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_singleshell.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_singlesphere` + +```{text} + FT_HEADMODEL_SINGLESPHERE creates a volume conduction model of the + head by fitting a spherical model to a set of points that describe + the head surface. + + For MEG this implements Cuffin BN, Cohen D. "Magnetic fields of a dipole in + special volume conductor shapes" IEEE Trans Biomed Eng. 1977 Jul;24(4):372-81. + + For EEG this implements R. Kavanagh, T. M. Darccey, D. Lehmann, and D. H. Fender. + Evaluation of methods for three-dimensional localization of electric sources in the + human brain. IEEE Trans Biomed Eng, 25:421-429, 1978. + + Use as + headmodel = ft_headmodel_singlesphere(mesh, ...) + + Optional arguments should be specified in key-value pairs and can include + conductivity = number, conductivity of the sphere + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_singlesphere.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodel_slab` + +```{text} + FT_HEADMODEL_SLAB creates an EEG volume conduction model that + is described with an infinite conductive slab. You can think + of this as two parallel planes containing a mass of conductive + material (e.g. water) and externally to them a non-conductive material + (e.g. air). + + Use as + headmodel = ft_headmodel_slab(mesh1, mesh2, Pc, varargin) + where + mesh1.pos = Nx3 vector specifying N points through which the 'upper' plane is fitted + mesh2.pos = Nx3 vector specifying N points through which the 'lower' plane is fitted + Pc = 1x3 vector specifying the spatial position of a point lying in the conductive slab + (this determines the plane's normal's direction) + + Optional arguments should be specified in key-value pairs and can include + 'sourcemodel' = 'monopole' + 'conductivity' = number , conductivity value of the conductive halfspace (default = 1) + + See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodel_slab.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmodeltype` + +```{text} + FT_HEADMODELTYPE determines the type of volume conduction model of the head + + Use as + [type] = ft_headmodeltype(headmodel) + to get a string describing the type, or + [flag] = ft_headmodeltype(headmodel, desired) + to get a boolean value. + + For EEG the following volume conduction models are recognized + singlesphere analytical single sphere model + concentricspheres analytical concentric sphere model with up to 4 spheres + halfspace infinite homogenous medium on one side, vacuum on the other + openmeeg boundary element method, based on the OpenMEEG software + bemcp boundary element method, based on the implementation from Christophe Phillips + dipoli boundary element method, based on the implementation from Thom Oostendorp + asa boundary element method, based on the (commercial) ASA software + simbio finite element method, based on the SimBio software + fns finite difference method, based on the FNS software + interpolate interpolate the potential based on pre-computed leadfields + + and for MEG the following volume conduction models are recognized + singlesphere analytical single sphere model + localspheres local spheres model for MEG, one sphere per channel + singleshell realisically shaped single shell approximation, based on the implementation from Guido Nolte + infinite magnetic dipole in an infinite vacuum + interpolate interpolate the potential based on pre-computed leadfields + + See also FT_COMPUTE_LEADFIELD, FT_READ_HEADMODEL, FT_HEADMODEL_BEMCP, + FT_HEADMODEL_ASA, FT_HEADMODEL_DIPOLI, FT_HEADMODEL_SIMBIO, + FT_HEADMODEL_FNS, FT_HEADMODEL_HALFSPACE, FT_HEADMODEL_INFINITE, + FT_HEADMODEL_OPENMEEG, FT_HEADMODEL_SINGLESPHERE, + FT_HEADMODEL_CONCENTRICSPHERES, FT_HEADMODEL_LOCALSPHERES, + FT_HEADMODEL_SINGLESHELL, FT_HEADMODEL_INTERPOLATE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_headmodeltype.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_headmovement` + +```{text} + FT_HEADMOVEMENT outputs a raw data structure, or cell-array of data structures + reflecting the variability in the subject's head poisition relative to the + MEG sensors, based on continuous head position information. Current support is + only for CTF-data. The output timeseries contain the raw HLC data, and a + parametrization of the head movement in terms of translation and + rotations in 3D space. The grad structure(s) have head position information + incorporated in the coils' position/orientation and/or in the tra + matrix, depending on the method used. + + Use as + data = ft_headmovement(cfg) + + where the configuration should contain + cfg.dataset = string with the filename + cfg.method = string, 'updatesens' (default), 'cluster', 'avgoverrpt', + 'pertrial_cluster', 'pertrial' (default = 'updatesens') + + optional arguments are + cfg.trl = empty (default), or Nx3 matrix with the trial + definition (see FT_DEFINETRIAL). When specified as empty, + the whole recording is used. + cfg.numclusters = number of segments with constant headposition in + which to split the data (default = 10). This argument + is only used for the methods that use clustering ('updatesens', + 'cluster', 'pertrial_cluster'). + + If cfg.method = 'updatesens', the grad in the single output structure has + a specification of the coils expanded as per the centroids of the position + clusters (obtained by kmeans clustering of the HLC time series). The balancing matrix + is a weighted concatenation of the original tra-matrix. This method requires + cfg.numclusters to be specified + + If cfg.method = 'avgoverrpt', the grad in the single output structure has + a specification of the coils according to the average head position + across the specified samples. + + If cfg.method = 'cluster', the cell-array of output structures represent + the epochs in which the head was considered to be positioned close to the + corresponding kmeans-cluster's centroid. The corresponding grad-structure + is specified according to this cluster's centroid. This method requires + cfg.numclusters to be specified. + + If cfg.method = 'pertrial', the cell-array of output structures contains + single trials, each trial with a trial-specific grad structure. Note that + this is extremely memory inefficient with large numbers of trials, and + probably an overkill. + + If cfg.method = 'pertrial_clusters', the cell-array of output structures + contains sets of trials where the trial-specific head position was + considered to be positioned close to the corresponding kmeans-cluster's + centroid. The corresponding grad-structure is specified accordin to the + cluster's centroid. This method requires cfg.numclusters to be specified. + + The updatesens method and related methods are described by Stolk et al., Online and + offline tools for head movement compensation in MEG. NeuroImage, 2012. + + See also FT_REGRESSCONFOUND, FT_REALTIME_HEADLOCALIZER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_headmovement.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_heartrate` + +```{text} + FT_HEARTRATE estimates the heart rate from a continuous PPG or ECG channel. It + returns a new data structure with a continuous representation of the heartrate in + beats per minute, the heart period (i.e., the RR interval) in seconds per interval, + the heartbeat phase and the moment of the heartbeat onsets. + + Use as + dataout = ft_heartrate(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING and the + output is a similar structure with the same trials and time-charactersitics, but + with new channels describing the heart rate parameters. + + The configuration structure has the following general options + cfg.channel = selected channel for processing, see FT_CHANNELSELECTION + cfg.feedback = 'yes' or 'no' + cfg.method = string representing the method for heart beat detection + 'findpeaks' filtering and normalization, followed by FINDPEAKS (default) + 'pantompkin' implementation of the Pan-Tompkin algorithm for ECG beat detection + + For the 'findpeaks' method the following additional options can be specified + cfg.envelopewindow = scalar, time in seconds (default = 10) + cfg.peakseparation = scalar, time in seconds + cfg.threshold = scalar, usually between 0 and 1 (default = 0.4), 'MinPeakHeight' parameter for findpeaks function + cfg.mindistance = scalar, time in seconds for the minimal distance between consecutive peaks (default = 0), + 'MinPeakDistance' for findpeaks functions (after conversion from seconds into samples) + cfg.flipsignal = 'yes' or 'no', whether to flip the polarity of the signal (default is automatic) + and the data can be preprocessed on the fly using + cfg.preproc.bpfilter = 'yes' or 'no' + cfg.preproc.bpfreq = [low high], filter frequency in Hz + This implementation performs some filtering and amplitude normalization, followed + by the FINDPEAKS function. It works both for ECG as for PPG signals. + + For the 'pantompkin` method there are no additional options. This implements + - J Pan, W J Tompkins, "A Real-Time QRS Detection Algorithm", IEEE Trans Biomed Eng, 1985. https://doi.org/10.1109/tbme.1985.325532 + - H Sedghamiz, "Matlab Implementation of Pan Tompkins ECG QRS detector". https://doi.org/10.13140/RG.2.2.14202.59841 + + You can correct ectopic beats using the following options + cfg.ectopicbeatcorrect = 'yes' or 'no', replace a single ectopic beat (default = 'no') + cfg.ectopicbeatthreshold = fractional number as percentage (default = 0.2 + + An ectopic beat is a premature ventricual contraction, causing a very short-lived + increase in the variability in the rate. This can be corrected by replacing it with + a beat that falls exactly in between its neighbouring beats. A beat is detected as + ectopic if the RR-interval of a beat is 20% (default) smaller than the previous + beat-to-beat interval and is followed by an interval that is 20% (default) larger + (i.e. refractory period). The default threshold of 0.2 can be modified with + cfg.ectopicbeatthreshold. + + See also FT_ELECTRODERMALACTIVITY, FT_HEADMOVEMENT, FT_REGRESSCONFOUND + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_heartrate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_info` + +```{text} + FT_INFO prints an info message on screen, depending on the verbosity + settings of the calling high-level FieldTrip function. + + Use as + ft_info(...) + with arguments similar to fprintf, or + ft_info(msgId, ...) + with arguments similar to warning. + + You can switch of all messages using + ft_info off + or for specific ones using + ft_info off msgId + + To switch them back on, you would use + ft_info on + or for specific ones using + ft_info on msgId + + Messages are only printed once per timeout period using + ft_info timeout 60 + ft_info once + or for specific ones using + ft_info once msgId + + You can see the most recent messages and identifier using + ft_info last + + You can query the current on/off/once state for all messages using + ft_info query + + See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inside_headmodel` + +```{text} + FT_INSIDE_HEADMODEL locates dipole locations inside/outside the source + compartment of a volume conductor model. + + Use as + [inside] = ft_inside_headmodel(dippos, headmodel, ...) + + The input should be + dippos = Nx3 matrix with dipole positions + headmodel = structure with volume conductor model + and the output is + inside = boolean vector indicating for each dipole wether it is inside the source compartment + + Additional optional input arguments should be given in key value pairs and can include + inwardshift = number + grad = structure with gradiometer information, used for localspheres + headshape = structure with headshape, used for old CTF localspheres strategy + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_inside_headmodel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_interactiverealign` + +```{text} + FT_INTERACTIVEREALIGN allows the user to interactively translate, rotate and scale an + individual geometrical object to a template geometrical object. It can for example be used + to align EEG electrodes to a model of the scalp surface. + + Use as + [cfg] = ft_interactiverealign(cfg) + + The configuration structure should contain the individuals geometrical object that + has to be realigned + cfg.individual.elec = structure, see FT_READ_SENS + cfg.individual.grad = structure, see FT_READ_SENS + cfg.individual.opto = structure, see FT_READ_SENS + cfg.individual.headmodel = structure, see FT_PREPARE_HEADMODEL + cfg.individual.headshape = structure, see FT_READ_HEADSHAPE + cfg.individual.mri = structure, see FT_READ_MRI + cfg.individual.mesh = structure, see FT_PREPARE_MESH + You can specify the style with which the objects are displayed using + cfg.individual.headmodelstyle = 'vertex', 'edge', 'surface' or 'both' (default = 'edge') + cfg.individual.headshapestyle = 'vertex', 'edge', 'surface' or 'both' (default = 'vertex') + + The configuration structure should also contain the geometrical object of a + template that serves as target + cfg.template.axes = string, 'yes' or 'no' (default = 'no') + cfg.template.elec = structure, see FT_READ_SENS + cfg.template.grad = structure, see FT_READ_SENS + cfg.template.opto = structure, see FT_READ_SENS + cfg.template.headmodel = structure, see FT_PREPARE_HEADMODEL + cfg.template.headshape = structure, see FT_READ_HEADSHAPE + cfg.template.mri = structure, see FT_READ_MRI + cfg.template.mesh = structure, see FT_PREPARE_MESH + You can specify the style with which the objects are displayed using + cfg.template.headmodelstyle = 'vertex', 'edge', 'surface' or 'both' (default = 'edge') + cfg.template.headshapestyle = 'vertex', 'edge', 'surface' or 'both' (default = 'vertex') + + You can specify one or multiple individual objects which will all be realigned and + one or multiple template objects. + + See also FT_VOLUMEREALIGN, FT_ELECTRODEREALIGN, FT_DETERMINE_COORDSYS, + FT_READ_SENS, FT_READ_HEADMODEL, FT_READ_HEADSHAPE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_interactiverealign.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_interpolatenan` + +```{text} + FT_INTERPOLATENAN interpolates time series that contains segments of nans obtained + by replacing artifactual data with nans using, for example, FT_REJECTARTIFACT, or + by redefining trials with FT_REDEFINETRIAL resulting in trials with gaps. + + Use as + outdata = ft_interpolatenan(cfg, indata) + where cfg is a configuration structure and the input data is obtained from FT_PREPROCESSING. + + The configuration should contain + cfg.method = string, interpolation method, see INTERP1 (default = 'linear') + cfg.prewindow = value, length of data prior to interpolation window, in seconds (default = 1) + cfg.postwindow = value, length of data after interpolation window, in seconds (default = 1) + cfg.feedback = string, 'no', 'text', 'textbar', 'gui' (default = 'text') + + This function only interpolates over time, not over space. If you want to + interpolate using spatial information, e.g. using neighbouring channels, you should + use FT_CHANNELREPAIR. + + 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_REJECTARTIFACT, FT_REDEFINETRIAL, FT_CHANNELREPAIR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_interpolatenan.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_dics` + +```{text} + FT_INVERSE_DICS scans on pre-defined dipole locations with a single dipole + and returns the beamformer spatial filter output for a dipole on every + location. + + Use as + [estimate] = ft_inverse_dics(sourcemodel, sens, headmodel, dat, cov, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + cov is the data covariance or cross-spectral density matrix + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'Pr' = power of the external reference channel + 'Cr' = cross spectral density between all data channels and the external reference channel + 'refdip' = location of dipole with which coherence is computed + 'powmethod' = can be 'trace' or 'lambda1' + 'feedback' = can be 'none', 'gui', 'dial', 'textbar', 'text', 'textcr', 'textnl' (default = 'text') + 'fixedori' = use fixed or free orientation, can be 'yes' or 'no' + 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no' + 'realfilter' = construct a real-valued filter, can be 'yes' or 'no' + 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no' + 'keepleadfield' = remember the forward computation, can be 'yes' or 'no' + 'keepcsd' = remember the estimated cross-spectral density, can be 'yes' or 'no' + 'weightnorm' = normalize the beamformer weights, can be 'no', 'unitnoisegain', 'arraygain', or 'nai' + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + These options influence the mathematical inversion of the cross-spectral density matrix + 'lambda' = regularisation parameter + 'kappa' = parameter for covariance matrix inversion + 'tol' = parameter for covariance matrix inversion + + If the dipole definition only specifies the dipole location, a rotating + dipole (regional source) is assumed on each location. If a dipole moment + is specified, its orientation will be used and only the strength will + be fitted to the data. + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_dics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_dipolefit` + +```{text} + FT_INVERSE_DIPOLEFIT performs an equivalent current dipole fit with a single + or a small number of dipoles to explain an EEG or MEG scalp topography. + + Use as + [estimate] = ft_inverse_dipolefit(sourcemodel, sens, headmodel, dat, ...) + where + sourcemodel is the input source model with a single or a few dipoles + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'display' = Level of display [ off | iter | notify | final ] + 'optimfun' = Function to use [fminsearch | fminunc ] + 'maxiter' = Maximum number of function evaluations allowed [ positive integer ] + 'constr' = Structure with constraints + 'metric' = Error measure to be minimised [ rv | var | abs ] + 'checkinside' = Boolean flag to check whether dipole is inside source compartment [ 0 | 1 ] + 'mleweight' = weight matrix for maximum likelihood estimation, e.g. inverse noise covariance + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + The constraints on the source model are specified in a structure + constr.symmetry = boolean, dipole positions are symmetrically coupled to each other + constr.fixedori = boolean, keep dipole orientation fixed over whole data window + constr.rigidbody = boolean, keep relative position of multiple dipoles fixed + constr.mirror = vector, used for symmetric dipole models + constr.reduce = vector, used for symmetric dipole models + constr.expand = vector, used for symmetric dipole models + constr.sequential = boolean, fit different dipoles to sequential slices of the data + + The maximum likelihood estimation implements + - Lutkenhoner B. "Dipole source localization by means of maximum likelihood + estimation I. Theory and simulations" Electroencephalogr Clin Neurophysiol. 1998 + Apr;106(4):314-21. + + See also FT_DIPOLEFITTING, FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_dipolefit.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_eloreta` + +```{text} + FT_INVERSE_ELORETA estimates the source activity using eLORETA + + Use as + [estimate] = ft_inverse_eloreta(sourcemodel, sens, headmodel, dat, cov, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + cov is the data covariance or cross-spectral density matrix + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'keepfilter' = remember the spatial filter, can be 'yes' or 'no' + 'keepleadfield' = remember the forward computation, can be 'yes' or 'no' + 'keepmom' = remember the dipole moment, can be 'yes' or 'no' + 'lambda' = scalar, regularisation parameter (default = 0.05) + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + If the dipole definition only specifies the dipole location, a rotating dipole + (regional source) is assumed on each location. If a dipole moment is specified, its + orientation will be used and only the strength will be fitted to the data. + + This implements: + - R.D. Pascual-Marqui; Discrete, 3D distributed, linear imaging methods of electric + neuronal activity. Part 1: exact, zero error localization. arXiv:0710.3341 + 2007-October-17, http://arxiv.org/pdf/0710.3341 + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_eloreta.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_harmony` + +```{text} + FT_INVERSE_HARMONY computes a linear estimate of the current in a distributed + source model using a mesh harmonic based low-pass filter. + + Use as + [estimate] = ft_inverse_harmony(sourcemodel, sens, headmodel, dat, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'noisecov' = Nchan x Nchan matrix with noise covariance + 'noiselambda' = scalar value, regularisation parameter for the noise covariance matrix (default=0) + 'filter_order' = scalar, order of the mesh Butterwirth filter + 'filter_bs' = scalar, stop-band of the mesh Butterworth filter + 'number_harmonics' = Integer, number of mesh harmonics used (can be empty, the default will then be identity) + 'lambda' = scalar, regularisation parameter (can be empty, it will then be estimated from snr) + 'snr' = scalar, signal to noise ratio + 'scalesourcecov' = 'no' or 'yes', scale the source covariance matrix R such that trace(leadfield*R*leadfield')/trace(C)=1 + 'connected_components' = number of connected components of the source mesh (1 or 2) + 'prewhiten' = 'no' or 'yes', prewhiten the leadfield matrix with the noise covariance matrix C + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + This implements + - Petrov Y (2012) Harmony: EEG/MEG Linear Inverse Source Reconstruction in the + Anatomical Basis of Spherical Harmonics. PLoS ONE 7(10): e44439. + doi:10.1371/journal.pone.0044439 + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_harmony.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_lcmv` + +```{text} + FT_INVERSE_LCMV scans on pre-defined dipole locations with a single dipole + and returns the linear constrained minimum variance beamformer spatial filter + output for a dipole on every location. + + Use as + [estimate] = ft_inverse_lcmv(sourcemodel, sens, headmodel, dat, cov, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + cov is the data covariance or cross-spectral density matrix + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'powmethod' = can be 'trace' or 'lambda1' + 'feedback' = can be 'none', 'gui', 'dial', 'textbar', 'text', 'textcr', 'textnl' (default = 'text') + 'fixedori' = use fixed or free orientation, can be 'yes' or 'no' + 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no' + 'projectmom' = project the dipole moment timecourse on the direction of maximal power, can be 'yes' or 'no' + 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no' + 'keepleadfield' = remember the forward computation, can be 'yes' or 'no' + 'keepmom' = remember the estimated dipole moment timeseries, can be 'yes' or 'no' + 'keepcov' = remember the estimated dipole covariance, can be 'yes' or 'no' + 'kurtosis' = compute the kurtosis of the dipole timeseries, can be 'yes' or 'no' + 'weightnorm' = normalize the beamformer weights, can be 'no', 'unitnoisegain', 'arraygain' or 'nai' + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + These options influence the mathematical inversion of the covariance matrix + 'lambda' = regularisation parameter + 'kappa' = parameter for covariance matrix inversion + 'tol' = parameter for covariance matrix inversion + + If the dipole definition only specifies the dipole location, a rotating + dipole (regional source) is assumed on each location. If a dipole moment + is specified, its orientation will be used and only the strength will + be fitted to the data. + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_lcmv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_mne` + +```{text} + FT_INVERSE_MNE computes a minimum norm linear estimate of the current in a + distributed source model. + + Use as + [estimate] = ft_inverse_mne(sourcemodel, sens, headmodel, dat, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'noisecov' = Nchan x Nchan matrix with noise covariance + 'noiselambda' = scalar value, regularisation parameter for the noise covariance matrix (default = 0) + 'sourcecov' = Nsource x Nsource matrix with source covariance (can be empty, the default will then be identity) + 'lambda' = scalar, regularisation parameter (can be empty, it will then be estimated from snr) + 'snr' = scalar, signal to noise ratio + 'keepfilter' = 'no' or 'yes', keep the spatial filter in the output + 'prewhiten' = 'no' or 'yes', prewhiten the leadfield matrix with the noise covariance matrix C + 'scalesourcecov' = 'no' or 'yes', scale the source covariance matrix R such that trace(leadfield*R*leadfield')/trace(C)=1 + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + This implements + - Dale AM, Liu AK, Fischl B, Buckner RL, Belliveau JW, Lewine JD, + Halgren E (2000): Dynamic statistical parametric mapping: combining fMRI and MEG + to produce high-resolution spatiotemporal maps of cortical activity. Neuron + 26:55-67. + - Arthur K. Liu, Anders M. Dale, and John W. Belliveau (2002): Monte + Carlo Simulation Studies of EEG and MEG Localization Accuracy. Human Brain + Mapping 16:47-62. + - Fa-Hsuan Lin, Thomas Witzel, Matti S. Hamalainen, Anders M. Dale, + John W. Belliveau, and Steven M. Stufflebeam (2004): Spectral spatiotemporal + imaging of cortical oscillations and interactions in the human brain. NeuroImage + 23:582-595. + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_mne.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_music` + +```{text} + FT_INVERSE_MUSIC source localization using MUltiple SIgnal Classification. + This is a signal subspace method, which covers the techniques for + multiple source localization by using the eigen-structure of the + measured data matrix. + + Use as + [estimate] = ft_inverse_music(sourcemodel, sens, headmodel, dat, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'cov' = data covariance matrix + 'numcomponent' = integer number + 'feedback' = can be 'none', 'gui', 'dial', 'textbar', 'text', 'textcr', 'textnl' (default = 'text') + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + This implements + - J.C. Mosher, P.S. Lewis and R.M. Leahy, "Multiple dipole modeling and + localization from spatiotemporal MEG data", IEEE Trans. Biomed. Eng., + pp 541-557, June, 1992. + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_music.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_pcc` + +```{text} + FT_INVERSE_PCC implements a linearly-constrained miminum variance beamformer that + allows for post-hoc computation of canonical or partial coherence or correlation. + Moreover, if cortico-cortical interactions are computed, the spatial filters are + computed with a paired dipole as sourcemodel, thus suppressing the distortive + effect of correlated activity from the seed region. + + Use as + [estimate] = ft_inverse_pcc(sourcemodel, sens, headmodel, dat, cov, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + cov is the data covariance or cross-spectral density matrix + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'refchan' + 'refdip' + 'supchan' + 'supdip' + 'feedback' + 'keepcsd' + 'keepfilter' + 'keepleadfield' + 'keepmom' + 'lambda' + 'projectnoise' + 'realfilter' + 'fixedori' + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_pcc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_rv` + +```{text} + FT_INVERSE_RV scan with a single dipole and computes the residual variance + at each dipole location. + + Use as + [estimate] = ft_inverse_rv(sourcemodel, sens, headmodel, dat, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'feedback' = can be 'none', 'gui', 'dial', 'textbar', 'text', 'textcr', 'textnl' (default = 'text') + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_rv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_sam` + +```{text} + FT_INVERSE_SAM scans on pre-defined dipole locations with a single dipole and + returns the Synthetic Aperture Magnetometry (SAM) beamformer estimates. + + Use as + [estimate] = ft_inverse_sam(sourcemodel, sens, headmodel, dat, cov, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + cov is the data covariance or cross-spectral density matrix + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'feedback' + 'fixedori' deprecated, control behaviour via 'reducerank' instead + 'noisecov' + 'toi' + + If no orientation is specified, the SAM beamformer will try to estimate the orientation from the data. + The beamformer will either try to estimate the whole orientation, or only its tangential component. + This is controlled by the 'reducerank' parameter. For reducerank=3, the whole orientation is estimated, + and for reducerank=2 only the tangential component is estimated, based on an svd of the dipole's leadfield, + treating the 3d component as the 'radial' orientation. + + These options influence the forward computation of the leadfield, if it has not yet been precomputed + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_sam.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_inverse_sloreta` + +```{text} + FT_INVERSE_SLORETA scans on pre-defined dipole locations with a single dipole and + returns the sLORETA spatial filter output for a dipole on every location. + + Use as + [estimate] = ft_inverse_sloreta(sourcemodel, sens, headmodel, dat, cov, ...) + where + sourcemodel is the input source model, see FT_PREPARE_SOURCEMODEL + sens is the gradiometer or electrode definition, see FT_DATATYPE_SENS + headmodel is the volume conductor definition, see FT_PREPARE_HEADMODEL + dat is the data matrix with the ERP or ERF + cov is the data covariance or cross-spectral density matrix + and + estimate contains the estimated source parameters + + Additional input arguments should be specified as key-value pairs and can include + 'lambda' = regularisation parameter + 'powmethod' = can be 'trace' or 'lambda1' + 'feedback' = can be 'none', 'gui', 'dial', 'textbar', 'text', 'textcr', 'textnl' (default = 'text') + 'fixedori' = use fixed or free orientation, can be 'yes' or 'no' + 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no' + 'projectmom' = project the dipole moment timecourse on the direction of maximal power, can be 'yes' or 'no' + 'keepfilter' = remember the spatial filter, can be 'yes' or 'no' + 'keepleadfield' = remember the forward computation, can be 'yes' or 'no' + 'keepmom' = remember the estimated dipole moment timeseries, can be 'yes' or 'no' + 'keepcov' = remember the estimated dipole covariance, can be 'yes' or 'no' + 'kurtosis' = compute the kurtosis of the dipole timeseries, can be 'yes' or 'no' + + These options influence the forward computation of the leadfield + 'reducerank' = 'no' or number (default = 3 for EEG, 2 for MEG) + 'backproject' = 'yes' or 'no', in the case of a rank reduction this parameter determines whether the result will be backprojected onto the original subspace (default = 'yes') + 'normalize' = 'no', 'yes' or 'column' (default = 'no') + 'normalizeparam' = parameter for depth normalization (default = 0.5) + 'weight' = number or Nx1 vector, weight for each dipole position to compensate for the size of the corresponding patch (default = 1) + + If the dipole definition only specifies the dipole location, a rotating dipole + (regional source) is assumed on each location. If a dipole moment is specified, its + orientation will be used and only the strength will be fitted to the data. + + See also FT_SOURCEANALYSIS, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/inverse/ft_inverse_sloreta.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_keyval2cfg` + +```{text} + FT_KEYVAL2CFG converts between a structure and a cell-array with key-value + pairs which can be used for optional input arguments. + + Use as + [cfg] = ft_keyval2cfg(varargin) + + See also FT_CFG2KEYVAL, FT_GETOPT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_keyval2cfg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_lateralizedpotential` + +```{text} + FT_LATERALIZEDPOTENTIAL computes lateralized potentials such as the + lateralized readiness potential (LRP) + + Use as + [lrp] = ft_lateralizedpotential(cfg, avgL, avgR) + + where the input datasets should come from FT_TIMELOCKANALYSIS + and the configuration should contain + cfg.channelcmb = Nx2 cell-array + + An example channelcombination containing the homologous channels + in the 10-20 standard system is + cfg.channelcmb = {'Fp1' 'Fp2' + 'F7' 'F8' + 'F3' 'F4' + 'T7' 'T8' + 'C3' 'C4' + 'P7' 'P8' + 'P3' 'P4' + 'O1' 'O2'} + + The lateralized potential is computed on combinations of channels and + not on indivudual channels. However, if you want to make a topographic + plot with e.g. FT_MULTIPLOTER, you can replace the output lrp.label + with lrp.plotlabel. + + The concept for the LRP was introduced approximately simultaneously in the + following two papers + - M. G. H. Coles. Modern mind-brain reading - psychophysiology, + physiology, and cognition. Psychophysiology, 26(3):251-269, 1988. + - R. de Jong, M. Wierda, G. Mulder, and L. J. Mulder. Use of + partial stimulus information in response processing. J Exp Psychol + Hum Percept Perform, 14:682-692, 1988. + and it is discussed in detail on a technical level in + - R. Oostenveld, D.F. Stegeman, P. Praamstra and A. van Oosterom. + Brain symmetry and topographic analysis of lateralized event-related + potentials. Clin Neurophysiol. 114(7):1194-202, 2003. + + 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_TIMELOCKANALYSIS, FT_MULTIPLOTER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_lateralizedpotential.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_layoutplot` + +```{text} + FT_LAYOUTPLOT makes a figure with the 2-D layout of the channel positions + for topoplotting and the individual channel axes (i.e. width and height + of the subfigures) for multiplotting. A correct 2-D layout is a + prerequisite for plotting the topographical distribution of the + potential or field distribution, or for plotting timecourses in a + topographical arrangement. + + This function uses the same configuration options as prepare_layout and + as the topoplotting and multiplotting functions. The difference is that + this function plots the layout without any data, which facilitates + the validation of your 2-D layout. + + Use as + ft_layoutplot(cfg, data) + + There are several ways in which a 2-D layout can be made: it can be read + directly from a *.lay file, it can be created based on 3-D electrode or + gradiometer positions in the configuration or in the data, or it can be + created based on the specification of an electrode of gradiometer file. + + You can specify either one of the following configuration options + cfg.layout = filename containg the layout + cfg.rotate = number, rotation around the z-axis in degrees (default = [], which means automatic) + cfg.projection = string, 2D projection method can be 'stereographic', 'ortographic', 'polar', 'gnomic' or 'inverse' (default = 'orthographic') + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + cfg.opto = structure with optode definition or filename, see FT_READ_SENS + cfg.output = filename to which the layout will be written (default = []) + cfg.montage = 'no' or a montage structure (default = 'no') + cfg.image = filename, use an image to construct a layout (e.g. usefull for ECoG grids) + cfg.box = string, 'yes' or 'no' whether box should be plotted around electrode (default = 'yes') + cfg.mask = string, 'yes' or 'no' whether the mask should be plotted (default = 'yes') + cfg.visible = string, 'on' or 'off' whether figure will be visible (default = 'on') + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + + Alternatively the layout can be constructed from either + data.elec structure with electrode positions + data.grad structure with gradiometer definition + + Alternatively, you can specify + cfg.layout = 'ordered' + which will give you a 2-D ordered layout. Note that this is only suited + for multiplotting and not for topoplotting. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_PREPARE_LAYOUT, FT_TOPOPLOTER, FT_TOPOPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_layoutplot.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_math` + +```{text} + 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' + 'sqrt', 'square' + 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 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_math.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_megplanar` + +```{text} + FT_MEGPLANAR computes planar MEG gradients gradients for raw data or average + event-related field data. It can also convert frequency-domain data that was computed + using FT_FREQANALYSIS, as long as it contains the complex-valued fourierspcrm and not + only the powspctrm. + + Use as + [interp] = ft_megplanar(cfg, data) + where the input data corresponds to the output from FT_PREPROCESSING, + FT_TIMELOCKANALYSIS or FT_FREQANALYSIS (with output='fourier'). + + The configuration should contain + cfg.planarmethod = string, can be 'sincos', 'orig', 'fitplane', 'sourceproject' (default = 'sincos') + cfg.channel = Nx1 cell-array with selection of channels (default = {'megmag', 'meggrad'}), see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + + The methods orig, sincos and fitplane are all based on a neighbourhood interpolation. + For these methods you need to specify + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS + + In the 'sourceproject' method a minumum current estimate is done using a large number + of dipoles that are placed in the upper layer of the brain surface, followed by a + forward computation towards a planar gradiometer array. This requires the + specification of a volume conduction model of the head and of a source model. The + 'sourceproject' method is not supported for frequency domain data. + + A dipole layer representing the brain surface must be specified with + cfg.inwardshift = depth of the source layer relative to the head model surface , + (default = 2.5 cm, which is appropriate for a skin-based head model) + cfg.spheremesh = number of dipoles in the source layer (default = 642) + cfg.tolerance = tolerance ratio for leadfield matrix inverse based on a truncated svd, + reflects the relative magnitude of the largest singular value + to retain (default = 1e-3) + cfg.headshape = a filename containing headshape, a structure containing a + single triangulated boundary, or a Nx3 matrix with surface + points + If no headshape is specified, the dipole layer will be based on the inner compartment + of the volume conduction model. + + Optionally, you can modify the leadfields by reducing the rank, i.e. remove the weakest orientation + cfg.reducerank = 'no', or number (default = 3 for EEG, 2 for MEG) + cfg.backproject = 'yes' or 'no', determines when reducerank is applied whether the + lower rank leadfield is projected back onto the original linear + subspace, or not (default = 'yes') + + The volume conduction model of the head should be specified as + cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL + + The following cfg fields are optional: + cfg.feedback + + 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_COMBINEPLANAR, FT_PREPARE_NEIGHBOURS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_megplanar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_megrealign` + +```{text} + FT_MEGREALIGN interpolates MEG data towards standard gradiometer locations by + projecting the individual timelocked data towards a coarse source reconstructed + representation and computing the magnetic field on the standard gradiometer + locations. + + Use as + [interp] = ft_megrealign(cfg, data) + where the input data corresponds to the output from FT_PREPROCESSING. + + Required configuration options are + cfg.template + cfg.inwardshift + + The new gradiometer definition is obtained from a template dataset, + or can be constructed by averaging the gradiometer positions over + multiple datasets. + cfg.template = single dataset that serves as template + cfg.template(1..N) = datasets that are averaged into the standard + + The realignment is done by computing a minumum norm estimate using a + large number of dipoles that are placed in the upper layer of the brain + surface, followed by a forward computation towards the template + gradiometer array. This requires the specification of a volume conduction + model of the head and of a source model. + + A volume conduction model of the head should be specified with + cfg.headmodel = structure, see FT_PREPARE_HEADMODEL + + A source model (i.e. a superficial layer with distributed sources) can be + constructed from a headshape file, or from inner surface of the volume conduction + model using FT_PREPARE_SOURCEMODEL using the following options + cfg.spheremesh = number of dipoles in the source layer (default = 642) + cfg.inwardshift = depth of the source layer relative to the headshape + surface or volume conduction model (no default + supplied, see below) + cfg.headshape = a filename containing headshape, a structure containing a + single triangulated boundary, or a Nx3 matrix with surface + points + + If you specify a headshape and it describes the skin surface, you should specify an + inward shift of 2.5 cm. + + For a single-sphere or a local-spheres volume conduction model based on the skin + surface, an inward shift of 2.5 cm is reasonable. + + For a single-sphere or a local-spheres volume conduction model based on the brain + surface, you should probably use an inward shift of about 1 cm. + + For a realistic single-shell volume conduction model based on the brain surface, you + should probably use an inward shift of about 1 cm. + + Other configuration options are + cfg.tolerance = tolerance ratio for leadfield matrix inverse based on a truncated svd, + reflects the relative magnitude of the largest singular value + to retain (default =s 1e-3) + cfg.verify = 'yes' or 'no', show the percentage difference (default = 'yes') + cfg.feedback = 'yes' or 'no' (default = 'no') + cfg.channel = Nx1 cell-array with selection of channels (default = 'MEG'), + see FT_CHANNELSELECTION for details + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + + This implements the method described by T.R. Knosche, Transformation + of whole-head MEG recordings between different sensor positions. + Biomed Tech (Berl). 2002 Mar;47(3):59-62. For more information and + related methods, see Stolk et al., Online and offline tools for head + movement compensation in MEG. NeuroImage, 2012. + + 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_PREPARE_LOCALSPHERES, FT_PREPARE_SINGLESHELL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_megrealign.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_meshrealign` + +```{text} + FT_MESHREALIGN rotates, translates and optionally scales a surface description of + the head or of the cortex. The different methods are described in detail below. + + INTERACTIVE - This displays the mesh surface together with an anatomical MRI, with + a head model, with electrodes, with gradiometers, with optodes, or simply with the + axis of the coordinate system, and you manually (using the graphical user + interface) adjust the rotation, translation and scaling parameters. + + FIDUCIAL - The coordinate system is updated according to the definition of the + coordinates of anatomical landmarks or fiducials that are specified in the + configuration. If the fiducials are not specified in the configuration, you will + have to click them in an interactive display of the mesh surface. + + Use as + mesh = ft_meshrealign(cfg, mesh) + where the mesh input argument comes from FT_READ_HEADSHAPE or FT_PREPARE_MESH and + cfg is a configuration structure that should contain + cfg.method = string, can be 'interactive' or fiducial' (default = 'interactive') + cfg.coordsys = string specifying the origin and the axes of the coordinate + system. Supported coordinate systems are 'ctf', '4d', 'bti', + 'eeglab', 'neuromag', 'itab', 'yokogawa', 'asa', 'acpc', + and 'paxinos'. See http://tinyurl.com/ojkuhqz + + When cfg.method = 'fiducial' and cfg.coordsys is based on external anatomical + landmarks, as is common for EEG and MEG, the following can be used to specify the + voxel indices of the fiducials: + cfg.fiducial.nas = [x y z], position of nasion + cfg.fiducial.lpa = [x y z], position of LPA + cfg.fiducial.rpa = [x y z], position of RPA + The fiducials should be expressed in the same coordinates and units as the input + mesh. If the fiducials are not specified in the configuration, the mesh is + displayed and you have to click on the fidicuals. + + When cfg.method = 'fiducial' you can specify + cfg.mri = structure, see FT_READ_MRI + cfg.headmodel = structure, see FT_PREPARE_HEADMODEL + cfg.elec = structure, see FT_READ_SENS + cfg.grad = structure, see FT_READ_SENS + cfg.opto = structure, see FT_READ_SENS + If none of these is specified, the x-, y- and z-axes will be shown. + + 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_READ_HEADSHAPE, FT_PREPARE_MESH, FT_ELECTRODEREALIGN, FT_VOLUMEREALIGN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_meshrealign.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_movieplotER` + +```{text} + FT_MOVIEPLOTER makes a movie of the the event-related potentials, event-related + fields or oscillatory activity (power or coherence) versus frequency. + + Use as + ft_movieplotER(cfg, timelock) + where the input data is from FT_TIMELOCKANALYSIS and the configuration + can contain + cfg.parameter = string, parameter that is color coded (default = 'avg') + cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin') + cfg.zlim = plotting limits for color dimension, 'maxmin', + 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.speed = number, initial speed for interactive mode (default = 1) + cfg.samperframe = number, samples per frame for non-interactive mode (default = 1) + cfg.framespersec = number, frames per second for non-interactive mode (default = 5)% cfg.framesfile = 'string' or empty, filename of saved frames.mat (default = []) + cfg.layout = specification of the layout, see below + cfg.interpolatenan = string 'yes', 'no' interpolate over channels containing NaNs (default = 'yes') + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE + cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute') + cfg.colorbar = 'yes', 'no' (default = 'no') + cfg.colorbartext = string indicating the text next to colorbar + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + + The layout defines how the channels are arranged. You can specify the + layout in a variety of ways: + - you can provide a pre-computed layout structure (see prepare_layout) + - you can give the name of an ascii layout file with extension *.lay + - you can give the name of an electrode file + - you can give an electrode definition, i.e. "elec" structure + - you can give a gradiometer definition, i.e. "grad" structure + If you do not specify any of these and the data structure contains an + electrode or gradiometer structure, that will be used for creating a + layout. If you want to have more fine-grained control over the layout + of the subplots, you should create your own layout file. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_MULTIPLOTER, FT_TOPOPLOTER, FT_SINGLEPLOTER, FT_MOVIEPLOTTFR, FT_SOURCEMOVIE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_movieplotER.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_movieplotTFR` + +```{text} + FT_MOVIEPLOTTFR makes a movie of the time-frequency representation of power or + coherence. + + Use as + ft_movieplotTFR(cfg, data) + where the input data comes from FT_FREQANALYSIS or FT_FREQDESCRIPTIVES and the + configuration is a structure that can contain + cfg.parameter = string, parameter that is color coded (default = 'avg') + cfg.xlim = selection boundaries over first dimension in data (e.g., time) + 'maxmin' or [xmin xmax] (default = 'maxmin') + cfg.ylim = selection boundaries over second dimension in data (e.g., freq) + 'maxmin' or [xmin xmax] (default = 'maxmin') + cfg.zlim = plotting limits for color dimension, 'maxmin', + 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.speed = number, initial speed for interactive mode (default = 1) + cfg.samperframe = number, samples per frame for non-interactive mode (default = 1) + cfg.framespersec = number, frames per second for non-interactive mode (default = 5) + cfg.framesfile = 'string' or empty, filename of saved frames.mat (default = []) + cfg.moviefreq = number, movie frames are all time points at the fixed frequency moviefreq (default = []) + cfg.movietime = number, movie frames are all frequencies at the fixed time movietime (default = []) + cfg.layout = specification of the layout, see below + cfg.interpolatenan = string 'yes', 'no' interpolate over channels containing NaNs (default = 'yes') + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + cfg.interactive = 'no' or 'yes', make it interactive + cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE + cfg.baselinetype = 'absolute', 'relative', 'relchange', 'normchange', 'db' or 'zscore' (default = 'absolute') + cfg.colorbar = 'yes', 'no' (default = 'no') + cfg.colorbartext = string indicating the text next to colorbar + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + + The layout defines how the channels are arranged. You can specify the + layout in a variety of ways: + - you can provide a pre-computed layout structure (see prepare_layout) + - you can give the name of an ascii layout file with extension *.mat + - you can give the name of an electrode file + - you can give an electrode definition, i.e. "elec" structure + - you can give a gradiometer definition, i.e. "grad" structure + If you do not specify any of these and the data structure contains an + electrode or gradiometer structure, that will be used for creating a + layout. If you want to have more fine-grained control over the layout + of the subplots, you should create your own layout file. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. this mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_MULTIPLOTTFR, FT_TOPOPLOTTFR, FT_SINGLEPLOTTFR, FT_MOVIEPLOTER, FT_SOURCEMOVIE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_movieplotTFR.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_multiplotCC` + +```{text} + FT_MULTIPLOTCC visualises the coherence between channels by using + multiple topoplots. The topoplot at a given channel location shows the + coherence of that channel with all other channels. + + Use as + ft_multiplotCC(cfg, data) + + See also FT_PREPARE_LAYOUT, FT_TOPOPLOTCC, FT_CONNECTIVITYPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_multiplotCC.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_multiplotER` + +```{text} + FT_MULTIPLOTER plots the event-related potentials or event-related fields + versus time, or the oscillatory activity (power or coherence) versus frequency. + Multiple datasets can be overlayed. The plots are arranged according to + the location of the channels specified in the layout. + + Use as + ft_multiplotER(cfg, data) + or + ft_multiplotER(cfg, data, data2, ..., dataN) + + The data can be an event-related potential or field produced by + FT_TIMELOCKANALYSIS, a power spectrum produced by FT_FREQANALYSIS or a coherence + spectrum produced by FT_FREQDESCRIPTIVES. + + If you specify multiple datasets they should contain the same channels, etc. + + The configuration can have the following parameters: + cfg.parameter = field to be plotted on y-axis, for example 'avg', 'powspctrm' or 'cohspctrm' (default is automatic) + cfg.maskparameter = field in the first dataset to be used for marking significant data + cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box') + cfg.maskfacealpha = mask transparency value between 0 and 1 + cfg.xlim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [xmin xmax] (default = 'maxmin') + cfg.ylim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [ymin ymax] (default = 'maxmin') + cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display + cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' + cfg.baseline = 'yes', 'no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.axes = string, 'yes' or 'no' whether to draw x- and y-axes for each graph (default = 'yes') + cfg.box = string, 'yes' or 'no' whether to draw a box around each graph (default = 'no') + cfg.showlabels = 'yes' or 'no' (default = 'no') + cfg.showoutline = 'yes' or 'no' (default = 'no') + cfg.showscale = 'yes' or 'no' (default = 'yes') + cfg.showcomment = 'yes' or 'no' (default = 'yes') + cfg.comment = string of text (default = date + limits) + Add 'comment' to graph (according to COMNT in the layout) + cfg.limittext = add user-defined text instead of cfg.comment, (default = cfg.comment) + cfg.fontsize = font size of comment and labels (default = 8) + cfg.interactive = 'yes' or 'no', make the plot interactive (default = 'yes') + In an interactive plot you can select areas and produce a new + interactive plot when a selected area is clicked. Multiple areas + can be selected by holding down the SHIFT key. + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + cfg.colorgroups = 'sequential', 'allblack', 'labelcharN' (N = Nth character in label), 'chantype' or a vector + with the length of the number of channels defining the groups (default = 'condition') + cfg.linestyle = linestyle/marker type, see options of the PLOT function (default = '-') + can be a single style for all datasets, or a cell-array containing one style for each dataset + cfg.linewidth = linewidth in points (default = 0.5) + cfg.linecolor = color(s) used for plotting the dataset(s). The default is defined in LINEATTRIBUTES_COMMON, see + the help of this function for more information. + cfg.directionality = '', 'inflow' or 'outflow' specifies for connectivity measures whether the + inflow into a node, or the outflow from a node is plotted. The (default) behavior + of this option depends on the dimord of the input data (see below). + cfg.layout = specify the channel layout for plotting using one of the supported ways (see below). + cfg.select = 'intersect' or 'union' with multiple input arguments determines the + pre-selection of the data that is considered for plotting (default = 'intersect') + cfg.viewmode = 'topographic' or 'butterfly', whether to use the topographic channel layout or a butterfly plot (default = 'topographic') + + The following options for the scaling of the EEG, EOG, ECG, EMG, MEG and NIRS channels + is optional and can be used to bring the absolute numbers of the different + channel types in the same range (e.g. fT and uV). The channel types are determined + from the input data using FT_CHANNELSELECTION. + cfg.eegscale = number, scaling to apply to the EEG channels prior to display + cfg.eogscale = number, scaling to apply to the EOG channels prior to display + cfg.ecgscale = number, scaling to apply to the ECG channels prior to display + cfg.emgscale = number, scaling to apply to the EMG channels prior to display + cfg.megscale = number, scaling to apply to the MEG channels prior to display + cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor) + cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor) + cfg.nirsscale = number, scaling to apply to the NIRS channels prior to display + cfg.mychanscale = number, scaling to apply to the channels specified in cfg.mychan + cfg.mychan = Nx1 cell-array with selection of channels + cfg.chanscale = Nx1 vector with scaling factors, one per channel specified in cfg.channel + + For the plotting of directional connectivity data the cfg.directionality option + determines what is plotted. The default value and the supported functionality + depend on the dimord of the input data. If the input data is of dimord + 'chan_chan_XXX', the value of directionality determines whether, given the + reference channel(s), the columns (inflow), or rows (outflow) are selected for + plotting. In this situation the default is 'inflow'. Note that for undirected + measures, inflow and outflow should give the same output. If the input data is of + dimord 'chancmb_XXX', the value of directionality determines whether the rows in + data.labelcmb are selected. With 'inflow' the rows are selected if the + refchannel(s) occur in the right column, with 'outflow' the rows are selected if + the refchannel(s) occur in the left column of the labelcmb-field. Default in this + case is '', which means that all rows are selected in which the refchannel(s) + occur. This is to robustly support linearly indexed undirected connectivity + metrics. In the situation where undirected connectivity measures are linearly + indexed, specifying 'inflow' or 'outflow' can result in unexpected behavior. + + The layout defines how the channels are arranged and what the size of each + subplot is. You can specify the layout in a variety of ways: + - you can provide a pre-computed layout structure (see prepare_layout) + - you can give the name of an ascii layout file with extension *.lay + - you can give the name of an electrode file + - you can give an electrode definition, i.e. "elec" structure + - you can give a gradiometer definition, i.e. "grad" structure + If you do not specify any of these and the data structure contains an + electrode or gradiometer structure, that will be used for creating a + layout. If you want to have more fine-grained control over the layout + of the subplots, you should create your own layout file. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. For this particular function, the + data should be provided as a cell-array. + + See also FT_MULTIPLOTTFR, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER, + FT_TOPOPLOTTFR, FT_PREPARE_LAYOUT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_multiplotER.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_multiplotTFR` + +```{text} + FT_MULTIPLOTTFR plots the time-frequency representations of power or coherence + in a topographical layout. The plots of the indivual sensors are arranged + according to their location specified in the layout. + + Use as + ft_multiplotTFR(cfg, data) + + The data can be a time-frequency representation of power or coherence + that was computed using the FT_FREQANALYSIS or FT_FREQDESCRIPTIVES + functions. + + The configuration can have the following parameters: + cfg.parameter = field to be represented as color, for example 'powspctrm' or 'cohspctrm' (default depends on data.dimord) + cfg.maskparameter = field in the data to be used for masking of data, can be logical (e.g. significant data points) or numerical (e.g. t-values). + (not possible for mean over multiple channels, or when input contains multiple subjects + or trials) + cfg.maskstyle = style used to masking, 'opacity', 'saturation', or 'outline' (default = 'opacity') + 'outline' can only be used with a logical cfg.maskparameter + use 'saturation' or 'outline' when saving to vector-format (like *.eps) to avoid all sorts of image-problems + cfg.maskalpha = alpha value between 0 (transparent) and 1 (opaque) used for masking areas dictated by cfg.maskparameter (default = 1) + (will be ignored in case of numeric cfg.maskparameter or if cfg.maskstyle = 'outline') + cfg.masknans = 'yes' or 'no' (default = 'yes') + cfg.xlim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [xmin xmax] (default = 'maxmin') + cfg.ylim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [ymin ymax] (default = 'maxmin') + cfg.zlim = plotting limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display + cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' + cfg.baseline = 'yes', 'no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE + cfg.baselinetype = 'absolute', 'relative', 'relchange', 'normchange', 'db' or 'zscore' (default = 'absolute') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.box = 'yes', 'no', whether to draw a box around each graph (default = 'no', if maskparameter is given default = 'yes') + cfg.hotkeys = enables hotkeys (up/down arrows) for dynamic colorbar adjustment + cfg.colorbar = 'yes', 'no' (default = 'no') + cfg.colorbartext = string indicating the text next to colorbar + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + cfg.showlabels = 'yes', 'no' (default = 'no') + cfg.showoutline = 'yes', 'no' (default = 'no') + cfg.showscale = 'yes', 'no' (default = 'yes') + cfg.showcomment = 'yes', 'no' (default = 'yes') + cfg.comment = string of text (default = date + limits) + Add 'comment' to graph (according to COMNT in the layout) + cfg.limittext = add user-defined text instead of cfg.comment, (default = cfg.comment) + cfg.fontsize = font size of comment and labels (if present) (default = 8) + cfg.fontweight = font weight of comment and labels (if present) + cfg.interactive = Interactive plot 'yes' or 'no' (default = 'yes') + In a interactive plot you can select areas and produce a new + interactive plot when a selected area is clicked. Multiple areas + can be selected by holding down the SHIFT key. + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + cfg.directionality = '', 'inflow' or 'outflow' specifies for + connectivity measures whether the inflow into a + node, or the outflow from a node is plotted. The + (default) behavior of this option depends on the dimor + of the input data (see below). + cfg.layout = specify the channel layout for plotting using one of + the supported ways (see below). + + The following options for the scaling of the EEG, EOG, ECG, EMG, MEG and NIRS channels + is optional and can be used to bring the absolute numbers of the different + channel types in the same range (e.g. fT and uV). The channel types are determined + from the input data using FT_CHANNELSELECTION. + cfg.eegscale = number, scaling to apply to the EEG channels prior to display + cfg.eogscale = number, scaling to apply to the EOG channels prior to display + cfg.ecgscale = number, scaling to apply to the ECG channels prior to display + cfg.emgscale = number, scaling to apply to the EMG channels prior to display + cfg.megscale = number, scaling to apply to the MEG channels prior to display + cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor) + cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor) + cfg.nirsscale = number, scaling to apply to the NIRS channels prior to display + cfg.mychanscale = number, scaling to apply to the channels specified in cfg.mychan + cfg.mychan = Nx1 cell-array with selection of channels + cfg.chanscale = Nx1 vector with scaling factors, one per channel specified in cfg.channel + + For the plotting of directional connectivity data the cfg.directionality + option determines what is plotted. The default value and the supported + functionality depend on the dimord of the input data. If the input data + is of dimord 'chan_chan_XXX', the value of directionality determines + whether, given the reference channel(s), the columns (inflow), or rows + (outflow) are selected for plotting. In this situation the default is + 'inflow'. Note that for undirected measures, inflow and outflow should + give the same output. If the input data is of dimord 'chancmb_XXX', the + value of directionality determines whether the rows in data.labelcmb are + selected. With 'inflow' the rows are selected if the refchannel(s) occur in + the right column, with 'outflow' the rows are selected if the + refchannel(s) occur in the left column of the labelcmb-field. Default in + this case is '', which means that all rows are selected in which the + refchannel(s) occur. This is to robustly support linearly indexed + undirected connectivity metrics. In the situation where undirected + connectivity measures are linearly indexed, specifying 'inflow' or + 'outflow' can result in unexpected behavior. + + The layout defines how the channels are arranged and what the size of each + subplot is. You can specify the layout in a variety of ways: + - you can provide a pre-computed layout structure, see FT_PREPARE_LAYOUT + - you can give the name of an ASCII layout file with extension *.lay + - you can give the name of an electrode file + - you can give an electrode definition, i.e. "elec" structure + - you can give a gradiometer definition, i.e. "grad" structure + If you do not specify any of these and the data structure contains an + electrode or gradiometer structure (common for MEG data, since the header + of the MEG datafile contains the gradiometer information), that will be + used for creating a layout. If you want to have more fine-grained control + over the layout of the subplots, you should create your own layout file. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. For this particular function, the + data should be provided as a cell-array. + + See also: + FT_MULTIPLOTER, FT_SINGLEPLOTER, FT_SINGLEPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR, + FT_PREPARE_LAYOUT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_multiplotTFR.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_mvaranalysis` + +```{text} + FT_MVARANALYSIS performs multivariate autoregressive modeling on + time series data over multiple trials. + + Use as + [mvardata] = ft_mvaranalysis(cfg, data) + + The input data should be organised in a structure as obtained from + the FT_PREPROCESSING function. The configuration depends on the type + of computation that you want to perform. + The output is a data structure of datatype 'mvar' which contains the + multivariate autoregressive coefficients in the field coeffs, and the + covariance of the residuals in the field noisecov. + + The configuration should contain: + cfg.method = the name of the toolbox containing the function for the + actual computation of the ar-coefficients + this can be 'biosig' (default) or 'bsmart' + you should have a copy of the specified toolbox in order + to use mvaranalysis (both can be downloaded directly). + cfg.mvarmethod = scalar (only required when cfg.method = 'biosig'). + default is 2, relates to the algorithm used for the + computation of the AR-coefficients by mvar.m + cfg.order = scalar, order of the autoregressive model (default=10) + cfg.channel = 'all' (default) or list of channels for which an mvar model + is fitted. (Do NOT specify if cfg.channelcmb is + defined) + cfg.channelcmb = specify channel combinations as a + two-column cell-array with channels in each column between + which a bivariate model will be fit (overrides + cfg.channel) + cfg.keeptrials = 'no' (default) or 'yes' specifies whether the coefficients + are estimated for each trial separately, or on the + concatenated data + cfg.jackknife = 'no' (default) or 'yes' specifies whether the coefficients + are estimated for all leave-one-out sets of trials + cfg.zscore = 'no' (default) or 'yes' specifies whether the channel data + are z-transformed prior to the model fit. This may be + necessary if the magnitude of the signals is very different + e.g. when fitting a model to combined MEG/EMG data + cfg.demean = 'yes' (default) or 'no' explicit removal of DC-offset + cfg.ems = 'no' (default) or 'yes' explicit removal ensemble mean + + ft_mvaranalysis can be used to obtain one set of coefficients across + all time points in the data, also when the trials are of varying length. + + ft_mvaranalysis can be also used to obtain time-dependent sets of + coefficients based on a sliding window. In this case the input cfg + should contain: + + cfg.t_ftimwin = the width of the sliding window on which the coefficients + are estimated + cfg.toi = [t1 t2 ... tx] the time points at which the windows are + centered + + 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_PREPROCESSING, FT_SOURCESTATISTICS, FT_FREQSTATISTICS, + FT_TIMELOCKSTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_mvaranalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_neighbourplot` + +```{text} + FT_NEIGHBOURPLOT visualizes neighbouring channels in a particular channel + configuration. The positions of the channel are specified in a + gradiometer or electrode configuration or from a layout. + + Use as + ft_neighbourplot(cfg) + or as + ft_neighbourplot(cfg, data) + + Where the configuration can contain + cfg.verbose = string, 'yes' or 'no', whether the function will print feedback text in the command window + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS (optional) + cfg.enableedit = string, 'yes' or 'no', allows you to interactively add or remove edges between vertices (default = 'no') + cfg.visible = string, 'on' or 'off' whether figure will be visible (default = 'on') + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see MATLAB Figure Properties. If this function crashes, you should try 'painters'. + + and either one of the following options + cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + cfg.opto = structure with gradiometer definition or filename, see FT_READ_SENS + + If cfg.neighbours is not defined, this function will call + FT_PREPARE_NEIGHBOURS to determine the channel neighbours. The + following data fields may also be used by FT_PREPARE_NEIGHBOURS + data.elec = structure with electrode positions + data.grad = structure with gradiometer definition + data.opto = structure with optode definition + + If cfg.neighbours is empty, no neighbouring sensors are assumed. + + Use cfg.enableedit to interactively add or remove edges in your own neighbour structure. + + See also FT_PREPARE_NEIGHBOURS, FT_PREPARE_LAYOUT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_neighbourplot.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_networkanalysis` + +```{text} + FT_NETWORKANALYSIS computes various network graph measures from + between-channel or between source-level EEG/MEG signals. This function + acts as a wrapper aroun the network metrics implemented in the brain + connectivity toolbox developed by Olaf Sporns and colleagues. + + Use as + stat = ft_networkanalysis(cfg, data) + + where the first input argument is a configuration structure (see below) + and the second argument is the output of FT_CONNECTIVITYANALYSIS. + + At present the input data should be channel-level data with dimord + 'chan_chan(_freq)(_time)' or source data with dimord + 'pos_pos(_freq)(_time)'. + + The configuration structure has to contain + cfg.method = string, specifying the graph measure that will be + computed. See below for the list of supported measures. + cfg.parameter = string specifying the bivariate parameter in the data + for which the graph measure will be computed. + + Supported methods are + assortativity + betweenness, betweenness centrality (nodes) + charpath, characteristic path length, needs distance matrix as + input + clustering_coef, clustering coefficient + degrees + density + distance + edge_betweenness, betweenness centrality (edges) + transitivity + + 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_CONNECTIVITYANALYSIS, FT_CONNECTIVITYPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_networkanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_notice` + +```{text} + FT_NOTICE prints a notice message on screen, depending on the verbosity + settings of the calling high-level FieldTrip function. + + Use as + ft_notice(...) + with arguments similar to fprintf, or + ft_notice(msgId, ...) + with arguments similar to warning. + + You can switch of all messages using + ft_notice off + or for specific ones using + ft_notice off msgId + + To switch them back on, you would use + ft_notice on + or for specific ones using + ft_notice on msgId + + Messages are only printed once per timeout period using + ft_notice timeout 60 + ft_notice once + or for specific ones using + ft_notice once msgId + + You can see the most recent messages and identifier using + ft_notice last + + You can query the current on/off/once state for all messages using + ft_notice query + + See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_notice.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_platform_supports` + +```{text} + FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform + supports a specific capability + + Use as + status = ft_platform_supports(what) + or + status = ft_platform_supports('matlabversion', min_version, max_version) + + The following values are allowed for the 'what' parameter, which means means that + the specific feature explained on the right is supported: + + 'which-all' which(...,'all') + 'exists-in-private-directory' exists(...) will look in the /private subdirectory to see if a file exists + 'onCleanup' onCleanup(...) + 'alim' alim(...) + 'int32_logical_operations' bitand(a,b) with a, b of type int32 + 'graphics_objects' graphics system is object-oriented + 'libmx_c_interface' libmx is supported through mex in the C-language (recent MATLAB versions only support C++) + 'images' all image processing functions in FieldTrip's external/images directory + 'signal' all signal processing functions in FieldTrip's external/signal directory + 'stats' all statistical functions in FieldTrip's external/stats directory + 'program_invocation_name' program_invocation_name() (GNU Octave) + 'singleCompThread' start MATLAB with -singleCompThread + 'nosplash' start MATLAB with -nosplash + 'nodisplay' start MATLAB with -nodisplay + 'nojvm' start MATLAB with -nojvm + 'no-gui' start GNU Octave with --no-gui + 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) + 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) + 'rng' rng(...) + 'rand-state' rand('state') + 'urlread-timeout' urlread(..., 'Timeout', t) + 'griddata-vector-input' griddata(...,...,...,a,b) with a and b vectors + 'griddata-v4' griddata(...,...,...,...,...,'v4') with v4 interpolation support + 'uimenu' uimenu(...) + 'weboptions' weboptions(...) + 'parula' parula(...) + 'datetime' datetime structure + 'html' html rendering in desktop + + See also FT_VERSION, VERSION, VER, VERLESSTHAN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_platform_supports.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_axes` + +```{text} + FT_PLOT_AXES adds three axes of 150 mm and a 10 mm sphere at the origin to the + present 3-D figure. The axes and sphere are scaled according to the units of the + geometrical object that is passed to this function. Furthermore, when possible, + the axes labels will represent the anatomical labels corresponding to the + specified coordinate system. + + Use as + ft_plot_axes(object) + + Additional optional input arguments should be specified as key-value pairs + and can include + 'unit' = string, plot axes that are suitable for the specified geometrical units (default = []) + 'axisscale' = scaling factor for the reference axes and sphere (default = 1) + 'coordsys' = string, assume the data to be in the specified coordinate system (default = 'unknown') + 'transform' = empty or 4x4 homogenous transformation matrix (default = []) + 'fontcolor' = string, color specification (default = [1 .5 0], i.e. orange) + 'fontsize' = number, sets the size of the text (default is automatic) + 'fontunits' = + 'fontname' = + 'fontweight' = + 'tag' = string, the tag assigned to the plotted elements (default = '') + + See also FT_PLOT_SENS, FT_PLOT_MESH, FT_PLOT_ORTHO, FT_PLOT_HEADSHAPE, FT_PLOT_DIPOLE, FT_PLOT_HEADMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_axes.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_box` + +```{text} + FT_PLOT_BOX plots the outline of a box that is specified by its lower + left and upper right corner + + Use as + ft_plot_box(position, ...) + where the position of the box is specified as is [x1, x2, y1, y2]. + + Optional arguments should come in key-value pairs and can include + 'facealpha' = transparency value between 0 and 1 + 'facecolor' = color specification as [r g b] values or a string, for example 'brain', 'cortex', 'skin', 'red', 'r' + 'edgecolor' = color specification as [r g b] values or a string, for example 'brain', 'cortex', 'skin', 'red', 'r' + 'parent' = handle which is set as the parent for the plotted elements (default = []) + 'tag' = string, the tag assigned to the plotted elements (default = '') + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'hpos' = horizontal position of the center of the local axes + 'vpos' = vertical position of the center of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + 'hlim' = horizontal scaling limits within the local axes + 'vlim' = vertical scaling limits within the local axes + 'parent' = handle which is set as the parent for all plots (default = []) + + Example + ft_plot_box([-1 1 2 3], 'facecolor', 'b') + axis([-4 4 -4 4]) + + See also FT_PLOT_LINE, FT_PLOT_CROSSHAIR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_box.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_cloud` + +```{text} + FT_PLOT_CLOUD visualizes spatially sparse scalar data as spheres or + spherical clouds of points and optionally 2D slices through those clouds + + Use as + ft_plot_cloud(pos, val, ...) + where the first argument are the positions and the second argument are the values + for each location. + + Optional input arguments should come in key-value pairs and can include + 'cloudtype' = 'cloud' (default) plots a group of spherically arranged points at each sensor position + 'surf' plots a single spherical surface mesh at each sensor position + 'scalerad' = scale radius with val, can be 'yes' or 'no' (default = 'yes') + 'radius' = scalar, maximum radius of cloud (default = 4 mm) + 'clim' = 1x2 vector specifying the min and max for the colorscale + 'unit' = string, convert the sensor array to the specified geometrical units (default = []) + 'mesh' = string or Nx1 cell-array, triangulated mesh(es), see FT_PREPARE_MESH + 'slice' = requires 'mesh' as input (default = 'none') + '2d', plots 2D slices through the cloud with an outline of the mesh + '3d', draws an outline around the mesh at a particular slice + + The following inputs apply when 'cloudtype' = 'cloud' + 'rmin' = scalar >= 1, minimum radius of cloud if scalerad = 'yes' (default = 1 mm) + 'colormap' = colormap for functional data, see COLORMAP + 'colorgrad' = 'white' or a scalar (e.g. 1), degree to which the saturatoin of points in cloud changes from its center + 'ptsize' = scalar, size of points in cloud (default = 1 mm) + 'ptdensity' = scalar, density of points in cloud (default = 20 per mm^3) + 'ptgradient' = scalar, degree to which density of points in cloud changes from its center (default = 0.5, i.e. uniform density) + + The following inputs apply when 'slice' = '2d' or '3d' + 'ori' = 'x', 'y', or 'z', specifies the orthogonal plane which will be plotted (default = 'y') + 'slicepos' = 'auto' or Nx1 vector specifying the position of the + slice plane along the orientation axis (default = 'auto': chooses slice(s) with + the most data) + 'nslices' = scalar, number of slices to plot if 'slicepos' = 'auto (default = 1) + 'minspace' = scalar, minimum spacing between slices if nslices>1 + (default = 1) + 'intersectcolor' = string, Nx1 cell-array, or Nx3 vector specifying line color (default = 'k') + 'intersectlinestyle' = string or Nx1 cell-array, line style specification (default = '-') + 'intersectlinewidth' = scalar or Nx1 vector, line width specification (default = 2) + + The following inputs apply when 'cloudtype' = 'surf' and 'slice' = '2d' + 'ncirc' = scalar, number of concentric circles to plot for each + cloud slice (default = 15) make this hidden or scale + 'scalealpha' = 'yes' or 'no', scale the maximum alpha value of the center circle + with distance from center of cloud + + See also FT_ELECTRODEPLACEMENT, FT_PLOT_SENS, FT_PLOT_TOPO, FT_PLOT_TOPO3D + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_cloud.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_crosshair` + +```{text} + FT_PLOT_CROSSHAIR plots a crosshair at a specified position in two [x, y] or three + [x, y, z] dimensions. + + Use as + h = ft_plot_crosshair(pos, ...) + where pos is the desired position of the crosshair. The handles of the lines are + returned. + + Optional input arguments should be specified in key-value pairs and can include + 'color' = [r g b] value or string, see PLOT + 'parent' = handle which is set as the parent for the plotted elements (default = []) + 'handle' = handle of the existing line objects to be updated + + You can specify the handles of existing line objects which will be then updated, + rather than creating a new set of lines. If both parent and handle ar specified, + the handle option prevail. + + Example + ft_plot_crosshair([0.5 0.5], 'color', 'r') + + See also FT_PLOT_BOX, FT_PLOT_LINE, TEXT, LINE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_crosshair.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_dipole` + +```{text} + FT_PLOT_DIPOLE makes a 3-D representation of a dipole using a sphere and a stick + pointing along the dipole orientation + + Use as + ft_plot_dipole(pos, mom, ...) + where pos and mom are the dipole mosition and moment. + + Optional input arguments should be specified in key-value pairs and can include + 'diameter' = number indicating sphere diameter (default = 'auto') + 'length' = number indicating length of the stick (default = 'auto') + 'thickness' = number indicating thickness of the stick (default = 'auto') + 'color' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r' (default = 'r') + 'alpha' = alpha value of the plotted dipole + 'scale' = scale the dipole with the amplitude, can be 'none', 'both', 'diameter', 'length' (default = 'none') + 'unit' = 'm', 'cm' or 'mm', used for automatic scaling (default = 'cm') + 'coordsys' = string, assume the data to be in the specified coordinate system (default = 'unknown') + 'axes' = boolean, whether to plot the axes of the 3D coordinate system (default = false) + 'tag' = string, the tag assigned to the plotted elements (default = '') + + Example + ft_plot_dipole([0 0 0], [1 2 3], 'color', 'r', 'alpha', 1) + + See also FT_PLOT_MESH, FT_PLOT_HEADMODEL, FT_PLOT_HEADSHAPE, FT_PLOT_ORTHO, + QUIVER3, PLOT3 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_dipole.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_headmodel` + +```{text} + FT_PLOT_HEADMODEL visualizes the boundaries in the volume conduction model of the + head as specified in the headmodel structure. This works for any of the head models + supported by FieldTrip. For spherical models, it will construct and plot a + triangulated sphere. + + Use as + ft_plot_headmodel(headmodel, ...) + + Optional arguments should come in key-value pairs and can include + 'facecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx3 or Nx1 array where N is the number of faces + 'vertexcolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx3 or Nx1 array where N is the number of vertices + 'edgecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r' + 'faceindex' = true or false + 'vertexindex' = true or false + 'facealpha' = transparency, between 0 and 1 (default = 1) + 'edgealpha' = transparency, between 0 and 1 (default = 1) + 'surfaceonly' = true or false, plot only the outer surface of a hexahedral or tetrahedral mesh (default = false) + 'unit' = string, convert to the specified geometrical units (default = []) + 'axes' = boolean, whether to plot the axes of the 3D coordinate system (default = false) + 'grad' = gradiometer array, used in combination with local spheres model + + Example + headmodel = []; + headmodel.r = [86 88 92 100]; + headmodel.o = [0 0 40]; + figure + ft_plot_headmodel(headmodel) + + See also FT_PREPARE_HEADMODEL, FT_DATATAYPE_HEADMODEL, FT_PLOT_MESH, + FT_PLOT_HEADSHAPE, FT_PLOT_SENS, FT_PLOT_DIPOLE, FT_PLOT_ORTHO, FT_PLOT_TOPO3D + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_headmodel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_headshape` + +```{text} + FT_PLOT_HEADSHAPE visualizes the shape of a head from a variety of + acquisition system. Usually the head shape is measured with a + Polhemus tracker and some proprietary software (e.g. from CTF, BTi + or Yokogawa). The headshape and fiducials can be used for coregistration. + If present in the headshape, the location of the fiducials will also + be shown. + + Use as + ft_plot_headshape(headshape, ...) + where the headshape is a structure obtained from FT_READ_HEADSHAPE. + + Optional arguments should come in key-value pairs and can include + 'facecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx3 or Nx1 array where N is the number of faces + 'facealpha' = transparency, between 0 and 1 (default = 1) + 'vertexcolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx3 or Nx1 array where N is the number of vertices + 'vertexsize' = scalar value specifying the size of the vertices (default = 10) + 'transform' = transformation matrix for the fiducials, converts MRI voxels into head shape coordinates + 'unit' = string, convert to the specified geometrical units (default = []) + 'axes' = boolean, whether to plot the axes of the 3D coordinate system (default = false) + 'tag' = string, the tag assigned to the plotted elements (default = '') + + The sensor array can include an optional fid field with fiducials, which will also be plotted. + 'fidcolor' = [r g b] values or string, for example 'red', 'r', or an Nx3 or Nx1 array where N is the number of fiducials + 'fidmarker' = ['.', '*', '+', ...] + 'fidlabel' = ['yes', 'no', 1, 0, 'true', 'false'] + + Example: + headshape = ft_read_headshape(filename); + ft_plot_headshape(headshape) + + See also FT_PLOT_MESH, FT_PLOT_HEADMODEL, FT_PLOT_SENS, FT_PLOT_DIPOLE, + FT_PLOT_ORTHO, FT_PLOT_TOPO3D + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_headshape.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_layout` + +```{text} + FT_PLOT_LAYOUT plots a two-dimensional channel layout + + Use as + ft_plot_layout(layout, ...) + where the layout is a FieldTrip structure obtained from FT_PREPARE_LAYOUT. + + Additional options should be specified in key-value pairs and can be + 'chanindx' = logical vector or vector of indices. Which channels to plot (default is all) + 'point' = 'yes' or 'no' (default 'yes'), plot markers for sensors, comment and scale + 'box' = 'yes' or 'no' (default 'yes'), plot boxes around the sensors, comment and scale + 'label' = 'yes' or 'no' (default 'yes'), plot the labels of the sensors, comment and scale + 'labeloffset' = offset of label from point (default = 0) + 'labelrotate' = scalar or vector with rotation angle (in degrees) per label (default = 0) + 'labelalignh' = string or cell-array specifying the horizontal alignment of the text (default = 'center') + 'labelalignv' = string or cell-array specifying the vertical alignment of the text (default = 'middle') + 'mask' = 'yes' or 'no' (default 'yes'), plot the interpolation area of the layout + 'outline' = 'yes' or 'no' (default 'yes'), plot the outline of the layout (e.g. head and MEG helmet) + 'verbose' = 'yes' or 'no' (default 'no'), print explanation of the figure to command window + 'fontcolor' = string, text color specification (default = 'k') + 'fontsize' = scalar, sets the size of the text (default = 10) + 'fontunits' = string, units of the font size (default is the Matlab's session default) + 'fontname' = string, font name (default is the Matlab's session default) + 'fontweight' = scalar, sets the size of the text (default = 10) + 'interpreter' = string, 'none', 'tex' or 'latex' (default = 'tex') + + The following options control the markers of the sensors. If any is defined, the other two must be defined as well. + Further note that if 'chanindx' is used, the number of elements in each choice should correspond to the original + labels in the layout, and not to the chosen subset. + 'pointsymbol' = string with symbol (e.g. 'o' or 'oooxxx') + 'pointcolor' = string with color (e.g. 'k'), or an NX3 matrix of RGB values + 'pointsize' = scalar or vector for marker size + The default marker is a blue dot sorrunded by a yellow circle. + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'hpos' = horizontal position of the lower left corner of the local axes + 'vpos' = vertical position of the lower left corner of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + + See also FT_PREPARE_LAYOUT, FT_PLOT_TOPO + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_layout.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_line` + +```{text} + FT_PLOT_LINE helper function for plotting a line, which can also be used in + combination with the multiple channel layout display in FieldTrip. + + Use as + ft_plot_line(X, Y, ...) + + Optional arguments should come in key-value pairs and can include + 'color' = + 'linestyle' = + 'linewidth' = + 'tag' = string, the tag assigned to the plotted elements (default = '') + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'hpos' = horizontal position of the center of the local axes + 'vpos' = vertical position of the center of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + 'hlim' = horizontal scaling limits within the local axes + 'vlim' = vertical scaling limits within the local axes + + See also FT_PLOT_BOX, FT_PLOT_CROSSHAIR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_line.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_matrix` + +```{text} + FT_PLOT_MATRIX visualizes a matrix as an image, similar to IMAGESC. + The position, width and height can be controlled to allow multiple + matrices (i.e. channels) to be plotted in a topographic arrangement. + + Use as + ft_plot_matrix(C, ...) + where C is a 2 dimensional MxN matrix, or + ft_plot_matrix(X, Y, C, ...) + where X and Y describe the 1xN horizontal and 1xM vertical axes + respectively. + + Optional arguments should come in key-value pairs and can include + 'clim' = 1x2 vector with color limits (default is automatic) + 'highlight' = a logical matrix of size C, where 0 means that the corresponding values in C are highlighted according to the highlightstyle + 'highlightstyle' = can be 'saturation', 'opacity', 'outline' or 'colormix' (default = 'opacity') + 'tag' = string, the tag assigned to the plotted elements (default = '') + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'box' = draw a box around the local axes, can be 'yes' or 'no' + 'hpos' = horizontal position of the center of the local axes + 'vpos' = vertical position of the center of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + 'hlim' = horizontal scaling limits within the local axes + 'vlim' = vertical scaling limits within the local axes + + When using a local pseudo-axis, you can plot a label next to the data + 'label' = string, label to be plotted at the upper left corner + 'fontcolor' = string, color specification (default = 'k') + 'fontsize' = number, sets the size of the text (default = 10) + 'fontunits' = + 'fontname' = + 'fontweight' = + + Example + ft_plot_matrix(randn(30,50), 'width', 1, 'height', 1, 'hpos', 0, 'vpos', 0) + + See also FT_PLOT_VECTOR, IMAGESC, SURF + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_mesh` + +```{text} + FT_PLOT_MESH visualizes a surface or volumetric mesh, for example with the cortical + folding of the brain, or the scalp surface of the head. Surface meshes are + described by triangles and consist of a structure with the fields "pos" and "tri". + Volumetric meshes are described with tetraheders or hexaheders and have the fields + "pos" and "tet" or "hex". + + Use as + ft_plot_mesh(mesh, ...) + or if you only want to plot the 3-D vertices + ft_plot_mesh(pos, ...) + + Optional arguments should come in key-value pairs and can include + 'facecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx3 or Nx1 array where N is the number of faces + 'vertexcolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx3 or Nx1 array where N is the number of vertices + 'edgecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r' + 'faceindex' = true or false (default = false) + 'vertexindex' = true or false (default = false) + 'facealpha' = transparency, between 0 and 1 (default = 1) + 'edgealpha' = transparency, between 0 and 1 (default = 1) + 'surfaceonly' = true or false, plot only the outer surface of a hexahedral or tetrahedral mesh (default = false) + 'vertexmarker' = character, e.g. '.', 'o' or 'x' (default = '.') + 'vertexsize' = scalar or vector with the size for each vertex (default = 10) + 'unit' = string, convert to the specified geometrical units (default = []) + 'axes' = boolean, whether to plot the axes of the 3D coordinate system (default = false) + 'maskstyle' = 'opacity' or 'colormix', if the latter is specified, opacity masked color values + are converted (in combination with a background color) to RGB. This bypasses + openGL functionality, which behaves unpredictably on some platforms (e.g. when + using software opengl) + 'fontsize' = number, sets the size of the text (default = 10) + 'fontunits' = + 'fontname' = + 'fontweight' = + 'tag' = string, the tag assigned to the plotted elements (default = '') + + If you don't want the faces, edges or vertices to be plotted, you should specify the color as 'none'. + + Example + [pos, tri] = mesh_sphere(162); + mesh.pos = pos; + mesh.tri = tri; + ft_plot_mesh(mesh, 'facecolor', 'skin', 'edgecolor', 'none') + camlight + + You can plot an additional contour around specified areas using + 'contour' = inside of contour per vertex, either 0 or 1 + 'contourcolor' = string, color specification + 'contourlinestyle' = string, line specification + 'contourlinewidth' = number + + See also FT_PREPARE_MESH, FT_PLOT_SENS, FT_PLOT_HEADSHAPE, FT_PLOT_HEADMODEL, + FT_PLOT_DIPOLE, TRIMESH, PATCH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_mesh.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_montage` + +```{text} + FT_PLOT_MONTAGE makes a montage of a 3-D array by selecting slices at regular distances + and combining them in one large 2-D image. Note that the montage of MRI slices is not to + be confused with the EEG montage, which is a way of specifying the reference scheme + between electrodes. + + Use as + ft_plot_montage(dat, ...) + where dat is a 3-D array. + + Additional options should be specified in key-value pairs and can be + 'transform' = 4x4 homogeneous transformation matrix specifying the mapping from voxel space to the coordinate system in which the data are plotted. + 'location' = 1x3 vector specifying a point on the plane which will be plotted, the coordinates are expressed in the coordinate system in which the data will be plotted. location defines the origin of the plane + 'orientation' = 1x3 vector specifying the direction orthogonal through the plane which will be plotted (default = [0 0 1]) + 'srange' = + 'slicesize' = + 'nslice' = scalar, number of slices + 'maskstyle' = string, 'opacity' or 'colormix', defines the rendering + 'background' = needed when maskstyle is 'colormix', 3D-matrix with + the same size as the data matrix, serving as + grayscale image that provides the background + + See also FT_PLOT_ORTHO, FT_PLOT_SLICE, FT_SOURCEPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_montage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_ortho` + +```{text} + FT_PLOT_ORTHO plots three orthographic slices through a 3-D volume and interpolates + the data if needed. + + Use as + ft_plot_ortho(dat, ...) + or + ft_plot_ortho(dat, mask, ...) + where dat and mask are equal-sized 3-D arrays. + + Additional options should be specified in key-value pairs and can be + 'style' = string, 'subplot' or 'intersect' (default = 'subplot') + 'orientation' = 3x3 matrix specifying the directions orthogonal through the planes which will be plotted + 'parents' = (optional) 3-element vector containing the handles of the axes for the subplots (when style = 'subplot') + 'surfhandle' = (optional) 3-element vector containing the handles of the surfaces for each of the sublots (when style = 'subplot'). Parents and surfhandle are mutually exclusive + 'update' = (optional) 3-element boolean vector with the axes that should be updated (default = [true true true]) + 'coordsys' = string, assume the data to be in the specified coordinate system (default = 'unknown') + + The following options are supported and passed on to FT_PLOT_SLICE + 'clim' = [min max], lower and upper color limits + 'facealpha' = transparency when no mask is specified, between 0 and 1 (default = 1) + 'transform' = 4x4 homogeneous transformation matrix specifying the mapping from voxel space to the coordinate system in which the data are plotted + 'location' = 1x3 vector specifying the intersection point at which the three slices will be plotted. The coordinates should be expressed in the coordinate system of the data. + 'datmask' = 3D-matrix with the same size as the matrix dat, serving as opacitymap if the second input argument to the function contains a matrix, this will be used as the mask + 'maskstyle' = string, 'opacity' or 'colormix', defines the rendering + 'background' = needed when maskstyle is 'colormix', 3D-matrix with the same size as the data matrix, serving as grayscale image that provides the background + 'interpmethod' = string specifying the method for the interpolation, see INTERPN (default = 'nearest') + 'colormap' = string, see COLORMAP + 'unit' = string, can be 'm', 'cm' or 'mm' (default is automatic) + 'intersectmesh' = triangulated mesh, see FT_PREPARE_MESH + 'intersectcolor' = string, color specification + 'intersectlinestyle' = string, line specification + 'intersectlinewidth' = number + + See also FT_PLOT_SLICE, FT_PLOT_MONTAGE, FT_PLOT_MESH, FT_SOURCEPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_ortho.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_patch` + +```{text} + FT_PLOT_PATCH plot a colored shape, similar to the MATLAB patch() function. It is + similar in usage as ft_plot_vector, and they can be combined, for example, + to plot an area equivalent to a SEM or STD-DEV around a line. + + Use as + ft_plot_patch(X, Y, ...) + where X and Y are similar as the input to the MATLAB patch() function. + + Optional arguments should come in key-value pairs and can include + 'axis' = draw the local axis, can be 'yes', 'no', 'xy', 'x' or 'y' + 'parent' = handle which is set as the parent for the plotted elements (default = []) + 'tag' = string, the tag assigned to the plotted elements (default = '') + 'facecolor' = see MATLAB standard patch properties + 'facealpha' = see MATLAB standard patch properties (note, approx. transparency can be achieved using 'facecolor') + 'edgecolor' = see MATLAB standard patch properties (default is 'none') (equivalent to 'linecolor' in PLOT) + 'linestyle' = see MATLAB standard patch properties + 'linewidth' = see MATLAB standard patch properties + + The color of the patchand the edges (i.e. border lines) can be specified in a variety of ways + - as a string with one character per line that you want to plot. Supported colors are the same as in PATCH, i.e. 'bgrcmykw'. + - as an 'RGB triplet', a 1x3 vector with values between 0 and 1 + - as 'none' if you do not want the face of the patch to be filled (useful when you want to plot an empty box). + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'box' = draw a box around the local axes, can be 'yes' or 'no' + 'hpos' = horizontal position of the center of the local axes + 'vpos' = vertical position of the center of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + 'hlim' = horizontal scaling limits within the local axes + 'vlim' = vertical scaling limits within the local axes + + Example + hdat = [1:10 10:-1:1]; + vdat = rand(1,10); + vdat = [vdat vdat(end:-1:1)+1]; + ft_plot_patch(hdat, vdat) + + See also FT_PLOT_VECTOR, PATCH, PLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_patch.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_sens` + +```{text} + FT_PLOT_SENS visualizes the EEG, MEG or NIRS sensor array. + + Use as + ft_plot_sens(sens, ...) + where the first argument is the sensor array as returned by FT_READ_SENS or + by FT_PREPARE_VOL_SENS. + + Optional input arguments should come in key-value pairs and can include + 'label' = show the label, can be 'off', 'label', 'number' (default = 'off') + 'chantype' = string or cell-array with strings, for example 'meg' (default = 'all') + 'unit' = string, convert the sensor array to the specified geometrical units (default = []) + 'axes' = boolean, whether to plot the axes of the 3D coordinate system (default = false) + 'fontcolor' = string, color specification (default = 'k') + 'fontsize' = number, sets the size of the text (default = 10) + 'fontunits' = + 'fontname' = + 'fontweight' = + + The following options apply to MEG magnetometers and/or gradiometers + 'coil' = true/false, plot each individual coil (default = false) + 'orientation' = true/false, plot a line for the orientation of each coil (default = false) + 'coilshape' = 'point', 'circle', 'square', 'sphere', or 'disc' (default is automatic) + 'coilsize' = diameter or edge length of the coils (default is automatic) + The following options apply to EEG electrodes + 'elec' = true/false, plot each individual electrode (default = false) + 'orientation' = true/false, plot a line for the orientation of each electrode (default = false) + 'elecshape' = 'point', 'circle', 'square', 'sphere', or 'disc' (default is automatic) + 'elecsize' = diameter of the electrodes (default is automatic) + 'headshape' = headshape, required for elecshape 'disc' + The following options apply to NIRS optodes + 'opto' = true/false, plot each individual optode (default = false) + 'orientation' = true/false, plot a line for the orientation of each optode (default = false) + 'optoshape' = 'point', 'circle', 'square', 'sphere', or 'disc' (default is automatic) + 'optosize' = diameter of the optodes (default is automatic) + 'headshape' = headshape, required for optoshape 'disc' + + The following options apply when electrodes/coils/optodes are NOT plotted individually + 'style' = plotting style for the points representing the channels, see plot3 (default = []) + 'marker' = marker type representing the channels, see plot3 (default = '.') + The following options apply when electrodes/coils/optodes are plotted individually + 'facecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx3 or Nx1 array where N is the number of faces (default is automatic) + 'edgecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', color of channels or coils (default is automatic) + 'facealpha' = transparency, between 0 and 1 (default = 1) + 'edgealpha' = transparency, between 0 and 1 (default = 1) + + The sensor array can include an optional fid field with fiducials, which will also be plotted. + 'fiducial' = rue/false, plot the fiducials (default = true) + 'fidcolor' = [r g b] values or string, for example 'red', 'r', or an Nx3 or Nx1 array where N is the number of fiducials + 'fidmarker' = ['.', '*', '+', ...] + 'fidlabel' = ['yes', 'no', 1, 0, 'true', 'false'] + + Example: + sens = ft_read_sens('Subject01.ds', 'senstype', 'meg'); + figure; ft_plot_sens(sens, 'coilshape', 'point', 'style', 'r*') + figure; ft_plot_sens(sens, 'coilshape', 'circle') + figure; ft_plot_sens(sens, 'coilshape', 'circle', 'coil', true, 'chantype', 'meggrad') + figure; ft_plot_sens(sens, 'coilshape', 'circle', 'coil', false, 'orientation', true) + + See also FT_DATATYPE_SENS, FT_READ_SENS, FT_PLOT_HEADSHAPE, FT_PLOT_HEADMODEL, + FT_PLOT_TOPO3D + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_sens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_slice` + +```{text} + FT_PLOT_SLICE plots a single slice that cuts through a 3-D volume and interpolates + the data if needed. + + Use as + ft_plot_slice(dat, ...) + or + ft_plot_slice(dat, mask, ...) + where dat and mask are equal-sized 3-D arrays. + + Additional options should be specified in key-value pairs and can be + 'transform' = 4x4 homogeneous transformation matrix specifying the mapping from + voxel coordinates to the coordinate system in which the data are plotted. + 'location' = 1x3 vector specifying a point on the plane which will be plotted + the coordinates are expressed in the coordinate system in which the + data will be plotted. location defines the origin of the plane + 'orientation' = 1x3 vector specifying the direction orthogonal through the plane + which will be plotted (default = [0 0 1]) + 'unit' = string, can be 'm', 'cm' or 'mm' (default is automatic) + 'coordsys' = string, assume the data to be in the specified coordinate system (default = 'unknown') + 'resolution' = number (default = 1 mm) + 'datmask' = 3D-matrix with the same size as the data matrix, serving as opacitymap + If the second input argument to the function contains a matrix, this + will be used as the mask + 'maskstyle' = string, 'opacity' or 'colormix', defines the rendering + 'background' = needed when maskstyle is 'colormix', 3D-matrix with + the same size as the data matrix, serving as + grayscale image that provides the background + 'opacitylim' = 1x2 vector specifying the limits for opacity masking + 'interpmethod' = string specifying the method for the interpolation, see INTERPN (default = 'nearest') + 'colormap' = string, see COLORMAP + 'clim' = 1x2 vector specifying the min and max for the colorscale + 'facealpha' = transparency when no mask is specified, between 0 and 1 (default = 1) + 'tag' = string, the tag assigned to the plotted elements (default = '') + + You can plot the slices from the volume together with an intersection of the slices + with a triangulated surface mesh (e.g. a cortical sheet) using + 'intersectmesh' = triangulated mesh, see FT_PREPARE_MESH + 'intersectcolor' = string, color specification + 'intersectlinestyle' = string, line specification + 'intersectlinewidth' = number + + See also FT_PLOT_ORTHO, FT_PLOT_MONTAGE, FT_SOURCEPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_slice.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_text` + +```{text} + FT_PLOT_TEXT helper function for plotting text, which can also be used in + combination with the multiple channel layout display in FieldTrip. + + Use as + ft_plot_text(X, Y, str, ...) + + Optional arguments should come in key-value pairs and can include + 'fontcolor' = string, color specification (default = 'k') + 'fontsize' = number, sets the size of the text (default = 10) + 'fontunits' = + 'fontname' = + 'fontweight' = + 'horizontalalignment' = + 'verticalalignment' = + 'interpreter' = string, can be 'none', 'tex' or 'latex' (default = 'none') + 'rotation' = + 'tag' = string, the tag assigned to the plotted elements (default = '') + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'hpos' = horizontal position of the center of the local axes + 'vpos' = vertical position of the center of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + 'hlim' = horizontal scaling limits within the local axes + 'vlim' = vertical scaling limits within the local axes + + Example + figure + ft_plot_vector(randn(1,10), rand(1,10), 'hpos', 1, 'vpos', 1, 'width', 0.2, 'height', 0.2, 'box', true) + ft_plot_text(0, 0 , '+', 'hpos', 1, 'vpos', 1, 'width', 0.2, 'height', 0.2) + axis([0 2 0 2]) + + See also FT_PLOT_VECTOR, FT_PLOT_MATRIX, FT_PLOT_LINE, FT_PLOT_BOX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_text.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_topo` + +```{text} + FT_PLOT_TOPO interpolates and plots the 2-D spatial topography of the + potential or field distribution over the head + + Use as + ft_plot_topo(x, y, val, ...) + + Optional arguments should come in key-value pairs and can include + 'gridscale' = scalar, number of points along both directions for interpolation (default = 67) + 'datmask' = vector of same dimensions as val + 'mask' = cell-array with line segments that forms the mask (see FT_PREPARE_LAYOUT) + 'outline' = cell-array with line segments that for the outline (see FT_PREPARE_LAYOUT) + 'isolines' = vector with values for isocontour lines (default = []) + 'interplim' = string, 'sensors' or 'mask' (default = 'sensors') + 'interpmethod' = string, 'nearest', 'linear', 'natural', 'cubic' or 'v4' (default = 'v4') + 'style' = can be 'surf', 'iso', 'isofill', 'surfiso', 'imsat', 'imsatiso', 'colormix' + 'clim' = [min max], limits for color scaling + 'shading' = string, 'none', 'flat', 'interp' (default = 'flat') + 'parent' = handle which is set as the parent for all plots (default = []) + 'tag' = string, the tag assigned to the plotted elements (default = '') + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'box' = draw a box around the local axes, can be 'yes' or 'no' + 'hpos' = horizontal position of the lower left corner of the local axes + 'vpos' = vertical position of the lower left corner of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + 'hlim' = horizontal scaling limits within the local axes + 'vlim' = vertical scaling limits within the local axes + + See also FT_PLOT_TOPO3D, FT_PLOT_LAYOUT, FT_TOPOPLOTER, FT_TOPOPLOTTFR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_topo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_topo3d` + +```{text} + FT_PLOT_TOPO3D visualizes a 3D topographic representation of the electric potential + or magnetic field distribution at the sensor locations. + + Use as + ft_plot_topo3d(pos, val, ...) + where the channel positions are given as a Nx3 matrix and the values are + given as Nx1 vector. + + Optional input arguments should be specified in key-value pairs and can include + 'contourstyle' = string, 'none', 'black', 'color' (default = 'none') + 'isolines' = vector with values at which to draw isocontours, or 'auto' (default = 'auto') + 'facealpha' = scalar, between 0 and 1 (default = 1) + 'refine' = scalar, number of refinement steps for the triangulation, to get a smoother interpolation (default = 0) + 'neighbourdist' = number, maximum distance between neighbouring sensors (default is automatic) + 'unit' = string, 'm', 'cm' or 'mm' (default = 'cm') + 'coordsys' = string, assume the data to be in the specified coordinate system (default = 'unknown') + 'axes' = boolean, whether to plot the axes of the 3D coordinate system (default = false) + + See also FT_PLOT_TOPO, FT_PLOT_SENS, FT_PLOT_MESH, FT_PLOT_HEADSHAPE, + FT_TOPOPLOTER, FT_TOPOPLOTTFR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_topo3d.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_plot_vector` + +```{text} + FT_PLOT_VECTOR visualizes a vector as a line, similar to PLOT. + + Use as + ft_plot_vector(Y, ...) + or as + ft_plot_vector(X, Y, ...) + where X and Y are similar as the input to the MATLAB plot function. + + Optional arguments should come in key-value pairs and can include + 'color' = see MATLAB standard line properties and see below + 'style' = see MATLAB standard line properties + 'linewidth' = see MATLAB standard line properties + 'markersize' = see MATLAB standard line properties + 'markerfacecolor' = see MATLAB standard line properties + 'axis' = draw the local axis, can be 'yes', 'no', 'xy', 'x' or 'y' + 'highlight' = a logical vector of size Y, where 1 means that the corresponding values in Y are highlighted (according to the highlightstyle) + 'highlightstyle' = can be 'box', 'thickness', 'saturation', 'difference' (default='box') + 'facecolor' = color for the highlighted box/difference (default = [0.6 0.6 0.6]) + 'facealpha' = transparency for the highlighted box/difference, between 0 and 1 (default = 1) + 'parent' = handle which is set as the parent for all plots (default = []) + 'tag' = string, the tag assigned to the plotted elements (default = '') + + The line color can be specified in a variety of ways + - as a string with one character per line that you want to plot. Supported colors are the same as in PLOT, i.e. 'bgrcmykw'. + - as 'none' if you do not want the lines to be plotted (useful in combination with the difference highlightstyle). + - as a Nx3 matrix, where N=length(x), to use graded RGB colors along the line + + It is possible to plot the object in a local pseudo-axis (c.f. subplot), which is specfied as follows + 'box' = draw a box around the local axes, can be 'yes' or 'no' + 'hpos' = horizontal position of the center of the local axes + 'vpos' = vertical position of the center of the local axes + 'width' = width of the local axes + 'height' = height of the local axes + 'hlim' = horizontal scaling limits within the local axes + 'vlim' = vertical scaling limits within the local axes + + When using a local pseudo-axis, you can plot a label next to the data + 'label' = string, label to be plotted in the corner of the box + 'labelpos' = string, position for the label (default = 'upperleft') + 'fontcolor' = string, color specification (default = 'k') + 'fontsize' = number, sets the size of the text (default = 10) + 'fontunits' = + 'fontname' = + 'fontweight' = + + Example 1 + subplot(2,1,1); ft_plot_vector(1:100, randn(1,100), 'color', 'r') + subplot(2,1,2); ft_plot_vector(1:100, randn(1,100), 'color', rand(100,3)) + + Example 2 + ft_plot_vector(randn(1,100), 'width', 0.9, 'height', 0.9, 'hpos', 0, 'vpos', 0, 'box', 'yes') + ft_plot_vector(randn(1,100), 'width', 0.9, 'height', 0.9, 'hpos', 1, 'vpos', 0, 'box', 'yes') + ft_plot_vector(randn(1,100), 'width', 0.9, 'height', 0.9, 'hpos', 0, 'vpos', 1, 'box', 'yes') + + Example 3 + x = 1:100; y = hann(100)'; + subplot(3,1,1); ft_plot_vector(x, y, 'highlight', y>0.8, 'highlightstyle', 'box'); + subplot(3,1,2); ft_plot_vector(x, y, 'highlight', y>0.8, 'highlightstyle', 'thickness'); + subplot(3,1,3); ft_plot_vector(x, y, 'highlight', y>0.8, 'highlightstyle', 'saturation'); + + Example 4 + x = 1:100; y = hann(100)'; ymin = 0.8*y; ymax = 1.2*y; + ft_plot_vector(x, [ymin; ymax], 'highlight', ones(size(y)), 'highlightstyle', 'difference', 'color', 'none'); + ft_plot_vector(x, y); + + Example 5 + colormap hot; + rgb = colormap; + rgb = interp1(1:64, rgb, linspace(1,64,100)); + ft_plot_vector(1:100, 'color', rgb); + + See also FT_PLOT_MATRIX, PLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_plot_vector.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_poll_buffer` + +```{text} + FT_POLL_BUFFER is deprecated. + + Please use FT_READ_DATA and FT_READ_EVENT with the 'blocking' and + the 'timeout' options. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_poll_buffer.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_postamble` + +```{text} + FT_POSTAMBLE is a helper function that is included in many of the FieldTrip + functions and which takes care of some general settings and operations at the end + of the function. + + This ft_postamble m-file is a function, but internally it executes a number of + private scripts in the callers workspace. This allows the private script to access + the variables in the callers workspace and behave as if the script were included as + a header file in C-code. + + See also FT_PREAMBLE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_postamble.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preamble` + +```{text} + FT_PREAMBLE is a helper function that is included in many of the FieldTrip + functions and which takes care of some general settings and operations at the + begin of the function. + + This ft_preamble m-file is a function, but internally it executes a + number of private scripts in the callers workspace. This allows the + private script to access the variables in the callers workspace and + behave as if the script were included as a header file in C-code. + + See also FT_POSTAMBLE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_preamble.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_headmodel` + +```{text} + FT_PREPARE_HEADMODEL constructs a volume conduction model from the geometry + of the head. The volume conduction model specifies how currents that are + generated by sources in the brain, e.g. dipoles, are propagated through the + tissue and how these result in externally measureable EEG potentials or MEG + fields. + + FieldTrip implements a variety of forward solutions, partially with internal + code and some of them using external toolboxes or executables. Each of the + forward solutions requires a set of configuration options which are listed + below. This function takes care of all the preparatory steps in the + construction of the volume conduction model and sets it up so that + subsequent computations are efficient and fast. + + Use as + headmodel = ft_prepare_headmodel(cfg) or + headmodel = ft_prepare_headmodel(cfg, mesh) with the output of FT_PREPARE_MESH or FT_READ_HEADSHAPE + headmodel = ft_prepare_headmodel(cfg, seg) with the output of FT_VOLUMESEGMENT + headmodel = ft_prepare_headmodel(cfg, elec) with the output of FT_READ_SENS + headmodel = ft_prepare_headmodel(cfg, sourcemodel) with the output of FT_PREPARE_LEADFIELD + + In general the input to this function is a geometrical description of the + shape of the head and a description of the electrical conductivity. The + geometrical description can be a set of surface points obtained from + fT_READ_HEADSHAPE, a surface mesh that was obtained from FT_PREPARE_MESH or + a segmented anatomical MRI that was obtained from FT_VOLUMESEGMENT. + + The cfg argument is a structure that can contain: + cfg.method = string that specifies the forward solution, see below + cfg.conductivity = a number or a vector containing the conductivities of the compartments + cfg.tissue = a string or integer, to be used in combination with a 'seg' for the + second intput. If 'brain', 'skull', and 'scalp' are fields + present in 'seg', then cfg.tissue need not be specified, as + these are defaults, depending on cfg.method. Otherwise, + cfg.tissue should refer to which field(s) of seg should be used. + + For EEG the following methods are available: + singlesphere analytical single sphere model + concentricspheres analytical concentric sphere model with up to 4 spheres + openmeeg boundary element method, based on the OpenMEEG software + bemcp boundary element method, based on the implementation from Christophe Phillips + dipoli boundary element method, based on the implementation from Thom Oostendorp + asa boundary element method, based on the (commercial) ASA software + simbio finite element method, based on the SimBio software + duneuro finite element method, based on duneuro software + fns finite difference method, based on the FNS software + infinite electric dipole in an infinite homogenous medium + halfspace infinite homogenous medium on one side, vacuum on the other + besa finite element leadfield matrix from BESA + interpolate interpolate the precomputed leadfield + + For MEG the following methods are available: + openmeeg boundary element method, based on the OpenMEEG software + singlesphere analytical single sphere model + localspheres local spheres model for MEG, one sphere per channel + singleshell realisically shaped single shell approximation, based on the implementation from Guido Nolte + infinite magnetic dipole in an infinite vacuum + + Each specific method has its own specific configuration options which are listed below. + + BEMCP, DIPOLI, OPENMEEG + cfg.tissue see above; in combination with 'seg' input + cfg.isolatedsource (optional) + cfg.tempdir (optional) + cfg.tempname (optional) + + CONCENTRICSPHERES + cfg.tissue see above; in combination with 'seg' input + cfg.order (optional) + cfg.fitind (optional) + + LOCALSPHERES + cfg.grad + cfg.tissue see above; in combination with 'seg' input; default options are 'brain' or 'scalp' + cfg.feedback (optional) + cfg.radius (optional) + cfg.maxradius (optional) + cfg.baseline (optional) + + SIMBIO + cfg.conductivity + + DUNEURO + cfg.conductivity An array with the conductivities must be provided. (see above) + cfg.grid_filename Alternatively, a filename for the grid and a filename for the conductivities can be passed. + cfg.tensors_filename " + cfg.duneuro_settings (optional) Additional settings can be provided for duneuro (see http://www.duneuro.org). + + SINGLESHELL + cfg.tissue see above; in combination with 'seg' input; default options are 'brain' or 'scalp' + cfg.order (optional) + + SINGLESPHERE + cfg.tissue see above; in combination with 'seg' input; default options are 'brain' or 'scalp'; must be only 1 value + + INTERPOLATE + cfg.outputfile (required) string, filename prefix for the output files + + BESA + cfg.headmodel (required) string, filename of precomputed FEM leadfield + cfg.elec (required) structure with electrode positions or filename, see FT_READ_SENS + cfg.outputfile (required) string, filename prefix for the output files + + FNS + cfg.tissue + cfg.tissueval + cfg.conductivity + cfg.elec + cfg.grad + cfg.transform + + HALFSPACE + cfg.point + cfg.submethod (optional) + + More details for each of the specific methods can be found in the corresponding + low-level function which is called FT_HEADMODEL_XXX where XXX is the method + of choise. + + See also FT_PREPARE_MESH, FT_PREPARE_SOURCEMODEL, FT_PREPARE_LEADFIELD, + FT_HEADMODEL_BEMCP, FT_HEADMODEL_ASA, FT_HEADMODEL_DIPOLI, + FT_HEADMODEL_SIMBIO, FT_HEADMODEL_FNS, FT_HEADMODEL_HALFSPACE, + FT_HEADMODEL_INFINITE, FT_HEADMODEL_OPENMEEG, FT_HEADMODEL_SINGLESPHERE, + FT_HEADMODEL_CONCENTRICSPHERES, FT_HEADMODEL_LOCALSPHERES, + FT_HEADMODEL_SINGLESHELL, FT_HEADMODEL_INTERPOLATE, FT_HEADMODEL_DUNEURO + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_prepare_headmodel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_layout` + +```{text} + FT_PREPARE_LAYOUT loads or creates a 2-D layout of the channel locations. This + layout is required for plotting the topographical distribution of the potential or + field distribution, or for plotting timecourses in a topographical arrangement. + + Use as + layout = ft_prepare_layout(cfg) + or + layout = ft_prepare_layout(cfg, data) + where the optional data input argument is any of the FieldTrip data structures. + + This returns a layout structure with the following elements + layout.pos = Nx2 matrix with the position where each channel should be plotted + layout.label = Nx1 cell-array with the channel labels + layout.width = Nx1 vector with the width of each box for multiplotting + layout.height = Nx1 vector with the height of each box for multiplotting + layout.mask = optional cell-array with line segments that determine the area for topographic interpolation + layout.outline = optional cell-array with line segments that represent the head, nose, ears, sulci or other anatomical features + layout.color = optional Nx3 matrix with rgb values for the channels' color, for fine-grained color behavior + + There are several ways in which a 2-D layout can be made: + 1) it can be read directly from a layout file + 2) it can be created on basis of an image or photo, + 3) it can be created from a projection of the 3-D sensor positions in the data, in the configuration, or in an electrode, gradiometer or optode file. + + Layout files are MATLAB *.mat files containing a single structure representing the layout + (see above). The layout file can also be an ASCII file with the extension *.lay, although + this file format is no longer recommended, since there is less control over the outline + of the head and the mask within which the interpolation is done. A large number of + template layout files is provided in the fieldtrip/template/layout directory. See + also http://www.fieldtriptoolbox.org/template/layout + + You can specify any one of the following configuration options + cfg.layout = filename containg the input layout (*.mat or *.lay file), this can also be a layout + structure, which is simply returned as-is (see below for details) + cfg.output = filename (ending in .mat or .lay) to which the layout will be written (default = []) + cfg.feedback = 'yes' or 'no', whether to show an image of the layout (default = 'no') + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + cfg.opto = structure with optode definition or filename, see FT_READ_SENS + cfg.rotate = number, rotation around the z-axis in degrees (default = [], which means automatic) + cfg.center = string, center and scale the electrodes in the sphere that represents the head, can be 'yes' or 'no' (default = 'no') + cfg.projection = string, 2D projection method can be 'stereographic', 'orthographic', 'polar' or 'gnomic' (default = 'polar') + When 'orthographic', cfg.viewpoint can be used to indicate to specificy projection (keep empty for legacy projection) + cfg.viewpoint = string indicating the view point that is used for orthographic projection of 3-D sensor + positions to the 2-D plane. The possible viewpoints are + 'left' - left sagittal view, L=anterior, R=posterior, top=top, bottom=bottom + 'right' - right sagittal view, L=posterior, R=anterior, top=top, bottom=bottom + 'topleft' - view from the top top, L=anterior, R=posterior, top=top, bottom=bottom + 'topright' - view from the top right, L=posterior, R=anterior, top=top, bottom=bottom + 'inferior' - inferior axial view, L=R, R=L, top=anterior, bottom=posterior + 'superior' - superior axial view, L=L, R=R, top=anterior, bottom=posterior + 'anterior' - anterior coronal view, L=R, R=L, top=top, bottom=bottom + 'posterior' - posterior coronal view, L=L, R=R, top=top, bottom=bottom + 'auto' - automatic guess of the most optimal of the above + tip: use cfg.viewpoint = 'auto' per iEEG electrode grid/strip/depth for more accurate results + tip: to obtain an overview of all iEEG electrodes, choose superior/inferior, use cfg.headshape/mri, and plot using FT_LAYOUTPLOT with cfg.box/mask = 'no' + cfg.outline = string, how to create the outline, can be 'circle', 'doublecirclecross', 'helmet', 'square', 'convex', 'headshape', 'mri' or 'no' (default is automatic) + cfg.mask = string, how to create the mask, can be 'circle', 'extended', 'square', 'convex', 'headshape', 'mri' or 'no' (default is automatic) + cfg.headshape = surface mesh (for example pial or head) to be used for generating an outline, see FT_READ_HEADSHAPE for details + cfg.mri = segmented anatomical MRI to be used for generating an outline, see FT_READ_MRI and FT_VOLUMESEGMENT for details + cfg.montage = 'no' or a montage structure (default = 'no') + cfg.image = filename, use an image to construct a layout (useful for ECoG grids) + cfg.bw = 'yes' or 'no', if an image is used and this option is true, the image is transformed in black and white (default = 'no', i.e. do not transform) + cfg.overlap = string, how to deal with overlapping channels when the layout is constructed from a sensor configuration structure. This can be + 'shift' - shift the positions in 2D space to remove the overlap (default) + 'keep' - do not shift, retain the overlap + 'no' - throw an error when overlap is present + cfg.channel = 'all', or Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + cfg.boxchannel = 'all', or Nx1 cell-array with selection of channels, see FT_CHANNELSELECTION for details + specificies channels to use for determining channel box size (default = 'all', recommended for MEG/EEG, a selection is recommended for iEEG) + cfg.skipscale = 'yes' or 'no', whether the scale should be included in the layout or not (default = 'no') + cfg.skipcomnt = 'yes' or 'no', whether the comment should be included in the layout or not (default = 'no') + cfg.color = empty, 'spatial', or Nx3 matrix, if non-empty, an Nx3 color matrix based on the position + of the sensors will be added (default = []) + + If you use cfg.headshape or cfg.mri to create a headshape outline, the input + geometry should be expressed in the same units and coordinate system as the input + sensors. + + Alternatively the layout can be constructed from either one of these in the input data structure: + data.elec = structure with electrode positions + data.grad = structure with gradiometer definition + data.opto = structure with optode definition + + Alternatively you can specify the following options for systematic layouts which + will be generated for all channels present in the data. Note that these layouts are + only suitable for multiplotting, not for topoplotting. + cfg.layout = 'ordered' will give you a NxN ordered layout + cfg.layout = 'vertical' will give you a Nx1 ordered layout + cfg.layout = 'horizontal' will give you a 1xN ordered layout + cfg.layout = 'butterfly' will give you a layout with all channels on top of each other + cfg.layout = 'circular' will distribute the channels on a circle + cfg.width = scalar (default is automatic) + cfg.height = scalar (default is automatic) + + For an sEEG shaft the option cfg.layout='vertical' or 'horizontal' is useful to + represent the channels in a linear sequence . In this case you can also specify the + direction of the shaft as going from left-to-right, top-to-bottom, etc. + cfg.direction = string, can be any of 'LR', 'RL' (for horizontal), 'TB', 'BT' (for vertical) + + For an ECoG grid the option cfg.layout='ordered' is useful to represent the + channels in a grid array. In this case you can also specify the number of rows + and/or columns and hwo the channels increment over the grid (e.g. first + left-to-right, then top-to-bottom). You can check the channel order of your grid + using FT_PLOT_LAYOUT. + cfg.rows = number of rows (default is automatic) + cfg.columns = number of columns (default is automatic) + cfg.direction = string, can be any of 'LRTB', 'RLTB', 'LRBT', 'RLBT', 'TBLR', 'TBRL', 'BTLR', 'BTRL' (default = 'LRTB') + + See also FT_TOPOPLOTER, FT_TOPOPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_PLOT_LAYOUT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_prepare_layout.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_leadfield` + +```{text} + FT_PREPARE_LEADFIELD computes the forward model for many dipole locations + on a regular 2D or 3D sourcemodel and stores it for efficient inverse modelling + + Use as + [sourcemodel] = ft_prepare_leadfield(cfg, data) + + It is necessary to input the data on which you want to perform the inverse + computations, since that data generally contain the gradiometer information and + information about the channels that should be included in the forward model + computation. The data structure can be either obtained from FT_PREPROCESSING, + FT_FREQANALYSIS or FT_TIMELOCKANALYSIS. If the data is empty, all channels will be + included in the forward model. + + The configuration should contain + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + + The positions of the sources can be specified as a regular 3-D + sourcemodel that is aligned with the axes of the head coordinate system + cfg.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto') + cfg.resolution = number (e.g. 1 cm) for automatic sourcemodel generation + + Alternatively the position of a few sources at locations of interest can + be specified, for example obtained from an anatomical or functional MRI + cfg.sourcemodel.pos = N*3 matrix with position of each source + cfg.sourcemodel.inside = N*1 vector with boolean value whether sourcemodel point is inside brain (optional) + cfg.sourcemodel.dim = [Nx Ny Nz] vector with dimensions in case of 3-D sourcemodel (optional) + + The volume conduction model of the head should be specified as + cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL + + The EEG or MEG sensor positions can be present in the data or can be specified as + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + + Optionally, you can modify the leadfields by reducing the rank (i.e. remove the + weakest orientation), or by normalizing each column. + cfg.reducerank = 'no', or number (default = 3 for EEG, 2 for MEG) + cfg.backproject = 'yes' or 'no', determines when reducerank is applied whether the + lower rank leadfield is projected back onto the original linear + subspace, or not (default = 'yes') + cfg.normalize = 'yes' or 'no' (default = 'no') + cfg.normalizeparam = depth normalization parameter (default = 0.5) + cfg.weight = number or Nx1 vector, weight for each dipole position to compensate + for the size of the corresponding patch (default = 1) + + Depending on the type of headmodel, some additional options may be + specified. + + For OPENMEEG based headmodels: + cfg.openmeeg.batchsize = scalar (default 1e4), number of dipoles + for which the leadfield is computed in a + single call to the low-level code. Trades off + memory efficiency for speed. + cfg.openmeeg.dsm = 'no'/'yes', reuse existing DSM if provided + cfg.openmeeg.keepdsm = 'no'/'yes', option to retain DSM (no by default) + cfg.openmeeg.nonadaptive = 'no'/'yes' + + For SINGLESHELL based headmodels: + cfg.singleshell.batchsize = scalar or 'all' (default 1), number of dipoles + for which the leadfield is computed in a + single call to the low-level code. Trades off + memory efficiency for speed. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_SOURCEANALYSIS, FT_DIPOLEFITTING, FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_prepare_leadfield.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_mesh` + +```{text} + FT_PREPARE_MESH creates a triangulated surface mesh or tetrahedral/hexahedral + volume mesh that can be used as geometrical description for a volume conduction + model. The mesh can either be created manually from anatomical MRI data or can be + generated starting from a segmented MRI. This function can also be used to create a + cortex hull, i.e. the smoothed envelope around the pial surface created by + freesurfer. + + Use as + mesh = ft_prepare_mesh(cfg) + mesh = ft_prepare_mesh(cfg, mri) + mesh = ft_prepare_mesh(cfg, seg) + where the mri input argument is the result from FT_READ_MRI, FT_VOLUMEREALIGN or + FT_VOLUMERESLICE and the seg input argument is from FT_VOLUMESEGMENT. If you + specify an anatomical MRI, it will be segmented on the fly. + + The cfg argument is a structure that can contain: + cfg.method = string, can be 'interactive', 'projectmesh', 'iso2mesh', 'isosurface', + 'headshape', 'hexahedral', 'tetrahedral', 'cortexhull' or 'fittemplate' + cfg.tissue = cell-array with strings representing the tissue types, or numeric vector with integer values + cfg.numvertices = numeric vector, should have same number of elements as the number of tissues + + When providing an anatomical MRI or a segmentation, you should specify + cfg.downsample = integer number (default = 1, i.e. no downsampling), see FT_VOLUMEDOWNSAMPLE + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + + For method 'headshape' you should specify + cfg.headshape = a filename containing headshape, a Nx3 matrix with surface + points, or a structure with a single or multiple boundaries + + For method 'cortexhull' you should not give input data, but specify + cfg.headshape = string, filename containing the pial surface computed by freesurfer recon-all + + For method 'fittemplate' you should specify + cfg.headshape = a filename containing headshape + cfg.template = a filename containing headshape + With this method you are fitting the headshape from the configuration to the template; + the resulting affine transformation is applied to the input mesh (or set of meshes), + which is subsequently returned as output variable. + + 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. + + Example + mri = ft_read_mri('Subject01.mri'); + + cfg = []; + cfg.output = {'scalp', 'skull', 'brain'}; + segmentation = ft_volumesegment(cfg, mri); + + cfg = []; + cfg.tissue = {'scalp', 'skull', 'brain'}; + cfg.numvertices = [800, 1600, 2400]; + mesh = ft_prepare_mesh(cfg, segmentation); + + cfg = []; + cfg.method = 'cortexhull'; + cfg.headshape = '/path/to/surf/lh.pial'; + cfg.fshome = '/path/to/freesurfer dir'; + cortex_hull = ft_prepare_mesh(cfg); + + See also FT_VOLUMESEGMENT, FT_PREPARE_HEADMODEL, FT_PLOT_MESH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_prepare_mesh.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_montage` + +```{text} + FT_PREPARE_MONTAGE creates a referencing scheme based on the input configuration + options and the channels in the data structure. The resulting montage can be + given as input to FT_APPLY_MONTAGE, or as cfg.montage to FT_PREPROCESSING. + + Use as + montage = ft_prepare_montage(cfg, data) + + The configuration can contain the following fields: + cfg.refmethod = 'avg', 'comp', 'bipolar', 'laplace', 'doublebanana', 'longitudinal', 'circumferential', 'transverse' (default = 'avg') + cfg.implicitref = string with the label of the implicit reference, or empty (default = []) + cfg.refchannel = cell-array with new EEG reference channel(s), this can be 'all' for a common average reference + cfg.groupchans = 'yes' or 'no', should channels be rereferenced in separate groups + for bipolar and laplace methods, this requires channnels to be + named using an alphanumeric code, where letters represent the + group and numbers represent the order of the channel whithin + its group (default = 'no') + + The implicitref option allows adding the implicit reference channel to the data as + a channel with zeros. + + The resulting montage is a structure with the fields + montage.tra = MxN matrix + montage.labelold = Nx1 cell-array + montage.labelnew = Mx1 cell-array + + As an example, an output bipolar montage could look like this + bipolar.labelold = {'1', '2', '3', '4'} + bipolar.labelnew = {'1-2', '2-3', '3-4'} + bipolar.tra = [ + +1 -1 0 0 + 0 +1 -1 0 + 0 0 +1 -1 + ]; + + See also FT_PREPROCESSING, FT_APPLY_MONTAGE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_prepare_montage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_neighbours` + +```{text} + FT_PREPARE_NEIGHBOURS finds the channel neighbours for spatial clustering + or interpolation of bad channels. Using the 'distance' method, neighbours + are based on a minimum neighbourhood distance (in cfg.neighbourdist). + Using the 'triangulation' method calculates a triangulation based on a 2D + projection of the sensor positions. The 'template' method loads a default + template for the given data type. Alternatively, using the 'parcellation' + method, in combination with an atlas as input data, spatial neighbours + of parcels are determined, based on the spatial relationship between the + labeled mesh vertices. Currently, only atlases defined on a triangular + mesh are supported. + + Use as + neighbours = ft_prepare_neighbours(cfg) + or + neighbours = ft_prepare_neighbours(cfg, data) + with an input data structure with the channels of interest and that + contains a sensor description, or represents an atlas, see FT_READ_ATLAS + + The configuration can contain + cfg.channel = channels in the data for which neighbours should be determined + cfg.method = 'distance', 'triangulation' or 'template' + cfg.template = name of the template file, e.g. CTF275_neighb.mat + cfg.neighbourdist = number, maximum distance between neighbouring sensors + (only for 'distance', default is 40 mm) + cfg.compress = 'yes' or 'no', add extra edges by compressing in the + x- and y-direction (only for 'triangulation', default is yes) + cfg.feedback = 'yes' or 'no' (default = 'no') + + The 3D sensor positions can be present in the data or can be specified as + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + + The 2D channel positions can be specified as + cfg.layout = filename of the layout, see FT_PREPARE_LAYOUT + + With an atlas in the input, the method 'parcellation' has the additional + options + cfg.parcellation = string that denotes the field in the atlas that is to be used + + The output is an array of structures with the "neighbours" which is + structured like this: + neighbours(1).label = 'Fz'; + neighbours(1).neighblabel = {'Cz', 'F3', 'F3A', 'FzA', 'F4A', 'F4'}; + neighbours(2).label = 'Cz'; + neighbours(2).neighblabel = {'Fz', 'F4', 'RT', 'RTP', 'P4', 'Pz', 'P3', 'LTP', 'LT', 'F3'}; + neighbours(3).label = 'Pz'; + neighbours(3).neighblabel = {'Cz', 'P4', 'P4P', 'Oz', 'P3P', 'P3'}; + etc. + + Note that a channel is not considered to be a neighbour of itself. + + See also FT_NEIGHBOURPLOT, FT_PREPARE_LAYOUT, FT_DATATYPE_SENS, + FT_READ_SENS, FT_READ_ATLAS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_prepare_neighbours.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_sourcemodel` + +```{text} + FT_PREPARE_SOURCEMODEL constructs a source model, for example a 3D grid or a + cortical sheet. The source model that can be used for source reconstruction, + beamformer scanning, linear estimation and MEG interpolation. + + Use as + sourcemodel = ft_prepare_sourcemodel(cfg) + where the details of the configuration structure determine how the source + model will be constructed. + + The different approaches for constructing a source model are + cfg.method = 'basedongrid' regular 3D grid with explicit specification + 'basedonresolution' regular 3D grid with specification of the resolution + 'basedonpos' place dipoles at the predefined positions + 'basedonmri' regular 3D grid, based on segmented MRI, restricted to gray matter + 'basedonmni' regular 3D grid, based on a warped template grid, based on the MNI brain + 'basedoncortex' cortical sheet from external software such as Caret or FreeSurfer, can also be two separate hemispheres + 'basedonshape' surface mesh based on inward shifted head surface from an external file + 'basedonvol' surface mesh based on inward shifted brain surface from volume conductor + 'basedonfile' the sourcemodel should be read from file + 'basedoncentroids' irregular 3D grid based on volumetric mesh + The default method is determined automatically based on the configuration options + that you specify. + + BASEDONGRID - uses an explicitly specified grid, according to the following + configuration options: + cfg.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto') + + BASEDONRESOLUTION - uses an grid with the desired resolution, according + to the following configuration options: + cfg.resolution = number (e.g. 1 cm) for automatic grid generation + + BASEDONPOS - places sources on positions that you explicitly specify, according to + the following configuration options: + cfg.sourcemodel.pos = N*3 matrix with position of each source + cfg.sourcemodel.inside = N*1 vector with boolean value whether position is inside brain (optional) + cfg.sourcemodel.dim = [Nx Ny Nz] vector with dimensions in case of 3D grid (optional) + The following fields (from FT_PRERARE_LEADFIELD or FT_SOURCEANALYSIS) are + not used in this function, but will be copied along to the output: + cfg.sourcemodel.leadfield = cell-array + cfg.sourcemodel.filter = cell-array + cfg.sourcemodel.subspace + cfg.sourcemodel.lbex + + BASEDONMNI - uses source positions from a template sourcemodel that is inversely + warped from MNI coordinates to the individual subjects MRI. It uses the following + configuration options: + cfg.mri = structure with the anatomical MRI, or the filename of the MRI, see FT_READ_MRI + cfg.nonlinear = 'no' (or 'yes'), use non-linear normalization + cfg.resolution = number (e.g. 6) of the resolution of the template MNI grid, defined in mm + cfg.template = structure with the template sourcemodel, or the filename of a template sourcemodel (defined in MNI space) + cfg.templatemri = string, filename of the MNI template (default = 'T1.mnc' for SPM2 or 'T1.nii' for SPM8 and SPM12) + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + cfg.spmmethod = string, 'old', 'new' or 'mars', see FT_VOLUMENORMALISE + cfg.nonlinear = string, 'yes' or 'no', see FT_VOLUMENORMALISE + Either cfg.resolution or cfg.template needs to be defined; if both are defined, cfg.template prevails. + + BASEDONMRI - makes a segmentation of the individual anatomical MRI and places + sources in the grey matter. It uses the following configuration options: + cfg.mri = can be filename, MRI structure or segmented MRI structure + cfg.threshold = 0.1, relative to the maximum value in the segmentation + cfg.smooth = 5, smoothing in voxels + + BASEDONCORTEX - places sources on the vertices of a cortical surface description + cfg.headshape = string, should be a *.fif file + + BASEDONCENTROIDS - places sources on the centroids of a volumetric mesh + cfg.headmodel = tetrahedral or hexahedral mesh + cfg.headmodel.type = 'simbio'; + + Other configuration options include + cfg.unit = string, can be 'mm', 'cm', 'm' (default is automatic) + cfg.tight = 'yes' or 'no' (default is automatic) + cfg.inwardshift = number, amount to shift the innermost surface of the headmodel inward when determining + whether sources are inside or outside the source compartment (default = 0) + cfg.moveinward = number, amount to move sources inward to ensure a certain minimal distance to the innermost + surface of the headmodel (default = 0) + cfg.movetocentroids = 'yes' or 'no', move the dipoles to the centroids of the hexahedral + or tetrahedral mesh (default = 'no') + cfg.spherify = 'yes' or 'no', scale the source model so that it fits inside a sperical + volume conduction model (default = 'no') + cfg.symmetry = 'x', 'y' or 'z' symmetry for two dipoles, can be empty (default = []) + cfg.headshape = a filename for the headshape, a structure containing a single surface, + or a Nx3 matrix with headshape surface points (default = []) + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + + The EEG or MEG sensor positions can be present in the data or can be specified as + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + + The headmodel or volume conduction model can be specified as + cfg.headmodel = structure with volume conduction model or filename, see FT_PREPARE_HEADMODEL + + The cfg.inwardshift option can be used for 3D grids to specify a positive (inward) + or negative (outward) number to shift the innermost surface of the headmodel + (usually the skull) when determining whether sources are to be flagged as inside or + outside the source compartment. Only sources flagged as inside will be considered + for subsequent source reconstructions. An ourward shift can be useful for a + spherical or singleshell MEG headmodel. For a source model based on a cortical + sheet in general you want all sources to be considered inside. For a BEM headmodel + (EEG or MEG), there should never be any sources outside the actual source + compartment. + + The cfg.moveinward option can be used for a source model based on a cortical sheet + to push the sources inward a little bit to ensure sufficient distance to the + innermost surface of a BEM headmodel (EEG or MEG). + + See also FT_PREPARE_LEADFIELD, FT_PREPARE_HEADMODEL, FT_SOURCEANALYSIS, + FT_DIPOLEFITTING, FT_MEGREALIGN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_prepare_sourcemodel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_prepare_vol_sens` + +```{text} + FT_PREPARE_VOL_SENS does some bookkeeping to ensure that the volume conductor model + and the sensor array are ready for subsequent forward leadfield computations and + takes care of some pre-computations to make the calculations more efficient. + + Use as + [headmodel, sens] = ft_prepare_vol_sens(headmodel, sens, ...) + with input arguments + headmodel = structure with volume conductor definition + sens = structure with gradiometer or electrode definition + + The headmodel structure represents a volume conductor model of the head, + its contents depend on the type of model. It is described in more detail + in FT_DATATYPE_HEADMODEL. The sens structure represents a electrode or + gradiometer array. It is described in more detail in FT_DATATYPE_SENS. + + Additional options should be specified in key-value pairs and can be + 'channel' = cell-array with strings (default = 'all') + + The detailed behavior of this function depends on whether the input + consists of EEG or MEG and furthermoree depends on the type of volume + conductor model: + - in case of EEG single and concentric sphere models, the electrodes are + projected onto the skin surface. + - in case of EEG boundary element models, the electrodes are projected on + the surface and a blilinear interpoaltion matrix from vertices to + electrodes is computed. + - in case of MEG and a localspheres model, a local sphere is determined + for each coil in the gradiometer definition. + - in case of MEG with a singleshell Nolte model, the volume conduction + model is initialized + In any case channel selection and reordering will be done. The channel + order returned by this function corresponds to the order in the 'channel' + option, or if not specified, to the order in the input sensor array. + + See also FT_COMPUTE_LEADFIELD, FT_READ_HEADMODEL, FT_READ_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_prepare_vol_sens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_bandpassfilter` + +```{text} + FT_PREPROC_BANDPASSFILTER applies a band-pass filter to the data and thereby + removes the spectral components in the data except for the ones in the + specified frequency band. + + Use as + [filt] = ft_preproc_bandpassfilter(dat, Fs, Fbp, order, type, dir, instabilityfix, df, wintype, dev, plotfiltresp, usefftfilt) + where + dat data matrix (Nchans X Ntime) + Fs sampling frequency in Hz + Fbp frequency band, specified as [Fhp Flp] in Hz + order optional filter order, default is 4 (but) or dependent on frequency band and data length (fir/firls) + type optional filter type, can be + 'but' Butterworth IIR filter (default) + 'firws' FIR filter with windowed sinc + 'fir' FIR filter using MATLAB fir1 function + 'firls' FIR filter using MATLAB firls function (requires MATLAB Signal Processing Toolbox) + 'brickwall' frequency-domain filter using forward and inverse FFT + dir optional filter direction, can be + 'onepass' forward filter only + 'onepass-reverse' reverse filter only, i.e. backward in time + 'onepass-zerophase' zero-phase forward filter with delay compensation (default for firws, linear-phase symmetric FIR only) + 'onepass-reverse-zerophase' zero-phase reverse filter with delay compensation + 'onepass-minphase' minimum-phase converted forward filter (non-linear, only for firws) + 'twopass' zero-phase forward and reverse filter (default, except for firws) + 'twopass-reverse' zero-phase reverse and forward filter + 'twopass-average' average of the twopass and the twopass-reverse + instabilityfix optional method to deal with filter instabilities + 'no' only detect and give error (default) + 'reduce' reduce the filter order + 'split' split the filter in two lower-order filters, apply sequentially + df optional transition width (only for firws) + wintype optional window type (only for firws), can be + 'hamming' (default) maximum passband deviation 0.0022 [0.22%], stopband attenuation -53dB + 'hann' maximum passband deviation 0.0063 [0.63%], stopband attenuation -44dB + 'blackman' maximum passband deviation 0.0002 [0.02%], stopband attenuation -74dB + 'kaiser' + dev optional max passband deviation/stopband attenuation (only for firws with kaiser window, default = 0.001 [0.1%, -60 dB]) + plotfiltresp optional, 'yes' or 'no', plot filter responses (only for firws, default = 'no') + usefftfilt optional, 'yes' or 'no', use fftfilt instead of filter (only for firws, default = 'no') + + Note that a one- or two-pass filter has consequences for the strength of the + filter, i.e. a two-pass filter with the same filter order will attenuate the signal + twice as strong. + + Further note that the filter type 'brickwall' filters in the frequency domain, + but may have severe issues. For instance, it has the implication that the time + domain signal is periodic. Another issue pertains to that frequencies are + not well defined over short time intervals; particularly for low frequencies. + + If the data contains NaNs, these will affect the output. With an IIR + filter, and/or with FFT-filtering, local NaNs will spread to the whole + time series. With a FIR filter, local NaNs will spread locally, depending + on the filter order. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_bandpassfilter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_bandstopfilter` + +```{text} + FT_PREPROC_BANDSTOPFILTER applies a band-stop filter to the data and thereby + removes the spectral components in the specified frequency band + + Use as + [filt] = ft_preproc_bandstopfilter(dat, Fs, Fbp, order, type, dir, instabilityfix, df, wintype, dev, plotfiltresp, usefftfilt) + where + dat data matrix (Nchans X Ntime) + Fs sampling frequency in Hz + Fbp frequency band, specified as [Fhp Flp] in Hz + N optional filter order, default is 4 (but) or dependent on frequency band and data length (fir/firls) + type optional filter type, can be + 'but' Butterworth IIR filter (default) + 'firws' FIR filter with windowed sinc + 'fir' FIR filter using MATLAB fir1 function + 'firls' FIR filter using MATLAB firls function (requires MATLAB Signal Processing Toolbox) + 'brickwall' frequency-domain filter using forward and inverse FFT + dir optional filter direction, can be + 'onepass' forward filter only + 'onepass-reverse' reverse filter only, i.e. backward in time + 'onepass-zerophase' zero-phase forward filter with delay compensation (default for firws, linear-phase symmetric FIR only) + 'onepass-reverse-zerophase' zero-phase reverse filter with delay compensation + 'onepass-minphase' minimum-phase converted forward filter (non-linear, only for firws) + 'twopass' zero-phase forward and reverse filter (default, except for firws) + 'twopass-reverse' zero-phase reverse and forward filter + 'twopass-average' average of the twopass and the twopass-reverse + instabilityfix optional method to deal with filter instabilities + 'no' only detect and give error (default) + 'reduce' reduce the filter order + 'split' split the filter in two lower-order filters, apply sequentially + df optional transition width (only for firws) + wintype optional window type (only for firws), can be + 'hamming' (default) maximum passband deviation 0.0022 [0.22%], stopband attenuation -53dB + 'hann' maximum passband deviation 0.0063 [0.63%], stopband attenuation -44dB + 'blackman' maximum passband deviation 0.0002 [0.02%], stopband attenuation -74dB + 'kaiser' + dev optional max passband deviation/stopband attenuation (only for firws with kaiser window, default = 0.001 [0.1%, -60 dB]) + plotfiltresp optional, 'yes' or 'no', plot filter responses (only for firws, default = 'no') + usefftfilt optional, 'yes' or 'no', use fftfilt instead of filter (only for firws, default = 'no') + + Note that a one- or two-pass filter has consequences for the strength of the + filter, i.e. a two-pass filter with the same filter order will attenuate the signal + twice as strong. + + Further note that the filter type 'brickwall' filters in the frequency domain, + but may have severe issues. For instance, it has the implication that the time + domain signal is periodic. Another issue pertains to that frequencies are + not well defined over short time intervals; particularly for low frequencies. + + If the data contains NaNs, these will affect the output. With an IIR + filter, and/or with FFT-filtering, local NaNs will spread to the whole + time series. With a FIR filter, local NaNs will spread locally, depending + on the filter order. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_bandstopfilter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_baselinecorrect` + +```{text} + FT_PREPROC_BASELINECORRECT performs a baseline correction, e.g. using the + prestimulus interval of the data or using the complete data + + Use as + [dat] = ft_preproc_baselinecorrect(dat, begin, end) + where + dat data matrix (Nchans X Ntime) + begsample index of the begin sample for the baseline estimate + endsample index of the end sample for the baseline estimate + + If no begin and end sample are specified for the baseline estimate, it + will be estimated on the complete data. + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also FT_PREPROC_DETREND, FT_PREPROC_POLYREMOVAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_baselinecorrect.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_denoise` + +```{text} + FT_PREPROC_DENOISE performs a regression of the matrix dat onto refdat, and + subtracts the projected data. This is for the purpose of removing signals generated + by coils during continuous head motion tracking, for example. + + Use as + [dat] = ft_preproc_denoise(dat, refdat, hilbertflag) + where + dat data matrix (Nchan1 X Ntime) + refdat data matrix (Nchan2 X Ntime) + hilbertflag boolean, regress out the real and imaginary parts of the Hilbert + transformed signal, this is only meaningful for narrow band + reference data (default = false) + + The number of channels of the data and reference data does not have to be the same. + + If the data contains NaNs, the output of the affected channel(s) will be all NaN. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_denoise.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_derivative` + +```{text} + FT_PREPROC_DERIVATIVE computes the temporal Nth order derivative of the + data + + Use as + [dat] = ft_preproc_derivative(dat, order, deltat) + where + dat data matrix (Nchans X Ntime) + order number representing the Nth derivative (default = 1) + deltat number representing the duration of 1 time step in the data + (default = 1) + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_derivative.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_detrend` + +```{text} + FT_PREPROC_DETREND removes mean and linear trend from the + data using using a General Linear Modeling approach. + + Use as + [dat] = ft_preproc_detrend(dat, begin, end) + where + dat = data matrix (Nchans X Ntime) + begsample = index of the begin sample for the trend estimate + endsample = index of the end sample for the trend estimate + + If no begin and end sample are specified for the trend estimate, it + will be estimated on the complete data. + + See also FT_PREPROC_BASELINECORRECT, FT_PREPROC_POLYREMOVAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_detrend.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_dftfilter` + +```{text} + FT_PREPROC_DFTFILTER reduces power line noise (50 or 60Hz) using a + discrete Fourier transform (DFT) filter, or spectrum interpolation. + + Use as + [filt] = ft_preproc_dftfilter(dat, Fsample) + or + [filt] = ft_preproc_dftfilter(dat, Fsample, Fline) + or + [filt] = ft_preproc_dftfilter(dat, Fsample, Fline, 'dftreplace', 'zero') + or + [filt] = ft_preproc_dftfilter(dat, Fsample, Fline, 'dftreplace', 'neighbour') + where + dat data matrix (Nchans X Ntime) + Fsample sampling frequency in Hz + Fline frequency of the power line interference (if omitted from the input + the default European value of 50 Hz is assumed) + + Additional optional arguments are to be provided as key-value pairs: + dftreplace = 'zero' (default), 'neighbour' or 'neighbour_fft'. + + If dftreplace = 'zero', the powerline component's amplitude is estimated by + fitting a sine and cosine at the specified frequency, and subsequently + this fitted signal is subtracted from the data. The longer the sharper + the spectral notch will be that is removed from the data. + Preferably the data should have a length that is an integer multiple of the + oscillation period of the line noise (i.e. 20ms for 50Hz noise). If the + data is of different length, then only the first N complete periods are + used to estimate the line noise. The estimate is subtracted from the + complete data. + + If dftreplace = 'neighbour' the powerline component is reduced via + spectrum interpolation (Leske & Dalal, 2019, NeuroImage 189, + doi: 10.1016/j.neuroimage.2019.01.026), estimating the required signal + components by fitting sines and cosines. The algorithmic steps are + described in more detail below. % Preferably the data should have a length + that is an integer multiple of the oscillation period of the line noise + (i.e. 20ms for 50Hz noise). If the data is of different length, then only + the first N complete periods are used to estimate the line noise. The + estimate is subtracted from the complete data. Due to the possibility of + using slightly truncated data for the estimation of the necessary signal + components, this method is more forgiving with respect to numerical + issues with respect to the sampling frequency, and suboptimal epoch + lengths, in comparison to the method below. + + If dftreplace = 'neighbour_fft' the powerline component is reduced via spectrum + interpolation, in its original implementation, based on an algorithm that + uses an FFT and iFFT for the estimation of the spectral components. The signal is: + I) transformed into the frequency domain via a fast Fourier + transform (FFT), + II) the line noise component (e.g. 50Hz, dftbandwidth = 1 (±1Hz): 49-51Hz) is + interpolated in the amplitude spectrum by replacing the amplitude + of this frequency bin by the mean of the adjacent frequency bins + ('neighbours', e.g. 49Hz and 51Hz). + dftneighbourwidth defines frequencies considered for the mean (e.g. + dftneighbourwidth = 2 (±2Hz) implies 47-49 Hz and 51-53 Hz). + The original phase information of the noise frequency bin is + retained. + III) the signal is transformed back into the time domain via inverse FFT + (iFFT). + If Fline is a vector (e.g. [50 100 150]), harmonics are also considered. + Preferably the data should be continuous or consist of long data segments + (several seconds) to avoid edge effects. If the sampling rate and the + data length are such, that a full cycle of the line noise and the harmonics + fit in the data and if the line noise is stationary (e.g. no variations + in amplitude or frequency), then spectrum interpolation can also be + applied to short trials. But it should be used with caution and checked + for edge effects. + + When using spectral interpolation, additional arguments are: + + dftbandwidth half bandwidth of line noise frequency bands, applies to spectrum interpolation, in Hz + dftneighbourwidth width of frequencies neighbouring line noise frequencies, applies to spectrum interpolation (dftreplace = 'neighbour'), in Hz + + If the data contains NaNs, the output of the affected channel(s) will be + all(NaN). + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_dftfilter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_highpassfilter` + +```{text} + FT_PREPROC_HIGHPASSFILTER applies a high-pass filter to the data and thereby removes + the low frequency components in the data + + Use as + [filt] = ft_preproc_highpassfilter(dat, Fsample, Fhp, N, type, dir, instabilityfix) + where + dat data matrix (Nchans X Ntime) + Fs sampling frequency in Hz + Fhp filter frequency in Hz + order optional filter order, default is 6 (but) or dependent on frequency band and data length (fir/firls) + type optional filter type, can be + 'but' Butterworth IIR filter (default) + 'firws' FIR filter with windowed sinc + 'fir' FIR filter using MATLAB fir1 function + 'firls' FIR filter using MATLAB firls function (requires MATLAB Signal Processing Toolbox) + 'brickwall' frequency-domain filter using forward and inverse FFT + dir optional filter direction, can be + 'onepass' forward filter only + 'onepass-reverse' reverse filter only, i.e. backward in time + 'onepass-zerophase' zero-phase forward filter with delay compensation (default for firws, linear-phase symmetric FIR only) + 'onepass-reverse-zerophase' zero-phase reverse filter with delay compensation + 'onepass-minphase' minimum-phase converted forward filter (non-linear, only for firws) + 'twopass' zero-phase forward and reverse filter (default, except for firws) + 'twopass-reverse' zero-phase reverse and forward filter + 'twopass-average' average of the twopass and the twopass-reverse + instabilityfix optional method to deal with filter instabilities + 'no' only detect and give error (default) + 'reduce' reduce the filter order + 'split' split the filter in two lower-order filters, apply sequentially + df optional transition width (firws) + wintype optional window type (firws), can be + 'hamming' (default) maximum passband deviation 0.0022 [0.22%], stopband attenuation -53dB + 'hann' maximum passband deviation 0.0063 [0.63%], stopband attenuation -44dB + 'blackman' maximum passband deviation 0.0002 [0.02%], stopband attenuation -74dB + 'kaiser' + dev optional max passband deviation/stopband attenuation (only for firws with kaiser window, default = 0.001 [0.1%, -60 dB]) + plotfiltresp optional, 'yes' or 'no', plot filter responses (only for firws, default = 'no') + usefftfilt optional, 'yes' or 'no', use fftfilt instead of filter (only for firws, default = 'no') + + Note that a one- or two-pass filter has consequences for the strength of the filter, + i.e. a two-pass filter with the same filter order will attenuate the signal twice as + strong. + + Further note that the filter type 'brickwall' filters in the frequency domain, + but may have severe issues. For instance, it has the implication that the time + domain signal is periodic. Another issue pertains to that frequencies are + not well defined over short time intervals; particularly for low frequencies. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_highpassfilter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_hilbert` + +```{text} + FT_PREPROC_HILBERT computes the Hilbert transform of the data and optionally + performs post-processing on the complex representation, e.g. the absolute + value of the Hilbert transform of a band-pass filtered signal corresponds + to the amplitude envelope. + + Use as + [dat] = ft_preproc_hilbert(dat, option) + where + dat data matrix (Nchans X Ntime) + option string that determines whether and how the Hilbert transform should be post-processed, can be + 'abs' (default) + 'complex' + 'real' + 'imag' + 'absreal' + 'absimag' + 'angle' + + If the data contains NaNs, the output of the affected channel(s) will be + all(NaN). + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_hilbert.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_lowpassfilter` + +```{text} + FT_PREPROC_LOWPASSFILTER applies a low-pass filter to the data and thereby removes + all high frequency components in the data + + Use as + [filt] = ft_preproc_lowpassfilter(dat, Fs, Flp, N, type, dir, instabilityfix, df, wintype, dev, plotfiltresp, usefftfilt) + where + dat data matrix (Nchans X Ntime) + Fs sampling frequency in Hz + Flp filter frequency in Hz + order optional filter order, default is 6 (but) or dependent on frequency band and data length (fir/firls) + type optional filter type, can be + 'but' Butterworth IIR filter (default) + 'firws' FIR filter with windowed sinc + 'fir' FIR filter using MATLAB fir1 function + 'firls' FIR filter using MATLAB firls function (requires MATLAB Signal Processing Toolbox) + 'brickwall' frequency-domain filter using forward and inverse FFT + dir optional filter direction, can be + 'onepass' forward filter only + 'onepass-reverse' reverse filter only, i.e. backward in time + 'onepass-zerophase' zero-phase forward filter with delay compensation (default for firws, linear-phase symmetric FIR only) + 'onepass-reverse-zerophase' zero-phase reverse filter with delay compensation + 'onepass-minphase' minimum-phase converted forward filter (non-linear, only for firws) + 'twopass' zero-phase forward and reverse filter (default, except for firws) + 'twopass-reverse' zero-phase reverse and forward filter + 'twopass-average' average of the twopass and the twopass-reverse + instabilityfix optional method to deal with filter instabilities + 'no' only detect and give error (default) + 'reduce' reduce the filter order + 'split' split the filter in two lower-order filters, apply sequentially + df optional transition width (firws) + wintype optional window type (firws), can be + 'hamming' (default) maximum passband deviation 0.0022 [0.22%], stopband attenuation -53dB + 'hann' maximum passband deviation 0.0063 [0.63%], stopband attenuation -44dB + 'blackman' maximum passband deviation 0.0002 [0.02%], stopband attenuation -74dB + 'kaiser' + dev optional max passband deviation/stopband attenuation (only for firws with kaiser window, default = 0.001 [0.1%, -60 dB]) + plotfiltresp optional, 'yes' or 'no', plot filter responses (only for firws, default = 'no') + usefftfilt optional, 'yes' or 'no', use fftfilt instead of filter (only for firws, default = 'no') + + Note that a one- or two-pass filter has consequences for the strength of the + filter, i.e. a two-pass filter with the same filter order will attenuate the signal + twice as strong. + + Further note that the filter type 'brickwall' filters in the frequency domain, + but may have severe issues. For instance, it has the implication that the time + domain signal is periodic. Another issue pertains to that frequencies are + not well defined over short time intervals; particularly for low frequencies. + + If the data contains NaNs, these will affect the output. With an IIR + filter, and/or with FFT-filtering, local NaNs will spread to the whole + time series. With a FIR filter, local NaNs will spread locally, depending + on the filter order. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_lowpassfilter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_medianfilter` + +```{text} + FT_PREPROC_MEDIANFILTER applies a median filter, which smooths the data with a + boxcar-like kernel, except that it keeps steps in the data. This function requires + the MATLAB Signal Processing toolbox. + + Use as + [dat] = ft_preproc_medianfilter(dat, order) + where + dat data matrix (Nchans X Ntime) + order number, the length of the median filter kernel (default = 25) + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_medianfilter.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_online_downsample_apply` + +```{text} + FT_PREPROC_ONLINE_DOWNSAMPLE_APPLY passes a signal through the online downsampler + and returns the downsampler state and the downsampled signal. The state keeps track + of the number of samples to be skipped in the next call. + + Use as + [state, dat] = ft_preproc_online_downsample_apply(state, x) + where + dat = Nchan x Ntime + state = downsampler state, see FT_PREPROC_ONLINE_DOWNSAMPLE_INIT + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_online_downsample_apply.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_online_downsample_init` + +```{text} + FT_PREPROC_ONLINE_DOWNSAMPLE_INIT initializes an downsampling model with the given factor. + + Use as + state = ft_preproc_online_downsample_init(factor) + + See also PREPROC, FT_PREPROC_ONLINE_DOWNSAMPLE_APPLY + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_online_downsample_init.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_online_filter_apply` + +```{text} + FT_PREPROC_ONLINE_FILTER_APPLY passes a signal through the online filter and + returns the updated filter model (delay states) and the filtered signal. + + Use as + [state, dat] = ft_preproc_online_filter_apply(state, dat) + where + dat = Nchan x Ntime + state = filter state, see FT_PREPROC_ONLINE_FILTER_INIT + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_online_filter_apply.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_online_filter_init` + +```{text} + FT_PREPROC_ONLINE_FILTER_INIT initialize an IIR filter model with coefficients B + and A, as used in filter and butter etc. The most recent sample of the signal must + be given as a column vector. + + Use as + state = ft_preproc_online_filter_init(B, A, dat) + + This function will calculate the filter delay states such that the initial response + will be as if the filter already have been applied forever. + + See also PREPROC, FT_PREPROC_ONLINE_FILTER_APPLY + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_online_filter_init.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_padding` + +```{text} + FT_PREPROC_PADDING performs padding on the data, i.e. adds or removes samples + to or from the data matrix. + + Use as + [dat] = ft_preproc_padding(dat, padtype, padlength) + or as + [dat] = ft_preproc_padding(dat, padtype, prepadlength, postpadlength) + where + dat data matrix (Nchan x Ntime) + padtype 'zero', 'mean', 'localmean', 'edge', 'mirror', 'nan' or 'remove' + padlength scalar, number of samples that will be padded + prepadlength scalar, number of samples that will be padded before the data + postpadlength scalar, number of samples that will be padded after the data + + If padlength is used instead of prepadlength and postpadlength, padding + will be symmetrical (i.e. padlength = prepadlength = postpadlength) + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. Depending on the type of padding, NaNs may spread + to the pads. + + See also FT_PREPROCESSING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_padding.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_polyremoval` + +```{text} + FT_PREPROC_POLYREMOVAL removed an Nth order polynomal from the data + + Use as + dat = ft_preproc_polyremoval(dat, order, begsample, endsample, flag) + where + dat data matrix (Nchans X Ntime) + order the order of the polynomial + begsample index of the begin sample for the estimate of the polynomial + endsample index of the end sample for the estimate of the polynomial + flag optional boolean to specify whether the first order basis + vector will zscored prior to computing higher order basis + vectors from the first-order basis vector (and the beta + weights). This is to avoid numerical problems with the + inversion of the covariance when the polynomial is of high + order/number of samples is large. + + If begsample and endsample are not specified, it will use the whole + window to estimate the polynomial. + + For example + ft_preproc_polyremoval(dat, 0) + removes the mean value from each channel and + ft_preproc_polyremoval(dat, 1) + removes the mean and the linear trend. + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also FT_PREPROC_BASELINECORRECT, FT_PREPROC_DETREND + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_polyremoval.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_rectify` + +```{text} + FT_PREPROC_RECTIFY rectifies the data, i.e. converts all samples with a + negative value into the similar magnitude positive value + + Use as + [dat] = ft_preproc_rectify(dat) + where + dat data matrix (Nchans X Ntime) + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_rectify.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_rereference` + +```{text} + FT_PREPROC_REREFERENCE computes the average reference over all EEG channels + or rereferences the data to the selected channels + + Use as + [dat] = ft_preproc_rereference(dat, refchan, method, handlenan, leadfield) + where + dat data matrix (Nchans X Ntime) + refchan vector with indices of the new reference channels, or 'all' + method string, can be 'avg', 'median', or 'rest' + handlenan boolean, can be false (default) or true + leadfield leadfield matrix (required for REST, otherwise empty) + + If the new reference channel(s) are not specified, the data will be + rereferenced to the average of all channels. + + If the data that is used to compute the new reference contains NaNs, + these will spread to all output channels, unless the handlenan flag has + been set to true. + + For REST the leadfield should be a matrix (channels X sources) + which is calculated by using the forward theory, based on + the electrode montage, head model and equivalent source + model. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_rereference.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_resample` + +```{text} + FT_PREPROC_RESAMPLE resamples all channels in the data matrix + + Use as + dat = ft_preproc_resample(dat, Fold, Fnew, method) + where + dat = matrix with the input data (Nchans X Nsamples) + Fold = scalar, original sampling frequency in Hz + Fnew = scalar, desired sampling frequency in Hz + method = string, can be 'resample', 'decimate', 'downsample', 'fft' + + The resample method applies an anti-aliasing (lowpass) FIR filter to + the data during the resampling process, and compensates for the filter's + delay. For the other two methods you should apply an anti-aliassing + filter prior to calling this function. + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also PREPROC, FT_PREPROC_LOWPASSFILTER + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_resample.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_slidingrange` + +```{text} + FT_PREPROC_SLIDINGRANGE computes the range of the data in a sliding time + window of the width specified. + + Use as + [dat] = ft_preproc_slidingrange(dat, width, normalize) + where + dat data matrix (Nchans x Ntime) + width width of the smoothing kernel, this should be an odd number since the window needs to be centered on an individual sample + normalize boolean, whether to normalize the range of the data with the square root of the window size (default = false) + + If the data contains NaNs, these are ignored for the computation, but retained in + the output. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_slidingrange.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_smooth` + +```{text} + FT_PREPROC_SMOOTH performs boxcar smoothing with specified length. + Edge behavior is improved by implicit padding with the mean over + half the boxcar length at the edges of the data segment. + + Use as + [dat] = ft_preproc_smooth(dat, n) + + Where dat is an Nchan x Ntime data matrix, and n is the length + of the boxcar smoothing kernel + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_smooth.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preproc_standardize` + +```{text} + FT_PREPROC_STANDARDIZE performs a z-transformation or standardization + of the data. The standardized data will have a zero-mean and a unit + standard deviation. + + Use as + [dat] = ft_preproc_standardize(dat, begsample, endsample) + where + dat data matrix (Nchans x Ntime) + begsample index of the begin sample for the mean and stdev estimate + endsample index of the end sample for the mean and stdev estimate + + If no begin and end sample are specified, it will be estimated on the + complete data. + + If the data contains NaNs, these are ignored for the computation, but + retained in the output. + + See also PREPROC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/preproc/ft_preproc_standardize.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_preprocessing` + +```{text} + FT_PREPROCESSING reads MEG and/or EEG data according to user-specified trials + and applies several user-specified preprocessing steps to the signals. + + Use as + [data] = ft_preprocessing(cfg) + or + [data] = ft_preprocessing(cfg, data) + + The first input argument "cfg" is the configuration structure, which contains all + details for the dataset filename, trials and the preprocessing options. + + If you are calling FT_PREPROCESSING with only the configuration as first input + argument and the data still has to be read from file, you should specify + cfg.dataset = string with the filename + cfg.trl = Nx3 matrix with the trial definition, see FT_DEFINETRIAL + cfg.padding = length (in seconds) to which the trials are padded for filtering (default = 0) + cfg.padtype = string, type of padding (default: 'data' padding or + 'mirror', depending on feasibility) + cfg.continuous = 'yes' or 'no' whether the file contains continuous data + (default is determined automatic) + + Instead of specifying the dataset in the configuration, you can also explicitly + specify the name of the file containing the header information and the name of the + file containing the data, using + cfg.datafile = string with the filename + cfg.headerfile = string with the filename + + If you are calling FT_PREPROCESSING with the second input argument "data", then + that should contain data that was already read from file in a previous call to + FT_PREPROCESSING. In that case only the configuration options below apply. + + The channels that will be read and/or preprocessed are specified with + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.chantype = string or Nx1 cell-array with channel types to be read (only for NeuroOmega) + + The preprocessing options for the selected channels are specified with + cfg.lpfilter = 'no' or 'yes' lowpass filter (default = 'no') + cfg.hpfilter = 'no' or 'yes' highpass filter (default = 'no') + cfg.bpfilter = 'no' or 'yes' bandpass filter (default = 'no') + cfg.bsfilter = 'no' or 'yes' bandstop filter (default = 'no') + cfg.dftfilter = 'no' or 'yes' line noise removal using discrete fourier transform (default = 'no') + cfg.medianfilter = 'no' or 'yes' jump preserving median filter (default = 'no') + cfg.lpfreq = lowpass frequency in Hz + cfg.hpfreq = highpass frequency in Hz + cfg.bpfreq = bandpass frequency range, specified as [lowFreq highFreq] in Hz + cfg.bsfreq = bandstop frequency range, specified as [low high] in Hz (or as Nx2 matrix for notch filter) + cfg.dftfreq = line noise frequencies in Hz for DFT filter (default = [50 100 150]) + cfg.lpfiltord = lowpass filter order (default set in low-level function) + cfg.hpfiltord = highpass filter order (default set in low-level function) + cfg.bpfiltord = bandpass filter order (default set in low-level function) + cfg.bsfiltord = bandstop filter order (default set in low-level function) + cfg.lpfilttype = digital filter type, 'but' or 'firws' or 'fir' or 'firls' (default = 'but') + cfg.hpfilttype = digital filter type, 'but' or 'firws' or 'fir' or 'firls' (default = 'but') + cfg.bpfilttype = digital filter type, 'but' or 'firws' or 'fir' or 'firls' (default = 'but') + cfg.bsfilttype = digital filter type, 'but' or 'firws' or 'fir' or 'firls' (default = 'but') + cfg.lpfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!) + cfg.hpfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!) + cfg.bpfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!) + cfg.bsfiltdir = filter direction, 'twopass' (default), 'onepass' or 'onepass-reverse' or 'onepass-zerophase' (default for firws) or 'onepass-minphase' (firws, non-linear!) + cfg.lpinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no') + cfg.hpinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no') + cfg.bpinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no') + cfg.bsinstabilityfix = deal with filter instability, 'no', 'reduce', 'split' (default = 'no') + cfg.lpfiltdf = lowpass transition width (firws, overrides order, default set in low-level function) + cfg.hpfiltdf = highpass transition width (firws, overrides order, default set in low-level function) + cfg.bpfiltdf = bandpass transition width (firws, overrides order, default set in low-level function) + cfg.bsfiltdf = bandstop transition width (firws, overrides order, default set in low-level function) + cfg.lpfiltwintype = lowpass window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws) + cfg.hpfiltwintype = highpass window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws) + cfg.bpfiltwintype = bandpass window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws) + cfg.bsfiltwintype = bandstop window type, 'hann' or 'hamming' (default) or 'blackman' or 'kaiser' (firws) + cfg.lpfiltdev = lowpass max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function) + cfg.hpfiltdev = highpass max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function) + cfg.bpfiltdev = bandpass max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function) + cfg.bsfiltdev = bandstop max passband deviation (firws with 'kaiser' window, default 0.001 set in low-level function) + cfg.dftreplace = 'zero' or 'neighbour', method used to reduce line noise, 'zero' implies DFT filter, 'neighbour' implies spectrum interpolation (default = 'zero') + cfg.dftbandwidth = bandwidth of line noise frequencies, applies to spectrum interpolation, in Hz (default = [1 2 3]) + cfg.dftneighbourwidth = bandwidth of frequencies neighbouring line noise frequencies, applies to spectrum interpolation, in Hz (default = [2 2 2]) + cfg.plotfiltresp = 'no' or 'yes', plot filter responses (firws, default = 'no') + cfg.usefftfilt = 'no' or 'yes', use fftfilt instead of filter (firws, default = 'no') + cfg.medianfiltord = length of median filter (default = 9) + cfg.demean = 'no' or 'yes', whether to apply baseline correction (default = 'no') + cfg.baselinewindow = [begin end] in seconds, the default is the complete trial (default = 'all') + cfg.detrend = 'no' or 'yes', remove linear trend from the data (done per trial) (default = 'no') + cfg.polyremoval = 'no' or 'yes', remove higher order trend from the data (done per trial) (default = 'no') + cfg.polyorder = polynome order for poly trend removal (default = 2; note that all lower-order trends will also be removed when using cfg.polyremoval) + cfg.derivative = 'no' or 'yes', computes the first order derivative of the data (default = 'no') + cfg.hilbert = 'no', 'abs', 'complex', 'real', 'imag', 'absreal', 'absimag' or 'angle' (default = 'no') + cfg.rectify = 'no' or 'yes' (default = 'no') + cfg.precision = 'single' or 'double' (default = 'double') + cfg.absdiff = 'no' or 'yes', computes absolute derivative (i.e. first derivative then rectify) + + Preprocessing options that only apply to MEG data are + cfg.coordsys = string, 'head' or 'dewar' (default = 'head') + cfg.coilaccuracy = can be empty or a number (0, 1 or 2) to specify the accuracy (default = []) + cfg.coildeffile = can be empty or a string to a custom coil_def.dat file (default = []) + + Preprocessing options that you should only use for EEG data are + cfg.reref = 'no' or 'yes' (default = 'no') + cfg.refchannel = cell-array with new EEG reference channel(s), this can be 'all' for a common average reference + cfg.refmethod = 'avg', 'median', 'rest', 'bipolar' or 'laplace' (default = 'avg') + cfg.groupchans = 'yes' or 'no', should channels be rereferenced in separate groups for bipolar and laplace methods, + this requires channnels to be named using an alphanumeric code, where letters represent the group + and numbers represent the order of the channel whithin its group (default = 'no') + cfg.leadfield = leadfield structure, this is required when cfg.refmethod='rest', see FT_PREPARE_LEADFIELD + cfg.implicitref = 'label' or empty, add the implicit EEG reference as zeros (default = []) + cfg.montage = 'no' or a montage structure, see FT_APPLY_MONTAGE (default = 'no') + + Preprocessing options that you should only use when you are calling FT_PREPROCESSING with + also the second input argument "data" are + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + + Preprocessing options that you should only use when you are calling + FT_PREPROCESSING with a single cfg input argument are + cfg.method = 'trial' or 'channel', read data per trial or per channel (default = 'trial') + + 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_DEFINETRIAL, FT_REDEFINETRIAL, FT_APPENDDATA, FT_APPENDSPIKE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_preprocessing.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_progress` + +```{text} + FT_PROGRESS shows a graphical or non-graphical progress indication similar to the + standard WAITBAR function, but with the extra option of printing it in the command + window as a plain text string or as a rotating dial. Alternatively, you can also + specify it not to give feedback on the progress. + + Prior to the for-loop, you should call either + ft_progress('init', 'none', 'Please wait...') + ft_progress('init', 'text', 'Please wait...') + ft_progress('init', 'textbar', 'Please wait...') % ascii progress bar + ft_progress('init', 'dial', 'Please wait...') % rotating dial + ft_progress('init', 'etf', 'Please wait...') % estimated time to finish + ft_progress('init', 'gui', 'Please wait...') + + In each iteration of the for-loop, you should call either + ft_progress(x) % only show percentage + ft_progress(x, 'Processing event %d from %d', i, N) % show string, x=i/N + + After finishing the for-loop, you should call + ft_progress('close') + + Here is an example for the use of a progress indicator + ft_progress('init', 'etf', 'Please wait...'); + for i=1:100 + ft_progress(i/100, 'Processing event %d from %d', i, 100); + pause(0.03); + end + ft_progress('close') + + See also WAITBAR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_progress.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_read_atlas` + +```{text} + FT_READ_ATLAS reads an template/individual segmentation or parcellation from disk. + The volumetric segmentation or the surface-based parcellation can either represent + a template atlas (e.g. AAL or the Talairach Daemon), it can represent an + individualized atlas (e.g. obtained from FreeSurfer) or it can represent an + unlabeled parcellation/segmentation obtained from an individual's DTi, anatomical, + or resting state fMRI scan. + + Use as + atlas = ft_read_atlas(filename, ...) + or + atlas = ft_read_atlas({filenamelabels, filenamemesh}, ...) + + Additional options should be specified in key-value pairs and can include + 'format' = string, see below + 'unit' = string, e.g. 'mm' (default is to keep it in the native units of the file) + 'map' = string, 'maxprob' (default), or 'prob', for FSL-based atlases, providing + either a probabilistic segmentation or a maximum a posterior probability map + 'labelfile' = string, point to a (generic) text or xml file for interpretation of the values in the atlas + + For individual surface-based atlases from FreeSurfer you should specify two + filenames as a cell-array: the first points to the file that contains information + with respect to the parcels' labels, the second points to the file that defines the + mesh on which the parcellation is defined. + + The 'format' variable, if not specified, will be determined automatically. In general + it will not be needed to specify it. The following formats are supported: + + Volumetric atlases based on a (gzipped) nifti-file with an companion txt-file for interpretation + 'aal' assumes filename starting with 'ROI_MNI' + 'brainnetome' assumes companion lookuptable txt-file starting with 'Brainnetome Atlas' + 'simnibs_v4' assumes filename starting with 'final_tissues', with companion freesurfer-style lookuptable txt-file + 'wfu' assumes specific formatting of companion lookuptable txt-file + + Volumetric atlases based on a (gzipped) nifti-file with hard coded assumption on the labels + 'yeo7' + 'yeo17' + + Volumetric atlases based on a folder with (gzipped) nifti-files with a companion xml-file for interpretation + 'fsl' assumes path to folder with data mentioned in the xml-file. Use xml-file as filename + + Volumetric atlases based on the freesurfer mgz format with standard lookuptable txt-file for interpretation + 'freesurfer_volume' assumes the freesurfer LUT file for interpretation, and assumes aparc or aseg in the + filename, used for subject-specific parcellations + + Volumetric atlases based on the afni software + 'afni' assumes filename containing BRIK or HEAD, assumes generic interpretation of the labels + for the TTatlas+tlrc, or otherwise the interpretation should be in the file + + Volumetric atlas based on the spm_anatomy toolbox + 'spm_anatomy' pair of .hdr/.img files, and an associated mat-file for the interpretation + Specify the associated mat-file with MPM in filename + + Surface based atlases, requiring a pair of files, containing the labels, and the associated geometry + 'caret_label' hcp-workbench/caret style .gii, with .label. in filename, requires additional file describing the geometry + 'freesurfer_surface' freesurfer style annotation file, requires additional file describing the geometry + + Miscellaneous formats + 'mat' mat-file, with FieldTrip style struct, other matlab data that FieldTrip knows to handle, can also be + Brainstorm derived surfaces + 'vtpm' + + For volume data for whicth the format cannot be automatically detected, or if the volume data does not have a companion file + for the interpretation of the labels, a list of 'fake' labels will be generated. + + The output atlas will be represented as structure according to FT_DATATYPE_SEGMENTATION or + FT_DATATYPE_PARCELLATION. + + The 'lines' and the 'colorcube' colormaps may be useful for plotting the different + patches, for example using FT_PLOT_MESH, or FT_SOURCEPLOT. + + See also FT_READ_MRI, FT_READ_HEADSHAPE, FT_PREPARE_SOURCEMODEL, FT_SOURCEPARCELLATE, FT_PLOT_MESH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_read_atlas.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_read_cifti` + +```{text} + FT_READ_CIFTI read functional data or functional connectivity from a cifti-1 or + cifti-2 file. The functional data can consist of a dense or a parcellated + representation. The geometrical description of the brainordinates can consist of + triangulated surfaces or voxels in a regular 3-D volumetric grid. If available, + it also reads the geometrical description of the surfaces from the accompanying + gifti files. + + Use as + data = ft_read_cifti(filename, ...) + + If the file contains a dense representation of functional data, the output data + structure is organized according to the FT_DATATYPE_SOURCE or FT_DATATYPE_VOLUME + definition. + + If the contains a parcellated representation of functional data, the output data + structure is organized according to the FT_DATATYPE_TIMELOCK or FT_DATATYPE_FREQ + definition. In addition, the description of the geometry wil be represented in a + data.brainordinate field, which is organized according to the FT_DATATYPE_SOURCE + or FT_DATATYPE_VOLUME definition. + + Any optional input arguments should come in key-value pairs and may include + 'readdata' = boolean, can be false or true (default depends on file size) + 'readsurface' = boolean, can be false or true (default = true) + 'cortexleft' = string, filename with left cortex (optional, default is automatic) + 'cortexright' = string, filename with right cortex (optional, default is automatic) + 'hemisphereoffset' = number, amount in milimeter to move the hemispheres apart from each other (default = 0) + 'mapname' = string, 'field' to represent multiple maps separately, or 'array' to represent as array (default = 'field') + 'debug' = boolean, write a debug.xml file (default = false) + + See also FT_WRITE_CIFTI, FT_READ_MRI, FT_WRITE_MRI + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_read_cifti.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_read_data` + +```{text} + FT_READ_DATA reads data from a variety of EEG, MEG and other time series data files + and represents it in a common data-independent format. The supported formats are + listed in the accompanying FT_READ_HEADER function. + + Use as + dat = ft_read_data(filename, ...) + + Additional options should be specified in key-value pairs and can be + 'header' header structure, see FT_READ_HEADER + 'begsample' first sample to read + 'endsample' last sample to read + 'begtrial' first trial to read, mutually exclusive with begsample+endsample + 'endtrial' last trial to read, mutually exclusive with begsample+endsample + 'chanindx' list with channel indices to read + 'chanunit' cell-array with strings, convert each channel to the desired unit + 'checkboundary' boolean, whether to check for reading segments over a trial boundary + 'checkmaxfilter' boolean, whether to check that maxfilter has been correctly applied (default = true) + 'cache' boolean, whether to use caching for multiple reads + 'dataformat' string + 'headerformat' string + 'fallback' can be empty or 'biosig' (default = []) + 'blocking' wait for the selected number of events (default = 'no') + 'timeout' amount of time in seconds to wait when blocking (default = 5) + 'password' password structure for encrypted data set (only for dhn_med10, mayo_mef30 and mayo_mef21) + + This function returns a 2-D matrix of size Nchans*Nsamples for continuous + data when begevent and endevent are specified, or a 3-D matrix of size + Nchans*Nsamples*Ntrials for epoched or trial-based data when begtrial + and endtrial are specified. + + To use an external reading function, you can specify an external function as the + 'dataformat' option. This function should take five input arguments: filename, hdr, + begsample, endsample, chanindx. Please check the code of this function for details, + and search for BIDS_TSV as example. + + See also FT_READ_HEADER, FT_READ_EVENT, FT_WRITE_DATA, FT_WRITE_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_read_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_read_event` + +```{text} + FT_READ_EVENT reads all events from an EEG, MEG or other time series dataset and + returns them in a common data-independent structure. The supported formats are + listed in the accompanying FT_READ_HEADER function. + + Use as + [event] = ft_read_event(filename, ...) + + Additional options should be specified in key-value pairs and can be + 'dataformat' = string + 'headerformat' = string + 'eventformat' = string + 'header' = header structure, see FT_READ_HEADER + 'detectflank' = string, can be 'up', 'updiff', 'down', 'downdiff', 'both', 'any', 'biton', 'bitoff' (default is system specific) + 'trigshift' = integer, number of samples to shift from flank to detect trigger value (default = 0) + 'chanindx' = list with channel numbers for trigger detection, specify -1 in case you don't want to detect triggers (default is automatic) + 'threshold' = threshold for analog trigger channels (default is system specific) + 'tolerance' = tolerance in samples when merging Neuromag analogue trigger channels (default = 1, meaning that a shift of one sample in both directions is compensated for) + 'blocking' = wait for the selected number of events (default = 'no') + 'timeout' = amount of time in seconds to wait when blocking (default = 5) + 'password' = password structure for encrypted data set (only for dhn_med10, mayo_mef30 and mayo_mef21) + 'readbids' = 'yes', no', or 'ifmakessense', whether to read information from the BIDS sidecar files (default = 'ifmakessense') + + This function returns an event structure with the following fields + event.type = string + event.sample = expressed in samples, the first sample of a recording is 1 + event.value = number or string + event.offset = expressed in samples + event.duration = expressed in samples + event.timestamp = expressed in timestamp units, which vary over systems (optional) + + You can specify optional arguments as key-value pairs for filtering the events, + e.g. to select only events of a specific type, of a specific value, or events + between a specific begin and end sample. This event filtering is especially usefull + for real-time processing. See FT_FILTER_EVENT for more details. + + Some data formats have trigger channels that are sampled continuously with the same + rate as the electrophysiological data. The default is to detect only the up-going + TTL flanks. The trigger events will correspond with the first sample where the TTL + value is up. This behavior can be changed using the 'detectflank' option, which + also allows for detecting the down-going flank or both. In case of detecting the + down-going flank, the sample number of the event will correspond with the first + sample at which the TTF went down, and the value will correspond to the TTL value + just prior to going down. + + To use an external reading function, you can specify an external function as the + 'eventformat' option. This function should take the filename and the headeras + input arguments. Please check the code of this function for details, and search for + BIDS_TSV as example. + + The event type and sample fields are always defined, other fields are present but + can be empty, depending on the type of event file. Events are sorted by the sample + on which they occur. After reading the event structure, you can use the following + tricks to extract information about those events in which you are interested. + + Determine the different event types + unique({event.type}) + + Get the index of all trial events + find(strcmp('trial', {event.type})) + + Make a vector with all triggers that occurred on the backpanel + [event(find(strcmp('backpanel trigger', {event.type}))).value] + + Find the events that occurred in trial 26 + t=26; samples_trials = [event(find(strcmp('trial', {event.type}))).sample]; + find([event.sample]>samples_trials(t) & [event.sample]FAQ on the FieldTrip website. + + 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_PREPROCESSING, FT_APPENDDATA, FT_PREPROC_LOWPASSFILTER, RESAMPLE, DOWNSAMPLE, DECIMATE, INTERP1 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_resampledata.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_respiration` + +```{text} + FT_RESPIRATION estimates the respiration rate from a respiration belt, temperature + sensor, movement sensor or from the heart rate. It returns a new data structure + with a continuous representation of the rate and phase. + + Use as + dataout = ft_respiration(cfg, data) + where the input data is a structure as obtained from FT_PREPROCESSING. + + The configuration structure has the following options + cfg.channel = selected channel for processing, see FT_CHANNELSELECTION + cfg.peakseparation = scalar, time in seconds + cfg.envelopewindow = scalar, time in seconds + cfg.feedback = 'yes' or 'no' + The input data can be preprocessed on the fly using + cfg.preproc.bpfilter = 'yes' or 'no' (default = 'yes') + cfg.preproc.bpfreq = [low high], filter frequency in Hz + + See also FT_HEARTRATE, FT_ELECTRODERMALACTIVITY, FT_HEADMOVEMENT, FT_REGRESSCONFOUND + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_respiration.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_save_workspace` + +```{text} + FT_SAVE_WORKSPACE saves every variable in the base workspace to a .mat file with + the same name as the variable in the workspace itself. For example, the variable + "ans" would be saved to the file "ans.mat". Prior to calling this function, you + might want to clean up your workspace using CLEAR or KEEP. + + Use as + ft_save_workspace(dirname) + + If the directory does not yet exist, this function will create it for you. If you + leave it empty, the files will be saved to the present working directory. + + For example, the following will save all variables to a time-stamped + sub-directory that is created inside the present working directory: + + ft_save_workspace(datestr(now)) + + See also SAVE, LOAD, SAVEFIG, CLEAR, KEEP + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_save_workspace.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_scalingfactor` + +```{text} + FT_SCALINGFACTOR determines the scaling factor from old to new units, i.e. it + returns a number with which the data in the old units needs to be multiplied + to get it expressed in the new units. + + Use as + factor = ft_scalingfactor(old, new) + where old and new are strings that specify the units. + + For example + ft_scalingfactor('m', 'cm') % returns 100 + ft_scalingfactor('V', 'uV') % returns 1000 + ft_scalingfactor('T/cm', 'fT/m') % returns 10^15 divided by 10^-2, which is 10^17 + ft_scalingfactor('cm^2', 'mm^2') % returns 100 + ft_scalingfactor('1/ms', 'Hz') % returns 1000 + + The following fundamental units are supported + metre m length l (a lowercase L), x, r L + kilogram kg mass m M + second s time t T + ampere A electric current I (an uppercase i) I + kelvin K thermodynamic temperature T # + mole mol amount of substance n N + candela cd luminous intensity Iv (an uppercase i with lowercase non-italicized v subscript) J + + The following derived units are supported + hertz Hz frequency 1/s T-1 + radian rad angle m/m dimensionless + steradian sr solid angle m2/m2 dimensionless + newton N force, weight kg#m/s2 M#L#T-2 + pascal Pa pressure, stress N/m2 M#L-1#T-2 + joule J energy, work, heat N#m = C#V = W#s M#L2#T-2 + coulomb C electric charge or quantity of electricity s#A T#I + volt V voltage, electrical potential difference, electromotive force W/A = J/C M#L2#T-3#I-1 + farad F electric capacitance C/V M-1#L-2#T4#I2 + siemens S electrical conductance 1/# = A/V M-1#L-2#T3#I2 + weber Wb magnetic flux J/A M#L2#T-2#I-1 + tesla T magnetic field strength V#s/m2 = Wb/m2 = N/(A#m) M#T-2#I-1 + henry H inductance V#s/A = Wb/A M#L2#T-2#I-2 + lumen lm luminous flux cd#sr J + lux lx illuminance lm/m2 L-2#J + becquerel Bq radioactivity (decays per unit time) 1/s T-1 + gray Gy absorbed dose (of ionizing radiation) J/kg L2#T-2 + sievert Sv equivalent dose (of ionizing radiation) J/kg L2#T-2 + katal kat catalytic activity mol/s T-1#N + + The following alternative units are supported + inch inch length + feet feet length + gauss gauss magnetic field strength + + The following derived units are not supported due to potential confusion + between their ascii character representation + ohm # electric resistance, impedance, reactance V/A M#L2#T-3#I-2 + watt W power, radiant flux J/s = V#A M#L2#T-3 + degree Celsius ?C temperature relative to 273.15 K K ? + + See also http://en.wikipedia.org/wiki/International_System_of_Units + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_scalingfactor.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_scalpcurrentdensity` + +```{text} + FT_SCALPCURRENTDENSITY computes an estimate of the SCD using the + second-order derivative (the surface Laplacian) of the EEG potential + distribution + + The relation between the surface Laplacian and the SCD is explained + in more detail on http://tinyurl.com/ptovowl. + + Use as + [data] = ft_scalpcurrentdensity(cfg, data) + or + [timelock] = ft_scalpcurrentdensity(cfg, timelock) + where the input data is obtained from FT_PREPROCESSING or from + FT_TIMELOCKANALYSIS. The output data has the same format as the input + and can be used in combination with most other FieldTrip functions + such as FT_FREQANALYSIS or FT_TOPOPLOTER. + + The configuration should contain + cfg.method = 'finite' for finite-difference method or + 'spline' for spherical spline method + 'hjorth' for Hjorth approximation method + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.feedback = string, 'no', 'text', 'textbar', 'gui' (default = 'text') + + The finite method require the following + cfg.conductivity = conductivity of the scalp (default = 0.33 S/m) + + The spline and finite method require the following + cfg.conductivity = conductivity of the scalp (default = 0.33 S/m) + cfg.lambda = regularization parameter (default = 1e-05) + cfg.order = order of the splines (default = 4) + cfg.degree = degree of legendre polynomials (default for + <=32 electrodes = 9, + <=64 electrodes = 14, + <=128 electrodes = 20, + else = 32 + + The hjorth method requires the following + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS + + For the spline method you can specify the following + cfg.badchannel = cell-array, see FT_CHANNELSELECTION for details (default = []) + + Note that the scalp conductivity, electrode dimensions and the potential + all have to be expressed in the same SI units, otherwise the units of + the SCD values are not scaled correctly. The spatial distribution still + will be correct. + + 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. + + The 'finite' method implements + TF Oostendorp, A van Oosterom; The surface Laplacian of the potential: + theory and application. IEEE Trans Biomed Eng, 43(4): 394-405, 1996. + G Huiskamp; Difference formulas for the surface Laplacian on a + triangulated sphere. Journal of Computational Physics, 2(95): 477-496, + 1991. + + The 'spline' method implements + F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier. + Spherical splines for scalp potential and curernt density mapping. + Electroencephalogr Clin Neurophysiol, 72:184-187, 1989 + including their corrections in + F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier. + Corrigenda: EEG 02274, Electroencephalography and Clinical + Neurophysiology 76:565. + + The 'hjorth' method implements + B. Hjort; An on-line transformation of EEG scalp potentials into + orthogonal source derivation. Electroencephalography and Clinical + Neurophysiology 39:526-530, 1975. + + See also FT_PREPROCESSING, FT_TIMELOCKANALYSIS, FT_FREQNALYSIS, FT_TOPOPLOTER. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_scalpcurrentdensity.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_select_box` + +```{text} + FT_SELECT_BOX helper function for selecting a single rectangular region in the + current figure using the mouse. This function is not used as a callabck, but blocks + the execution of the code until a selection is made. + + Use as + [x, y] = ft_select_box() + + It returns a 2-element vector x and a 2-element vector y + with the corners of the selected region. + + See also FT_SELECT_CHANNEL, FT_SELECT_POINT, FT_SELECT_POINT3D, FT_SELECT_RANGE, + FT_SELECT_VOXEL, GINPUT, RBBOX + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_select_box.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_select_channel` + +```{text} + FT_SELECT_CHANNEL is a helper function that can be used as callback function + in a figure. It allows the user to select a channel. The channel labels + are returned. + + Use as + label = ft_select_channel(h, eventdata, ...) + The first two arguments are automatically passed by MATLAB to any + callback function. + + Additional options should be specified in key-value pairs and can be + 'callback' = function handle to be executed after channels have been selected + + You can pass additional arguments to the callback function in a cell-array + like {@function_handle,arg1,arg2} + + Example 1 + % create a figure + figure + cfg = []; + cfg.channel = {'chan1', 'chan2', 'chan3', 'chan4'}; + cfg.layout = 'ordered'; + lay = ft_prepare_layout(cfg); + ft_plot_layout(lay) + + % add the required guidata + info = guidata(gcf); + info.x = lay.pos(:,1); + info.y = lay.pos(:,2); + info.label = lay.label; + guidata(gcf, info); + + % add this function as the callback to make a single selection + set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'callback', @disp}) + + % or to make multiple selections + set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) + set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) + set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) + + Example 2, executed from within a subplot + % create a figure + figure + subplot(2,2,1) + cfg = []; + cfg.channel = {'chan1', 'chan2', 'chan3', 'chan4'}; + cfg.layout = 'ordered'; + lay = ft_prepare_layout(cfg); + ft_plot_layout(lay) + + % add the channel information to guidata under identifier linked to this axis + ident = ['axh' num2str(round(sum(clock.*1e6)))]; % unique identifier for this axis + set(gca,'tag',ident); + info = guidata(gcf); + info.(ident).x = lay.pos(:, 1); + info.(ident).y = lay.pos(:, 2); + info.(ident).label = lay.label; + guidata(gcf, info); + + % add this function as the callback to make a single selection + set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'callback', @disp}) + + % or to make multiple selections + set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) + set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) + set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) + + Subsequently you can click in the figure and you'll see that the disp + function is executed as callback and that it displays the selected + channels. + + See also FT_SELECT_BOX, FT_SELECT_POINT, FT_SELECT_POINT3D, FT_SELECT_RANGE, FT_SELECT_VOXEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_select_channel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_select_point` + +```{text} + FT_SELECT_POINT helper function for selecting a one or multiple points in the + current figure using the mouse. It returns a list of the [x y] coordinates of the + selected points. + + Use as + [selected] = ft_select_point(pos, ...) + + Optional input arguments should come in key-value pairs and can include + 'multiple' = true/false, make multiple selections, pressing "q" on the keyboard finalizes the selection (default = false) + 'nearest' = true/false (default = true) + + Example + pos = randn(10,2); + figure + plot(pos(:,1), pos(:,2), '.') + ft_select_point(pos) + + See also FT_SELECT_BOX, FT_SELECT_CHANNEL, FT_SELECT_POINT3D, FT_SELECT_RANGE, FT_SELECT_VOXEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_select_point.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_select_point3d` + +```{text} + FT_SELECT_POINT3D helper function for selecting one or multiple points on a 3D mesh + using the mouse. It returns a list of the [x y z] coordinates of the selected + points. + + Use as + [selected] = ft_select_point3d(bnd, ...) + + Optional input arguments should come in key-value pairs and can include + 'multiple' = true/false, make multiple selections, pressing "q" on the keyboard finalizes the selection (default = false) + 'nearest' = true/false (default = true) + 'marker' = character or empty, for example '.', 'o' or 'x' (default = []) + 'markersize' = scalar, the size of the marker (default = 10) + 'markercolor' = character, for example 'r', 'b' or 'g' (default = 'k') + + Example + [pos, tri] = mesh_sphere(162); + bnd.pos = pos; + bnd.tri = tri; + ft_plot_mesh(bnd) + camlight + ... do something here + + See also FT_SELECT_BOX, FT_SELECT_CHANNEL, FT_SELECT_POINT, FT_SELECT_RANGE, FT_SELECT_VOXEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_select_point3d.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_select_range` + +```{text} + FT_SELECT_RANGE is a helper function that can be used as callback function + in a figure. It allows the user to select a horizontal or a vertical + range, or one or multiple boxes. + + The callback function (and it's arguments) specified in callback is called + on a left-click inside a selection, or using the right-click context-menu. + The callback function will have as its first-to-last input argument the range of + all selections. The last input argument is either empty, or, when using the context + menu, a label of the item clicked. + Context menus are shown as the labels presented in the input. When activated, + the callback function is called, with the last input argument being the label of + the selection option. + + Input arguments: + 'event' = string, event used as hook. + 'callback' = function handle or cell-array containing function handle and additional input arguments + 'contextmenu' = cell-array containing labels shown in right-click menu + 'multiple' = boolean, allowing multiple selection boxes or not + 'xrange' = boolean, xrange variable or not + 'yrange' = boolean, yrange variable or not + 'clear' = boolean + + Example + x = randn(10,1); + y = randn(10,1); + figure; plot(x, y, '.'); + + The following example allows multiple horizontal and vertical selections to be made + set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', true, 'callback', @disp}); + set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', true, 'callback', @disp}); + set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', true, 'callback', @disp}); + + The following example allows a single horizontal selection to be made + set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); + set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); + set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); + + The following example allows a single point to be selected + set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); + set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); + set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); + + See also FT_SELECT_BOX, FT_SELECT_CHANNEL, FT_SELECT_POINT, FT_SELECT_POINT3D, FT_SELECT_VOXEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_select_range.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_select_voxel` + +```{text} + FT_SELECT_VOXEL is a helper function that can be used as callback function + in a figure. It allows the user to select a voxel from a (resliced) 3-D volume. + + Use as + voxel = ft_select_voxel(h, eventdata, ...) + The first two arguments are automatically passed by MATLAB to any + callback function. + + Additional options should be specified in key-value pairs and can be + 'callback' = function handle to be executed after channels have been selected + + You can pass additional arguments to the callback function in a cell-array + like {@function_handle,arg1,arg2} + + Example + % create a figure with a random 3-D volume + mri = rand(128,128,128); + ft_plot_slice(mri, 'location', [64 64 64], 'orientation', [1 1 1]); + view(120,30) + xlabel('x'); ylabel('y'); zlabel('z'); grid on + axis([0 128 0 128 0 128]) + axis equal; axis vis3d + axis([0 128 0 128 0 128]) + + % add this function as the callback to make a single selection + set(gcf, 'WindowButtonDownFcn', {@ft_select_voxel, 'callback', @disp}) + + Subsequently you can click in the figure and you'll see that the disp + function is executed as callback and that it displays the selected + voxel. + + See also FT_SELECT_BOX, FT_SELECT_CHANNEL, FT_SELECT_POINT, FT_SELECT_POINT3D, FT_SELECT_RANGE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_select_voxel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_selectdata` + +```{text} + FT_SELECTDATA makes a selection in the input data along specific data + dimensions, such as channels, time, frequency, trials, etc. It can also + be used to average the data along each of the specific dimensions. + + Use as + [data] = ft_selectdata(cfg, data, ...) + + The cfg argument is a configuration structure which can contain + cfg.tolerance = scalar, tolerance value to determine equality of time/frequency bins (default = 1e-5) + + For data with trials or subjects as repetitions, you can specify + cfg.trials = 1xN, trial indices to keep, can be 'all'. You can use logical indexing, where false(1,N) removes all the trials + cfg.avgoverrpt = string, can be 'yes' or 'no' (default = 'no') + + For data with a channel dimension you can specify + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION + cfg.avgoverchan = string, can be 'yes' or 'no' (default = 'no') + cfg.nanmean = string, can be 'yes' or 'no' (default = 'no') + + For data with channel combinations you can specify + cfg.channelcmb = Nx2 cell-array with selection of channels (default = 'all'), see FT_CHANNELCOMBINATION + cfg.avgoverchancmb = string, can be 'yes' or 'no' (default = 'no') + + For data with a time dimension you can specify + cfg.latency = scalar or string, can be 'all', 'minperiod', 'maxperiod', 'prestim', 'poststim', or [beg end], specify time range in seconds + cfg.avgovertime = string, can be 'yes' or 'no' (default = 'no') + cfg.nanmean = string, can be 'yes' or 'no' (default = 'no') + + For data with a frequency dimension you can specify + cfg.frequency = scalar or string, can be 'all', or [beg end], specify frequency range in Hz + cfg.avgoverfreq = string, can be 'yes' or 'no' (default = 'no') + cfg.nanmean = string, can be 'yes' or 'no' (default = 'no') + + When you average over a dimension, you can choose whether to keep that dimension in + the data representation or remove it altogether. + cfg.keeprptdim = 'yes' or 'no' (default is automatic) + cfg.keepchandim = 'yes' or 'no' (default = 'yes') + cfg.keepchancmbdim = 'yes' or 'no' (default = 'yes') + cfg.keeptimedim = 'yes' or 'no' (default = 'yes') + cfg.keepfreqdim = 'yes' or 'no' (default = 'yes') + + If multiple input arguments are provided, FT_SELECTDATA will adjust the individual + inputs such that either the INTERSECTION across inputs is retained (i.e. only the + channel, time, and frequency points that are shared across all input arguments), or + that the UNION across inputs is retained (replacing missing data with nans). In + either case, the order of the channels is made consistent across inputs. The + behavior can be specified with + cfg.select = string, can be 'intersect' or 'union' (default = 'intersect') + For raw data structures you cannot make the union. + + See also FT_DATATYPE, FT_CHANNELSELECTION, FT_CHANNELCOMBINATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_selectdata.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_senslabel` + +```{text} + FT_SENSLABEL returns a list of predefined sensor labels given the + EEG or MEG system type which can be used to detect the type of data. + + Use as + label = ft_senslabel(type) + + The input sensor array type can be any of the following + 'ant128' + 'biosemi64' + 'biosemi128' + 'biosemi256' + 'bti148' + 'bti148_planar' + 'bti248' + 'bti248_planar' + 'btiref' + 'ctf64' + 'ctf64_planar' + 'ctf151' + 'ctf151_planar' + 'ctf275' + 'ctf275_planar' + 'ctfheadloc' + 'ctfref' + 'eeg1005' + 'eeg1010' + 'eeg1020' + 'ext1020' + 'egi32' + 'egi64' + 'egi128' + 'egi256' + 'neuromag122' + 'neuromag122_planar' + 'neuromag306' + 'neuromag306_planar' + 'itab28' + 'itab153' + 'itab153_planar' + 'yokogawa9' + 'yokogawa64' + 'yokogawa64_planar' + 'yokogawa160' + 'yokogawa160_planar' + 'yokogawa208' + 'yokogawa208_planar' + 'yokogawa440' + 'yokogawa440_planar' + + It is also possible to specify + 'eeg' + 'electrode' + although for these an empty set of labels (i.e. {}) will be returned. + + See also FT_SENSTYPE, FT_CHANNELSELECTION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_senslabel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_senstype` + +```{text} + FT_SENSTYPE determines the type of acquisition device by looking at the channel + names and comparing them with predefined lists. + + Use as + [type] = ft_senstype(sens) + or + [flag] = ft_senstype(sens, desired) + + The output type can be any of the following + 'ctf64' + 'ctf151' + 'ctf151_planar' + 'ctf275' + 'ctf275_planar' + 'bti148' + 'bti148_planar' + 'bti248' + 'bti248_planar' + 'bti248grad' + 'bti248grad_planar' + 'itab28' + 'itab153' + 'itab153_planar' + 'yokogawa9' + 'yokogawa64' + 'yokogawa64_planar' + 'yokogawa160' + 'yokogawa160_planar' + 'yokogawa208' + 'yokogawa208_planar' + 'yokogawa440' + 'neuromag122' + 'neuromag122_combined' + 'neuromag306' + 'neuromag306_combined' + 'babysquid74' this is a BabySQUID system from Tristan Technologies + 'artemis123' this is a BabySQUID system from Tristan Technologies + 'magview' this is a BabySQUID system from Tristan Technologies + 'fieldline_v2' + 'fieldline_v3' + 'egi32' + 'egi64' + 'egi128' + 'egi256' + 'biosemi64' + 'biosemi128' + 'biosemi256' + 'ant128' + 'neuralynx' + 'plexon' + 'artinis' + 'nirx' + 'shimadzu' + 'hitachi' + 'nirs' + 'meg' + 'eeg' + 'ieeg' + 'seeg' + 'ecog' + 'eeg1020' + 'eeg1010' + 'eeg1005' + 'ext1020' in case it is a small subset of eeg1020, eeg1010 or eeg1005 + 'nex5' + + The optional input argument for the desired type can be any of the above, or any of + the following generic classes of acquisition systems + 'eeg' + 'ieeg' + 'ext1020' + 'ant' + 'biosemi' + 'egi' + 'meg' + 'meg_planar' + 'meg_axial' + 'ctf' + 'bti' + 'neuromag' + 'yokogawa' + 'itab' + 'babysquid' + 'fieldline' + If you specify the desired type, this function will return a boolean flag + indicating true/false depending on the input data. + + Besides specifiying a sensor definition (i.e. a grad or elec structure, see + FT_DATATYPE_SENS), it is also possible to give a data structure containing a grad + or elec field, or giving a list of channel names (as cell-arrray). So assuming that + you have a FieldTrip data structure, any of the following calls would also be fine. + ft_senstype(hdr) + ft_senstype(data) + ft_senstype(data.label) + ft_senstype(data.grad) + ft_senstype(data.grad.label) + + See also FT_SENSLABEL, FT_CHANTYPE, FT_READ_SENS, FT_COMPUTE_LEADFIELD, FT_DATATYPE_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_senstype.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_setopt` + +```{text} + FT_SETOPT assigns a value to an configuration structure or to a cell-array + with key-value pairs. It will overwrite the option if already present, or + append the option if not present. + + Use as + s = ft_setopt(s, key, val) + where s is a structure or a cell-array. + + See also FT_GETOPT, FT_CHECKOPT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_setopt.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_singleplotER` + +```{text} + FT_SINGLEPLOTER plots the event-related fields or potentials of a single + channel or the average over multiple channels. Multiple datasets can be + overlayed. + + Use as + ft_singleplotER(cfg, data) + or + ft_singleplotER(cfg, data1, data2, ..., datan) + + The data can be an erp/erf produced by FT_TIMELOCKANALYSIS, a power + spectrum or time-frequency respresentation produced by FT_FREQANALYSIS or + a connectivity spectrum produced by FT_CONNECTIVITYANALYSIS. + + The configuration can have the following parameters: + cfg.parameter = field to be plotted on y-axis, for example 'avg', 'powspctrm' or 'cohspctrm' (default is automatic) + cfg.maskparameter = field in the first dataset to be used for masking of data; this is not supported when + computing the mean over multiple channels, or when giving multiple input datasets (default = []) + cfg.maskstyle = style used for masking of data, 'box', 'thickness' or 'saturation' (default = 'box') + cfg.maskfacealpha = mask transparency value between 0 and 1 + cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin') + cfg.ylim = 'maxmin', 'maxabs', 'zeromax', 'minzero', or [ymin ymax] (default = 'maxmin') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.title = string, title of plot + cfg.showlegend = 'yes' or 'no', show the legend with the colors (default = 'no') + cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' + cfg.baseline = 'yes', 'no' or [time1 time2] (default = 'no'), see ft_timelockbaseline + cfg.baselinetype = 'absolute', 'relative', 'relchange', 'normchange', 'db', 'vssum' or 'zscore' (default = 'absolute'), only relevant for TFR data. + See ft_freqbaseline. + cfg.trials = 'all' or a selection given as a 1xn vector (default = 'all') + cfg.fontsize = font size of title (default = 8) + cfg.hotkeys = enables hotkeys (leftarrow/rightarrow/uparrow/downarrow/m) for dynamic zoom and translation (ctrl+) of the axes + cfg.interactive = interactive plot 'yes' or 'no' (default = 'yes') + in a interactive plot you can select areas and produce a new + interactive plot when a selected area is clicked. multiple areas + can be selected by holding down the shift key. + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + cfg.linestyle = linestyle/marker type, see options of the PLOT function (default = '-') + can be a single style for all datasets, or a cell-array containing one style for each dataset + cfg.linewidth = linewidth in points (default = 0.5) + cfg.linecolor = color(s) used for plotting the dataset(s). The default is defined in LINEATTRIBUTES_COMMON, see + the help of this function for more information + cfg.directionality = '', 'inflow' or 'outflow' specifies for + connectivity measures whether the inflow into a + node, or the outflow from a node is plotted. The + (default) behavior of this option depends on the dimor + of the input data (see below). + cfg.select = 'intersect' or 'union' (default = 'intersect') + with multiple input arguments determines the + pre-selection of the data that is considered for + plotting. + cfg.showlocations = 'no' (default), or 'yes'. plot a small spatial layout of all sensors, highlighting the specified subset + cfg.layouttopo = filename, or struct (see FT_PREPARE_LAYOUT) used for showing the locations with cfg.showlocations = 'yes' + + The following options for the scaling of the EEG, EOG, ECG, EMG, MEG and NIRS channels + is optional and can be used to bring the absolute numbers of the different + channel types in the same range (e.g. fT and uV). The channel types are determined + from the input data using FT_CHANNELSELECTION. + cfg.eegscale = number, scaling to apply to the EEG channels prior to display + cfg.eogscale = number, scaling to apply to the EOG channels prior to display + cfg.ecgscale = number, scaling to apply to the ECG channels prior to display + cfg.emgscale = number, scaling to apply to the EMG channels prior to display + cfg.megscale = number, scaling to apply to the MEG channels prior to display + cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor) + cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor) + cfg.nirsscale = number, scaling to apply to the NIRS channels prior to display + cfg.mychanscale = number, scaling to apply to the channels specified in cfg.mychan + cfg.mychan = Nx1 cell-array with selection of channels + cfg.chanscale = Nx1 vector with scaling factors, one per channel specified in cfg.channel + + For the plotting of directional connectivity data the cfg.directionality + option determines what is plotted. The default value and the supported + functionality depend on the dimord of the input data. If the input data + is of dimord 'chan_chan_XXX', the value of directionality determines + whether, given the reference channel(s), the columns (inflow), or rows + (outflow) are selected for plotting. In this situation the default is + 'inflow'. Note that for undirected measures, inflow and outflow should + give the same output. If the input data is of dimord 'chancmb_XXX', the + value of directionality determines whether the rows in data.labelcmb are + selected. With 'inflow' the rows are selected if the refchannel(s) occur in + the right column, with 'outflow' the rows are selected if the + refchannel(s) occur in the left column of the labelcmb-field. Default in + this case is '', which means that all rows are selected in which the + refchannel(s) occur. This is to robustly support linearly indexed + undirected connectivity metrics. In the situation where undirected + connectivity measures are linearly indexed, specifying 'inflow' or + 'outflow' can result in unexpected behavior. + + to facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + if you specify this option the input data will be read from a *.mat + file on disk. this mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_SINGLEPLOTTFR, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_singleplotER.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_singleplotTFR` + +```{text} + FT_SINGLEPLOTTFR plots the time-frequency representation of power of a + single channel or the average over multiple channels. + + Use as + ft_singleplotTFR(cfg,data) + + The input freq structure should be a a time-frequency representation of + power or coherence that was computed using the FT_FREQANALYSIS function. + + The configuration can have the following parameters: + cfg.parameter = field to be plotted on z-axis, e.g. 'powspctrm' (default depends on data.dimord) + cfg.maskparameter = field in the data to be used for masking of data, can be logical (e.g. significant data points) or numerical (e.g. t-values). + (not possible for mean over multiple channels, or when input contains multiple subjects + or trials) + cfg.maskstyle = style used to masking, 'opacity', 'saturation', or 'outline' (default = 'opacity') + 'outline' can only be used with a logical cfg.maskparameter + use 'saturation' or 'outline' when saving to vector-format (like *.eps) to avoid all sorts of image-problems + cfg.maskalpha = alpha value between 0 (transparent) and 1 (opaque) used for masking areas dictated by cfg.maskparameter (default = 1) + (will be ignored in case of numeric cfg.maskparameter or if cfg.maskstyle = 'outline') + cfg.masknans = 'yes' or 'no' (default = 'yes') + cfg.xlim = 'maxmin' or [xmin xmax] (default = 'maxmin') + cfg.ylim = 'maxmin' or [ymin ymax] (default = 'maxmin') + cfg.zlim = plotting limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.baseline = 'yes', 'no' or [time1 time2] (default = 'no'), see FT_FREQBASELINE + cfg.baselinetype = 'absolute', 'relative', 'relchange', 'normchange', 'db' or 'zscore' (default = 'absolute') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.title = string, title of plot + cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' + cfg.fontsize = font size of title (default = 8) + cfg.hotkeys = enables hotkeys (leftarrow/rightarrow/uparrow/downarrow/pageup/pagedown/m) for dynamic zoom and translation (ctrl+) of the axes and color limits + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + cfg.colorbar = 'yes', 'no' (default = 'yes') + cfg.colorbartext = string indicating the text next to colorbar + cfg.interactive = interactive plot 'yes' or 'no' (default = 'yes') + In a interactive plot you can select areas and produce a new + interactive plot when a selected area is clicked. Multiple areas + can be selected by holding down the SHIFT key. + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + cfg.directionality = '', 'inflow' or 'outflow' specifies for + connectivity measures whether the inflow into a + node, or the outflow from a node is plotted. The + (default) behavior of this option depends on the dimor + of the input data (see below). + + The following options for the scaling of the EEG, EOG, ECG, EMG, MEG and NIRS channels + is optional and can be used to bring the absolute numbers of the different + channel types in the same range (e.g. fT and uV). The channel types are determined + from the input data using FT_CHANNELSELECTION. + cfg.eegscale = number, scaling to apply to the EEG channels prior to display + cfg.eogscale = number, scaling to apply to the EOG channels prior to display + cfg.ecgscale = number, scaling to apply to the ECG channels prior to display + cfg.emgscale = number, scaling to apply to the EMG channels prior to display + cfg.megscale = number, scaling to apply to the MEG channels prior to display + cfg.gradscale = number, scaling to apply to the MEG gradiometer channels prior to display (in addition to the cfg.megscale factor) + cfg.magscale = number, scaling to apply to the MEG magnetometer channels prior to display (in addition to the cfg.megscale factor) + cfg.nirsscale = number, scaling to apply to the NIRS channels prior to display + cfg.mychanscale = number, scaling to apply to the channels specified in cfg.mychan + cfg.mychan = Nx1 cell-array with selection of channels + cfg.chanscale = Nx1 vector with scaling factors, one per channel specified in cfg.channel + + For the plotting of directional connectivity data the cfg.directionality + option determines what is plotted. The default value and the supported + functionality depend on the dimord of the input data. If the input data + is of dimord 'chan_chan_XXX', the value of directionality determines + whether, given the reference channel(s), the columns (inflow), or rows + (outflow) are selected for plotting. In this situation the default is + 'inflow'. Note that for undirected measures, inflow and outflow should + give the same output. If the input data is of dimord 'chancmb_XXX', the + value of directionality determines whether the rows in data.labelcmb are + selected. With 'inflow' the rows are selected if the refchannel(s) occur in + the right column, with 'outflow' the rows are selected if the + refchannel(s) occur in the left column of the labelcmb-field. Default in + this case is '', which means that all rows are selected in which the + refchannel(s) occur. This is to robustly support linearly indexed + undirected connectivity metrics. In the situation where undirected + connectivity measures are linearly indexed, specifying 'inflow' or + 'outflow' can result in unexpected behavior. + + See also FT_SINGLEPLOTER, FT_MULTIPLOTER, FT_MULTIPLOTTFR, FT_TOPOPLOTER, FT_TOPOPLOTTFR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_singleplotTFR.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sliceinterp` + +```{text} + FT_SLICEINTERP plots a 2D-montage of source reconstruction and anatomical MRI + after these have been interpolated onto the same grid. + + Use as + ft_sliceinterp(cfg, interp) + or + [rgbimage] = ft_sliceinterp(cfg, interp), rgbimage is the monatage image + + where interp is the output of sourceinterpolate and cfg is a structure + with any of the following fields: + + cfg.funparameter = string with the functional parameter of interest (default = 'source') + cfg.maskparameter = parameter used as opacity mask (default = 'none') + cfg.clipmin = value or 'auto' (clipping of source data) + cfg.clipmax = value or 'auto' (clipping of source data) + cfg.clipsym = 'yes' or 'no' (default) symmetrical clipping + cfg.colormap = colormap for source overlay (default is jet(128)) + cfg.colmin = source value mapped to the lowest color (default = 'auto') + cfg.colmax = source value mapped to the highest color (default = 'auto') + cfg.maskclipmin = value or 'auto' (clipping of mask data) + cfg.maskclipmax = value or 'auto' (clipping of mask data) + cfg.maskclipsym = 'yes' or 'no' (default) symmetrical clipping + cfg.maskmap = opacitymap for source overlay (default is linspace(0,1,128)) + cfg.maskcolmin = mask value mapped to the lowest opacity, i.e. completely transparent (default ='auto') + cfg.maskcolmin = mask value mapped to the highest opacity, i.e. non-transparent (default = 'auto') + cfg.alpha = value between 0 and 1 or 'adaptive' (default) + cfg.nslices = integer value, default is 20 + cfg.dim = integer value, default is 3 (dimension to slice) + cfg.spacemin = 'auto' (default) or integer (first slice position) + cfg.spacemax = 'auto' (default) or integer (last slice position) + cfg.resample = integer value, default is 1 (for resolution reduction) + cfg.rotate = number of ccw 90 deg slice rotations (default = 0) + cfg.title = optional title (default is '') + cfg.whitebg = 'yes' or 'no' (default = 'yes') + cfg.flipdim = flip data along the sliced dimension, 'yes' or 'no' (default = 'no') + cfg.marker = [Nx3] array defining N marker positions to display + cfg.markersize = radius of markers (default = 5); + cfg.markercolor = [1x3] marker color in RGB (default = [1 1 1], i.e. white) + cfg.interactive = 'yes' or 'no' (default), interactive coordinates and source values + + if cfg.alpha is set to 'adaptive' the opacity of the source overlay + linearly follows the source value: maxima are opaque and minima are + transparent. + + if cfg.spacemin and/or cfg.spacemax are set to 'auto' the sliced + space is automatically restricted to the evaluated source-space + + if cfg.colmin and/or cfg.colmax are set to 'auto' the colormap is mapped + to source values the following way: if source values are either all + positive or all negative the colormap is mapped to from + min(source) to max(source). If source values are negative and positive + the colormap is symmetrical mapped around 0 from -max(abs(source)) to + +max(abs(source)). + + If cfg.maskparameter specifies a parameter to be used as an opacity mask + cfg.alpha is not used. Instead the mask values are maped to an opacitymap + that can be specified using cfg.maskmap. The mapping onto that + opacitymap is controlled as for the functional data using the + corresponding clipping and min/max options. + + if cfg.whitebg is set to 'yes' the function estimates the head volume and + displays a white background outside the head, which can save a lot of black + printer toner. + + if cfg.interactive is set to 'yes' a button will be displayed for + interactive data evaluation and coordinate reading. After clicking the + button named 'coords' you can click on any position in the slice montage. + After clicking these coordinates and their source value are displayed in + a text box below the button. The coordinates correspond to indeces in the + input data array: + + f = interp.source(coord_1,coord_2,coord_3) + + The coordinates are not affected by any transformations used for displaying + the data such as cfg.dim, cfg.rotate,cfg.flipdim or cfg.resample. + + See also FT_SOURCEANALYSIS, FT_VOLUMERESLICE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sliceinterp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_source2full` + +```{text} + FT_SOURCE2FULL recreates the grid locations outside the brain in the source + reconstruction, so that the source volume again describes the full grid. + This undoes the memory savings that can be achieved using FT_SOURCE2SPARSE + and makes it possible again to plot the source volume and save it to an + external file. + + Use as + [source] = ft_source2full(source) + + See also FT_SOURCE2SPARSE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_source2full.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_source2grid` + +```{text} + FT_SOURCE2GRID removes the fields from a source structure that are + not necessary to reuse the dipole grid in another source estimation. + + Use as + [grid] = ft_source2grid(source); + + The resulting grid can be used in the configuration of another + run of FT_SOURCEANALYSIS. + + See also FTSOURCE2SPARSE, FT_SOURCE2FULL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_source2grid.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_source2sparse` + +```{text} + FT_SOURCE2SPARSE removes the grid locations outside the brain from the source + reconstruction, thereby saving memory. + + This invalidates the fields that describe the grid, and also makes it + more difficult to make a plot of each of the slices of the source volume. + The original source structure can be recreated using FT_SOURCE2FULL. + + Use as + [source] = ft_source2sparse(source) + + See also FT_SOURCE2FULL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_source2sparse.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourceanalysis` + +```{text} + FT_SOURCEANALYSIS performs beamformer dipole analysis on EEG or MEG data + after preprocessing and a timelocked or frequency analysis + + Use as + [source] = ft_sourceanalysis(cfg, freq) + or + [source] = ft_sourceanalysis(cfg, timelock) + + where the second input argument with the data should be organised in a structure + as obtained from the FT_FREQANALYSIS or FT_TIMELOCKANALYSIS function. The + configuration "cfg" is a structure containing the specification of the head model, + the source model, and other options. + + The different source reconstruction algorithms that are implemented are + cfg.method = 'lcmv' linear constrained minimum variance beamformer + 'sam' synthetic aperture magnetometry + 'dics' dynamic imaging of coherent sources + 'pcc' partial canonical correlation/coherence + 'mne' minimum norm estimation + 'rv' scan residual variance with single dipole + 'music' multiple signal classification + 'sloreta' standardized low-resolution electromagnetic tomography + 'eloreta' exact low-resolution electromagnetic tomography + The DICS and PCC methods are for frequency or time-frequency domain data, all other + methods are for time domain data. ELORETA can be used both for time, frequency and + time-frequency domain data. + + The complete grid with dipole positions and optionally precomputed leadfields is + constructed using FT_PREPARE_SOURCEMODEL. It can be specified as as a regular 3-D + grid that is aligned with the axes of the head coordinate system using + cfg.xgrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.ygrid = vector (e.g. -20:1:20) or 'auto' (default = 'auto') + cfg.zgrid = vector (e.g. 0:1:20) or 'auto' (default = 'auto') + cfg.resolution = number (e.g. 1 cm) for automatic grid generation + If the source model destribes a triangulated cortical sheet, it is described as + cfg.sourcemodel.pos = N*3 matrix with the vertex positions of the cortical sheet + cfg.sourcemodel.tri = M*3 matrix that describes the triangles connecting the vertices + Alternatively the position of a few dipoles at locations of interest can be + user-specified, for example obtained from an anatomical or functional MRI + cfg.sourcemodel.pos = N*3 matrix with position of each source + cfg.sourcemodel.inside = N*1 vector with boolean value whether grid point is inside brain (optional) + cfg.sourcemodel.dim = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional) + + Besides the source positions, you may also include previously computed + spatial filters and/or leadfields using + cfg.sourcemodel.filter + cfg.sourcemodel.leadfield + + The following strategies are supported to obtain statistics for the source parameters using + multiple trials in the data, either directly or through a resampling-based approach + cfg.rawtrial = 'no' or 'yes' construct filter from single trials, apply to single trials. Note that you also may want to set cfg.keeptrials='yes' to keep all trial information, especially if using in combination with sourcemodel.filter + cfg.jackknife = 'no' or 'yes' jackknife resampling of trials + cfg.pseudovalue = 'no' or 'yes' pseudovalue resampling of trials + cfg.bootstrap = 'no' or 'yes' bootstrap resampling of trials + cfg.numbootstrap = number of bootstrap replications (e.g. number of original trials) + If none of these options is specified, the average over the trials will + be computed prior to computing the source reconstruction. + + To obtain statistics over the source parameters between two conditions, you + can also use a resampling procedure that reshuffles the trials over both + conditions. In that case, you should call the function with two datasets + containing single trial data like + [source] = ft_sourceanalysis(cfg, freqA, freqB) + [source] = ft_sourceanalysis(cfg, timelockA, timelockB) + and you should specify + cfg.randomization = 'no' or 'yes' + cfg.permutation = 'no' or 'yes' + cfg.numrandomization = number, e.g. 500 + cfg.numpermutation = number, e.g. 500 or 'all' + + If you have not specified a sourcemodel with pre-computed leadfields, the leadfield + for each source position will be computed on the fly, in the lower level function that + is called for the heavy lifting. In that case you can modify parameters for the forward + computation, e.g. by reducing the rank (i.e. remove the weakest orientation), or by + normalizing each column. + cfg.reducerank = 'no', or number (default = 3 for EEG, 2 for MEG) + cfg.backproject = 'yes' or 'no', determines when reducerank is applied whether the + lower rank leadfield is projected back onto the original linear + subspace, or not (default = 'yes') + cfg.normalize = 'yes' or 'no' (default = 'no') + cfg.normalizeparam = depth normalization parameter (default = 0.5) + cfg.weight = number or Nx1 vector, weight for each dipole position to compensate + for the size of the corresponding patch (default = 1) + + Other configuration options are + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.frequency = single number (in Hz) + cfg.latency = single number in seconds, for time-frequency analysis + cfg.refchan = reference channel label (for coherence) + cfg.refdip = reference dipole location (for coherence) + cfg.supchan = suppressed channel label(s) + cfg.supdip = suppressed dipole location(s) + cfg.keeptrials = 'no' or 'yes' + cfg.keepleadfield = 'no' or 'yes' + + Some options need to be specified as method specific options, and determine the low-level computation of the inverse operator. + The functionality (and applicability) of the (sub-)options are documented in the lower-level ft_inverse_ functions. + Replace with one of the supported methods. + cfg..lambda = number or empty for automatic default + cfg..kappa = number or empty for automatic default + cfg..tol = number or empty for automatic default + cfg..projectnoise = 'no' or 'yes' + cfg..keepfilter = 'no' or 'yes' + cfg..keepcsd = 'no' or 'yes' + cfg..keepmom = 'no' or 'yes' + cfg..feedback = 'no', 'text', 'textbar', 'gui' (default = 'text') + + The volume conduction model of the head should be specified as + cfg.headmodel = structure with volume conduction model, see FT_PREPARE_HEADMODEL + + The EEG or MEG sensor positions can be present in the data or can be specified as + cfg.elec = structure with electrode positions or filename, see FT_READ_SENS + cfg.grad = structure with gradiometer definition or filename, see FT_READ_SENS + + 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_SOURCEDESCRIPTIVES, FT_SOURCESTATISTICS, FT_PREPARE_LEADFIELD, + FT_PREPARE_HEADMODEL, FT_PREPARE_SOURCEMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourceanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourcedepth` + +```{text} + FT_SOURCEDEPTH computes the distance from the source to the surface of + the source compartment (usually the brain) in the volume conduction model. + + Use as + depth = ft_sourcedepth(dippos, headmodel); + where + dippos = Nx3 matrix with the position of N sources + headmodel = structure describing volume condition model + + A negative depth indicates that the source is inside the source + compartment, positive indicates outside. + + See also FT_INSIDE_HEADMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/forward/ft_sourcedepth.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourcedescriptives` + +```{text} + FT_SOURCEDESCRIPTIVES computes descriptive parameters of the source + analysis results. + + Use as + [source] = ft_sourcedescriptives(cfg, source) + + where cfg is a structure with the configuration details and source is the + result from a beamformer source estimation. The configuration can contain + cfg.cohmethod = 'regular', 'lambda1', 'canonical' + cfg.powmethod = 'regular', 'lambda1', 'trace', 'none' + cfg.supmethod = 'chan_dip', 'chan', 'dip', 'none' (default) + cfg.projectmom = 'yes' or 'no' (default = 'no') + cfg.eta = 'yes' or 'no' (default = 'no') + cfg.kurtosis = 'yes' or 'no' (default = 'no') + cfg.keeptrials = 'yes' or 'no' (default = 'no') + cfg.keepcsd = 'yes' or 'no' (default = 'no') + cfg.keepnoisecsd = 'yes' or 'no' (default = 'no') + cfg.keepmom = 'yes' or 'no' (default = 'yes') + cfg.keepnoisemom = 'yes' or 'no' (default = 'yes') + cfg.resolutionmatrix = 'yes' or 'no' (default = 'no') + cfg.feedback = 'no', 'text' (default), 'textbar', 'gui' + + The following option only applies to timecourses. + cfg.flipori = 'yes' or 'no' (default = 'no') + + The following option only applies to single-trial timecourses. + cfg.fixedori = 'within_trials' or 'over_trials' (default = 'over_trials') + + If repeated trials are present that have undergone some sort of + resampling (i.e. jackknife, bootstrap, singletrial or rawtrial), the mean, + variance and standard error of mean will be computed for all source + parameters. This is done after applying the optional transformation + on the power and projected noise. + + 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_SOURCEANALYSIS, FT_SOURCESTATISTICS, FT_MATH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourcedescriptives.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourcegrandaverage` + +```{text} + FT_SOURCEGRANDAVERAGE averages source reconstructions over either multiple + subjects or conditions. It computes the average and variance for all + known source parameters. The output can be used in FT_SOURCESTATISTICS + with the method 'parametric'. + + Alternatively, it can construct an average for multiple input source + reconstructions in two conditions after randomly reassigning the + input data over the two conditions. The output then can be used in + FT_SOURCESTATISTICS with the method 'randomization' or 'randcluster'. + + The input source structures should be spatially alligned to each other + and should have the same positions for the sourcemodel. + + Use as + [grandavg] = ft_sourcegrandaverage(cfg, source1, source2, ...) + + where the source structures are obtained from FT_SOURCEANALYSIS or + from FT_VOLUMENORMALISE, and the configuration can contain the + following fields: + cfg.parameter = string, describing the functional data to be processed, e.g. 'pow', 'nai' or 'coh' + cfg.keepindividual = 'no' or 'yes' + + 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. For this particular function, the input data + should be structured as a single cell-array. + + See also FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES, FT_SOURCESTATISTICS, FT_MATH + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourcegrandaverage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourceinterpolate` + +```{text} + FT_SOURCEINTERPOLATE interpolates source activity or statistical maps onto the + voxels or vertices of an anatomical description of the brain. Both the functional + and the anatomical data can either describe a volumetric 3D regular grid, a + triangulated description of the cortical sheet or an arbitrary cloud of points. + + The functional data in the output data will be interpolated at the locations at + which the anatomical data are defined. For example, if the anatomical data was + volumetric, the output data is a volume-structure, containing the resliced source + and the anatomical volume that can be visualized using FT_SOURCEPLOT or written to + file using FT_SOURCEWRITE. + + The following scenarios can be considered: + + - Both functional data and anatomical data are defined on 3D regular grids, for + example with a low-res grid for the functional data and a high-res grid for the + anatomy. + + - The functional data is defined on a 3D regular grid and the anatomical data is + defined on an irregular point cloud, which can be a 2D triangulated surface mesh. + + - The functional data is defined on an irregular point cloud, which can be a 2D + triangulated surface mesh, and the anatomical data is defined on a 3D regular grid. + + - Both the functional and the anatomical data are defined on an irregular point + cloud, which can be a 2D triangulated mesh. + + - The functional data is defined on a low-resolution 2D triangulated surface mesh and the + anatomical data is defined on a high-resolution 2D triangulated surface mesh, where the + low-res vertices form a subset of the high-res vertices. This allows for mesh-based + interpolation. The algorithm currently implemented is so-called 'smudging' as it is + also applied by the MNE-suite software. + + Use as + [interp] = ft_sourceinterpolate(cfg, source, anatomy) + [interp] = ft_sourceinterpolate(cfg, stat, anatomy) + where + source is the output of FT_SOURCEANALYSIS + stat is the output of FT_SOURCESTATISTICS + anatomy is the output of FT_READ_MRI, or one of the FT_VOLUMExxx functions, + or a cortical sheet that was read with FT_READ_HEADSHAPE, + or a regular 3D grid created with FT_PREPARE_SOURCEMODEL. + + The configuration should contain: + cfg.parameter = string or cell-array with the functional parameter(s) to be interpolated + cfg.downsample = integer number (default = 1, i.e. no downsampling) + cfg.interpmethod = string, can be 'nearest', 'linear', 'cubic', 'spline', 'sphere_avg', 'sphere_weighteddistance', or 'smudge' (default = 'linear for interpolating two 3D volumes, 'nearest' for all other cases) + + For interpolating two 3D regular grids or volumes onto each other the supported + interpolation methods are 'nearest', 'linear', 'cubic' or 'spline'. For all other + cases the supported interpolation methods are 'nearest', 'sphere_avg', + 'sphere_weighteddistance' or 'smudge'. + + The functional and anatomical data should be expressed in the same + coordinate sytem, i.e. either both in MEG headcoordinates (NAS/LPA/RPA) + or both in SPM coordinates (AC/PC). + + 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_READ_MRI, FT_READ_HEADSHAPE, FT_SOURCEPLOT, FT_SOURCEANALYSIS, + FT_SOURCEWRITE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourceinterpolate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourcemovie` + +```{text} + FT_SOURCEMOVIE displays the source reconstruction on a cortical mesh + and allows the user to scroll through time with a movie. + + Use as + ft_sourcemovie(cfg, source) + where the input source data is obtained from FT_SOURCEANALYSIS, or a + a parcellated source structure (i.e. contains a brainordinate field) and + cfg is a configuration structure that should contain + + cfg.funparameter = string, functional parameter that is color coded (default = 'avg.pow') + cfg.maskparameter = string, functional parameter that is used for opacity (default = []) + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_SOURCEPLOT, FT_SOURCEINTERPOLATE, FT_SOURCEPARCELLATE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourcemovie.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourceparcellate` + +```{text} + FT_SOURCEPARCELLATE combines the source-reconstruction parameters over the parcels, for + example by averaging all the values in the anatomically or functionally labeled parcel. + + Use as + output = ft_sourceparcellate(cfg, source, parcellation) + where the input source is a 2D surface-based or 3-D voxel-based source grid that was for + example obtained from FT_SOURCEANALYSIS or FT_COMPUTE_LEADFIELD. The input parcellation is + described in detail in FT_DATATYPE_PARCELLATION (2-D) or FT_DATATYPE_SEGMENTATION (3-D) and + can be obtained from FT_READ_ATLAS or from a custom parcellation/segmentation for your + individual subject. The output is a channel-based representation with the combined (e.g. + averaged) representation of the source parameters per parcel. + + The configuration "cfg" is a structure that can contain the following fields + cfg.method = string, method to combine the values, see below (default = 'mean') + cfg.parcellation = string, fieldname that contains the desired parcellation + cfg.parameter = cell-array with strings, fields that should be parcellated (default = 'all') + + The values within a parcel or parcel-combination can be combined with different methods: + 'mean' compute the mean + 'median' compute the median (unsupported for fields that are represented in a cell-array) + 'eig' compute the largest eigenvector + 'min' take the minimal value + 'max' take the maximal value + 'maxabs' take the signed maxabs value + 'std' take the standard deviation + + See also FT_SOURCEANALYSIS, FT_DATATYPE_PARCELLATION, FT_DATATYPE_SEGMENTATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourceparcellate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourceplot` + +```{text} + FT_SOURCEPLOT plots functional source reconstruction data on slices or on a surface, + optionally as an overlay on anatomical MRI data, where statistical data can be used to + determine the opacity of the mask. Input data comes from FT_SOURCEANALYSIS, + FT_SOURCEGRANDAVERAGE or statistical values from FT_SOURCESTATISTICS. + + Use as + ft_sourceplot(cfg, anatomical) + ft_sourceplot(cfg, functional) + ft_sourceplot(cfg, functional, anatomical) + where the input data can contain either anatomical, functional or statistical data, + or a combination of them. + + The input data can be in a 3-D volumetric representation or in a 2-D cortical sheet + representation. If both anatomical and functional/statistical data is provided as input, + they should be represented in the same coordinate system or interpolated on the same + geometrical representation, e.g. using FT_SOURCEINTERPOLATE. + + The slice and ortho visualization plot the data in the input data voxel arrangement, i.e. + the three ortho views are the 1st, 2nd and 3rd dimension of the 3-D data matrix, not of + the head coordinate system. The specification of the coordinate for slice intersection + is specified in head coordinates, i.e. relative to anatomical landmarks or fiducials and + expressed in mm or cm. If you want the visualisation to be consistent with the head + coordinate system, you can reslice the data using FT_VOLUMERESLICE. See http://bit.ly/1OkDlVF + + The configuration should contain: + cfg.method = 'ortho', plots the data on three orthogonal slices + 'slice', plots the data on a number of slices in the same plane + 'surface', plots the data on a 3D brain surface + 'glassbrain', plots a max-projection through the brain + 'vertex', plots the grid points or vertices scaled according to the functional value + 'cloud', plot the data as clouds, spheres, or points scaled according to the functional value + and + cfg.anaparameter = string, field in data with the anatomical data (default = 'anatomy' if present in data) + cfg.funparameter = string, field in data with the functional parameter of interest (default = []) + cfg.maskparameter = string, field in the data to be used for opacity masking of fun data (default = []) + If values are between 0 and 1, zero is fully transparant and one is fully opaque. + If values in the field are not between 0 and 1 they will be scaled depending on the values + of cfg.opacitymap and cfg.opacitylim (see below) + You can use masking in several ways, f.i. + - use outcome of statistics to show only the significant values and mask the insignificant + NB see also cfg.opacitymap and cfg.opacitylim below + - use the functional data itself as mask, the highest value (and/or lowest when negative) + will be opaque and the value closest to zero transparent + - Make your own field in the data with values between 0 and 1 to control opacity directly + + The following parameters can be used in all methods: + cfg.downsample = downsampling for resolution reduction, integer value (default = 1) (orig: from surface) + cfg.atlas = string, filename of atlas to use (default = []) see FT_READ_ATLAS + for ROI masking (see 'masking' below) or for orthogonal plots (see method='ortho' below) + cfg.visible = string, 'on' or 'off' whether figure will be visible (default = 'on') + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO. The OpenGL renderer is required when using opacity (default = 'opengl') + + The following parameters can be used for the functional data: + cfg.funcolormap = colormap for functional data, see COLORMAP (default = 'auto') + 'auto', depends structure funparameter, or on funcolorlim + - funparameter: only positive values, or funcolorlim:'zeromax' -> 'hot' + - funparameter: only negative values, or funcolorlim:'minzero' -> 'cool' + - funparameter: both pos and neg values, or funcolorlim:'maxabs' -> 'default' + - funcolorlim: [min max] if min & max pos-> 'hot', neg-> 'cool', both-> 'default' + cfg.funcolorlim = color range of the functional data (default = 'auto') + [min max] + 'maxabs', from -max(abs(funparameter)) to +max(abs(funparameter)) + 'zeromax', from 0 to max(funparameter) + 'minzero', from min(funparameter) to 0 + 'auto', if funparameter values are all positive: 'zeromax', + all negative: 'minzero', both possitive and negative: 'maxabs' + cfg.colorbar = 'yes' or 'no' (default = 'yes') + cfg.colorbartext = string indicating the text next to colorbar + + The 'ortho' method can also plot time and/or frequency, the other methods can not. + If your functional data has a time and/or frequency dimension, you can use + cfg.latency = scalar or string, can be 'all', 'prestim', 'poststim', or [beg end], specify time range in seconds + cfg.avgovertime = string, can be 'yes' or 'no' (default = 'no') + cfg.frequency = scalar or string, can be 'all', or [beg end], specify frequency range in Hz + cfg.avgoverfreq = string, can be 'yes' or 'no' (default = 'no') + + The following parameters can be used for the masking data: + cfg.maskstyle = 'opacity', or 'colormix'. If 'opacity', low-level + graphics opacity masking is applied, if + 'colormix', the color data is explicitly + expressed as a single RGB value, incorporating + the opacitymask. Yields faster and more robust + rendering in general. + cfg.opacitymap = opacitymap for mask data, see ALPHAMAP (default = 'auto') + 'auto', depends structure maskparameter, or on opacitylim + - maskparameter: only positive values, or opacitylim:'zeromax' -> 'rampup' + - maskparameter: only negative values, or opacitylim:'minzero' -> 'rampdown' + - maskparameter: both pos and neg values, or opacitylim:'maxabs' -> 'vdown' + - opacitylim: [min max] if min & max pos-> 'rampup', neg-> 'rampdown', both-> 'vdown' + - NB. to use p-values use 'rampdown' to get lowest p-values opaque and highest transparent + cfg.opacitylim = range of mask values to which opacitymap is scaled (default = 'auto') + [min max] + 'maxabs', from -max(abs(maskparameter)) to +max(abs(maskparameter)) + 'zeromax', from 0 to max(abs(maskparameter)) + 'minzero', from min(abs(maskparameter)) to 0 + 'auto', if maskparameter values are all positive: 'zeromax', + all negative: 'minzero', both positive and negative: 'maxabs' + cfg.roi = string or cell of strings, region(s) of interest from anatomical atlas (see cfg.atlas above) + everything is masked except for ROI + + When cfg.method='ortho', three orthogonal slices will be rendered. You can click in any + of the slices to update the display in the other two. You can also use the arrow keys on + your keyboard to navigate in one-voxel steps. Note that the slices are along the first, + second and third voxel dimension, which do not neccessarily correspond to the axes of the + head coordinate system. See http://bit.ly/1OkDlVF + + The following parameters apply when cfg.method='ortho' + cfg.location = location of cut, (default = 'auto') + 'auto', 'center' if only anatomy, 'max' if functional data + 'min' and 'max' position of min/max funparameter + 'center' of the brain + [x y z], coordinates in voxels or head, see cfg.locationcoordinates + cfg.locationcoordinates = coordinate system used in cfg.location, 'head' or 'voxel' (default = 'head') + 'head', headcoordinates as mm or cm + 'voxel', voxelcoordinates as indices + cfg.crosshair = 'yes' or 'no' (default = 'yes') + cfg.axis = 'on' or 'off' (default = 'on') + cfg.queryrange = number, in atlas voxels (default = 1) + cfg.clim = lower and upper anatomical MRI limits (default = [0 1]) + + When cfg.method='slice', a NxM montage with a large number of slices will be rendered. + All slices are evenly spaced and along the same dimension. + + The following parameters apply for cfg.method='slice' + cfg.nslices = number of slices, (default = 20) + cfg.slicerange = range of slices in data, (default = 'auto') + 'auto', full range of data + [min max], coordinates of first and last slice in voxels + cfg.slicedim = dimension to slice 1 (x-axis) 2(y-axis) 3(z-axis) (default = 3) + cfg.title = string, title of the plot + cfg.figurename = string, title of the figure window + + When cfg.method='surface', the functional data will be rendered onto a cortical mesh + (can be an inflated mesh). If the input source data contains a tri-field (i.e. a + description of a mesh), no interpolation is needed. If the input source data does not + contain a tri-field, an interpolation is performed onto a specified surface. Note that + the coordinate system in which the surface is defined should be the same as the coordinate + system that is represented in the pos-field. + + The following parameters apply to cfg.method='surface' when an interpolation is required + cfg.surffile = string, file that contains the surface (default = 'surface_white_both.mat') + 'surface_white_both.mat' contains a triangulation that corresponds with the + SPM anatomical template in MNI coordinates + cfg.surfinflated = string, file that contains the inflated surface (default = []) + may require specifying a point-matching (uninflated) surffile + cfg.surfdownsample = number (default = 1, i.e. no downsampling) + cfg.projmethod = projection method, how functional volume data is projected onto surface + 'nearest', 'project', 'sphere_avg', 'sphere_weighteddistance' + cfg.projvec = vector (in mm) to allow different projections that + are combined with the method specified in cfg.projcomb + cfg.projcomb = 'mean', 'max', method to combine the different projections + cfg.projweight = vector of weights for the different projections (default = 1) + cfg.projthresh = implements thresholding on the surface level + for example, 0.7 means 70% of maximum + cfg.sphereradius = maximum distance from each voxel to the surface to be + included in the sphere projection methods, expressed in mm + cfg.distmat = precomputed distance matrix (default = []) + + The following parameters apply to cfg.method='surface' irrespective of whether an interpolation is required + cfg.camlight = 'yes' or 'no' (default = 'yes') + cfg.facecolor = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', + or an Nx3 or Nx1 array where N is the number of faces + cfg.vertexcolor = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', + or an Nx3 or Nx1 array where N is the number of vertices + cfg.edgecolor = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r' + + When cfg.method = 'cloud', the functional data will be rendered as as clouds (groups of points), + spheres, or single points at each sensor position. These spheres or point clouds can either be + viewed in 3D or as 2D slices. The 'anatomical' input may also consist of a single or multiple + triangulated surface meshes in an Nx1 cell-array to be plotted with the interpolated functional + data (see FT_PLOT_CLOUD). + + The following parameters apply to cfg.method='cloud' + cfg.cloudtype = 'point' plots a single point at each sensor position + 'cloud' (default) plots each a group of spherically arranged points at each sensor position + 'surf' plots a single spherical surface mesh at each sensor position + cfg.radius = scalar, maximum radius of cloud (default = 4) + cfg.colorgrad = 'white' or a scalar (e.g. 1), degree to which color of points in cloud + changes from its center + cfg.slice = requires 'anatomical' as input (default = 'none') + '2d', plots 2D slices through the cloud with an outline of the mesh + '3d', draws an outline around the mesh at a particular slice + cfg.ori = 'x', 'y', or 'z', specifies the orthogonal plane which will be plotted (default = 'y') + cfg.slicepos = 'auto' or Nx1 vector specifying the position of the + slice plane along the orientation axis (default = 'auto': chooses slice(s) with + the most data) + cfg.nslices = scalar, number of slices to plot if 'slicepos' = 'auto (default = 1) + cfg.minspace = scalar, minimum spacing between slices if nslices>1 (default = 1) + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat file on + disk. This mat files should contain only a single variable corresponding to the + input structure. + + See also FT_SOURCEMOVIE, FT_SOURCEANALYSIS, FT_SOURCEGRANDAVERAGE, FT_SOURCESTATISTICS, + FT_VOLUMELOOKUP, FT_READ_ATLAS, FT_READ_MRI + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourceplot.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourceplot_interactive` + +```{text} + FT_SOURCEPLOT_INTERACTIVE provides a rapid way to plot 3D surface + renderings of pos_time or pos_freq functional data, and interactively + explore them. One figure is created with surface plots of the individual + conditions, and by default a plot of the functional data averaged over + the entire cortex is created over time (or frequency). Users can click in + the line graph to shift the time point for which the functional data is + shown in the surface plots. Additionally, users can Shift+Click in the + surface plots to add a "virtual electrode", for which a new line graph + figure will be created. + + Input data needs to be source+mesh, so has to contain a tri, pos, and one + functional field plus a time- or frequency axis. + + Configuration options (all optional) include: + cfg.parameter = string, functional parameter to plot. Default = 'pow'. + cfg.data_labels = cell array of strings, describing each data input argument. Default = + {'Input 1',...,'Input N'} + cfg.time_label = string, xlabel for line graphs of functional data. Default = 'Time + (s)' for data with time dimension, 'Frequency (Hz)' for data with + freq dimension. + cfg.pow_label = string, ylabel for line graphs of functional data. Default = 'Current + density (a.u.)'. + cfg.clim = string, or 2-element numeric vector specifying the color limits + (see 'has_diff' option below). + cfg.has_diff = 1x1 logical, default = false. If true, this function will treat the + last data input argument slightly differently from the ones before + it, which is useful in case you wish to plot a difference score in + addition to two per-condition current densities. Specifically, if + true, (1) the line plots generated by this function will not include + the last data input argument; and (2) the colours limits for the + surface plot corresponding to the last data input argument will be + set symmetrically around zero (if cfg.clim is left empty - see + above). + cfg.atlas = string, filename of an atlas to use in generating title strings for + the line graphs corresponding to 'virtual electrodes' placed on the + surface plots. Atlas must be in the coordinate system of the + specified data input arguments. See FT_READ_ATLAS. + + Example use: + cfg = []; + cfg.data_labels = {'Congruent', 'Incongruent'}; + ft_sourceplot_interactive(cfg, sourceFC, sourceFIC); + + See also FT_SOURCEPLOT, FT_SOURCEMOVIE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourceplot_interactive.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourcestatistics` + +```{text} + FT_SOURCESTATISTICS computes the probability for a given null-hypothesis using + a parametric statistical test or using a non-parametric randomization test. + + Use as + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + where the input data is the result from FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES + or FT_SOURCEGRANDAVERAGE. The source structures should be spatially alligned + to each other and should have the same positions for the sourcemodel. + + The configuration should contain the following option for data selection + cfg.parameter = string, describing the functional data to be processed, e.g. 'pow', 'nai' or 'coh' + + Furthermore, the configuration should contain: + cfg.method = different methods for calculating the probability of the null-hypothesis, + 'montecarlo' uses a non-parametric randomization test to get a Monte-Carlo estimate of the probability, + 'analytic' uses a parametric test that results in analytic probability, + 'stats' (soon deprecated) uses a parametric test from the MATLAB statistics toolbox, + + The other cfg options depend on the method that you select. You + should read the help of the respective subfunction FT_STATISTICS_XXX + for the corresponding configuration options and for a detailed + explanation of each method. + + See also FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES, FT_SOURCEGRANDAVERAGE, FT_MATH, + FT_STATISTICS_MONTECARLO, FT_STATISTICS_ANALYTIC, FT_STATISTICS_CROSSVALIDATE, FT_STATISTICS_STATS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourcestatistics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_sourcewrite` + +```{text} + FT_SOURCEWRITE exports source-reconstructed results to gifti or nifti format file. + The appropriate output file depends on whether the source locations are described by + on a cortically constrained sheet (gifti) or by a regular 3D lattice (nifti). + + Use as + ft_sourcewrite(cfg, source) + where source is a source structure obtained from FT_SOURCEANALYSIS and + cfg is a structure that should contain + + cfg.filename = string, filename without the extension + cfg.filetype = string, can be 'nifti', 'gifti' or 'cifti' (default is automatic) + cfg.parameter = string, functional parameter to be written to file + cfg.precision = string, can be 'single', 'double', etc. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this the input data will be read from a *.mat + file on disk. This mat file should contain only a single variable, + corresponding with the input data structure. + + See also FT_SOURCEANALYSIS, FT_SOURCEDESCRIPTIVES, FT_VOLUMEWRITE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_sourcewrite.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_specest_hilbert` + +```{text} + FT_SPECEST_HILBERT performs a spectral estimation of data by repeatedly applying a + bandpass filter and then doing a Hilbert transform. + + Use as + [spectrum, freqoi, timeoi] = ft_specest_hilbert(dat, time, ...) + where the input arguments are + dat = matrix of chan*sample + time = vector, containing time in seconds for each sample + and the output arguments are + spectrum = matrix of nchan*nfreq*ntime of fourier coefficients + freqoi = vector of frequencies in spectrum + timeoi = vector of timebins in spectrum + + Optional arguments should be specified in key-value pairs and can include + timeoi = vector, containing time points of interest (in seconds) + freqoi = vector, containing frequencies (in Hz) + pad = number, indicating time-length of data to be padded out to in seconds (split over pre/post; used for spectral interpolation, NOT filtering) + padtype = string, indicating type of padding to be used, can be 'zero', 'mean', 'localmean', 'edge', or 'mirror' (default = 'zero') + width = number or vector, width of band-pass surrounding each element of freqoi + bpfilttype = string, filter type, 'but', 'firws', 'fir', 'firls' + bpfiltord = number or vector, filter order + bpfiltdir = string, filter direction, 'onepass', 'onepass-reverse', 'onepass-zerophase', 'onepass-reverse-zerophase', 'onepass-minphase', 'twopass', 'twopass-reverse', 'twopass-average' + edgeartnan = 0 (default) or 1, replace edge artifacts due to filtering with NaNs (only applicable for bpfilttype = 'fir'/'firls'/'firws') + polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component) + verbose = output progress to console (0 or 1, default 1) + + See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_TFR, FT_SPECEST_MTMCONVOL, FT_SPECEST_WAVELET + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/specest/ft_specest_hilbert.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_specest_irasa` + +```{text} + FT_SPECEST_IRASA separates the fractal components from the orginal power spectrum + using Irregular-Resampling Auto-Spectral Analysis (IRASA) + + Use as + [spectrum, ntaper, freqoi] = ft_specest_irasa(dat, time, ...) + where the input arguments are + dat = matrix of chan*sample + time = vector, containing time in seconds for each sample + and the output arguments are + spectrum = matrix of taper*chan*freqoi of fourier coefficients + ntaper = vector containing number of tapers per element of freqoi + freqoi = vector of frequencies in spectrum + + Optional arguments should be specified in key-value pairs and can include + freqoi = vector, containing frequencies of interest + output = string, indicating type of output ('fractal' or 'original', default 'fractal') + pad = number, total length of data after zero padding (in seconds) + padtype = string, indicating type of padding to be used, can be 'zero', 'mean', 'localmean', 'edge', or 'mirror' (default = 'zero') + polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the Fourier transform (default = 0, which removes the DC-component) + verbose = boolean, output progress to console (0 or 1, default 1) + + This implements: Wen.H. & Liu.Z.(2016), Separating fractal and oscillatory components in the power + spectrum of neurophysiological signal. Brain Topogr. 29(1):13-26. The source code accompanying the + original paper is avaible from https://purr.purdue.edu/publications/1987/1 + + For more information about the difference between the current and previous version and how to use this + function, please see https://www.fieldtriptoolbox.org/example/irasa/ + + See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_MTMCONVOL, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/specest/ft_specest_irasa.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_specest_mtmconvol` + +```{text} + FT_SPECEST_MTMCONVOL performs wavelet convolution in the time domain by + multiplication in the frequency domain. + + Use as + [spectrum, ntaper, freqoi, timeoi] = ft_specest_mtmconvol(dat, time, ...) + where the input arguments are + dat = matrix of chan*sample + time = vector, containing time in seconds for each sample + and the ouitput arguments are + spectrum = matrix of ntaper*chan*freqoi*timeoi of fourier coefficients + ntaper = vector containing the number of tapers per freqoi + freqoi = vector of frequencies in spectrum + timeoi = vector of timebins in spectrum + + Optional arguments should be specified in key-value pairs and can include + freqoi = vector, containing frequencies (in Hz) + timeoi = vector, containing time points of interest (in seconds) + timwin = vector, containing length of time windows (in seconds) + taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') + taperopt = additional taper options to be used in the WINDOW function, see WINDOW + tapsmofrq = number, the amount of spectral smoothing through multi-tapering. Note: 4 Hz smoothing means plus-minus 4 Hz, i.e. a 8 Hz smoothing box + pad = number, indicating time-length of data to be padded out to in seconds + padtype = string, indicating type of padding to be used (see ft_preproc_padding, default: zero) + dimord = 'tap_chan_freq_time' (default) or 'chan_time_freqtap' for memory efficiency + polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component) + verbose = output progress to console (0 or 1, default 1) + + See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/specest/ft_specest_mtmconvol.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_specest_mtmfft` + +```{text} + FT_SPECEST_MTMFFT computes a fast Fourier transform using multitapering with + multiple tapers from the DPSS sequence or using a variety of single tapers. + + Use as + [spectrum, ntaper, freqoi] = ft_specest_mtmfft(dat, time, ...) + where the input arguments are + dat = matrix of chan*sample + time = vector, containing time in seconds for each sample + and the output arguments are + spectrum = matrix of ntaper*nchan*nfreq of fourier coefficients + ntaper = vector containing number of tapers per element of freqoi + freqoi = vector of frequencies in spectrum + + Optional arguments should be specified in key-value pairs and can include + freqoi = vector, containing frequencies of interest + taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') + taperopt = additional taper options to be used in the WINDOW function, see WINDOW + tapsmofrq = the amount of spectral smoothing through multi-tapering. Note: 4 Hz smoothing means plus-minus 4 Hz, i.e. a 8 Hz smoothing box + pad = number, total length of data after zero padding (in seconds) + padtype = string, indicating type of padding to be used, can be 'zero', 'mean', 'localmean', 'edge', or 'mirror' (default = 'zero') + dimord = 'tap_chan_freq' (default) or 'chan_time_freqtap' for memory efficiency (only when using variable number of slepian tapers) + polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component) + verbose = output progress to console (0 or 1, default 1) + + See also FT_FREQANALYSIS, FT_SPECEST_MTMCONVOL, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/specest/ft_specest_mtmfft.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_specest_neuvar` + +```{text} + FT_SPECEST_NEUVAR computes a time-domain estimation of overall signal power, having + compensated for the 1/f distribution of spectral content. + + Use as + [spectrum, freqoi] = ft_specest_neuvar(dat, time...) + where the input arguments are + dat = matrix of chan*sample + time = vector, containing time in seconds for each sample + and the output arguments are + spectrum = matrix of chan*neuvar + freqoi = vector of frequencies in spectrum + + Optional arguments should be specified in key-value pairs and can include + order = number, the order of differentation for compensating for the 1/f (default = 1) + pad = number, total length of data after zero padding (in seconds) + padtype = string, indicating type of padding to be used, can be 'zero', 'mean', 'localmean', 'edge', or 'mirror' (default = 'zero') + polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the Fourier transform (default = 0, which removes the DC-component) + verbose = output progress to console (0 or 1, default 1) + + See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_MTMCONVOL, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/specest/ft_specest_neuvar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_specest_tfr` + +```{text} + FT_SPECEST_TFR performs time-frequency analysis on any time series trial data using + the 'wavelet method' based on Morlet wavelets, doing convolution in the time + domain. + + Use as + [spectrum, freqoi, timeoi] = ft_specest_convol(dat, time, ...) + where the input arguments are + dat = matrix of nchan*nsample + time = vector, containing time in seconds for each sample + and the output arguments are + spectrum = array of nchan*nfreq*ntime of fourier coefficients + freqoi = vector of frequencies in spectrum + timeoi = vector of timebins in spectrum + + Optional arguments should be specified in key-value pairs and can include + timeoi = vector, containing time points of interest (in seconds, analysis window will be centered around these time points) + freqoi = vector, containing frequencies (in Hz) + width = number or vector, width of the wavelet, determines the temporal and spectral resolution (default = 7) + gwidth = number, determines the length of the used wavelets in standard deviations of the implicit Gaussian kernel + polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component) + verbose = output progress to console (0 or 1, default 1) + + See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_MTMCONVOL, FT_SPECEST_HILBERT, FT_SPECEST_NANFFT, FT_SPECEST_WAVELET + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/specest/ft_specest_tfr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_specest_wavelet` + +```{text} + FT_SPECEST_WAVELET performs time-frequency analysis on any time series trial data + using the 'wavelet method' based on Morlet wavelets, doing convolution in the time + domain by multiplication in the frequency domain. + + Use as + [spectrum, freqoi, timeoi] = ft_specest_wavelet(dat, time, ...) + where the input arguments are + dat = matrix of chan*sample + time = vector, containing time in seconds for each sample + and the output arguments are + spectrum = array of chan*freqoi*timeoi of fourier coefficients + freqoi = vector of frequencies in spectrum + timeoi = vector of timebins in spectrum + + Optional arguments should be specified in key-value pairs and can include + timeoi = vector, containing time points of interest (in seconds) + freqoi = vector, containing frequencies of interest + width = number or vector, width of the wavelet, determines the temporal and spectral resolution + gwidth = number, determines the length of the used wavelets in standard deviations of the implicit Gaussian kernel + pad = number, total length of data after zero padding (in seconds) + padtype = string, indicating type of padding to be used, can be 'zero', 'mean', 'localmean', 'edge', or 'mirror' (default = 'zero') + polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component) + verbose = output progress to console (0 or 1, default 1) + + See also FT_FREQANALYSIS, FT_SPECEST_MTMCONVOL, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_MTMFFT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/specest/ft_specest_wavelet.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_standalone` + +```{text} + FT_STANDALONE is the entry function of the compiled FieldTrip application. + The compiled application can be used to execute FieldTrip data analysis + scripts. + + This function can be started on the interactive MATLAB command line as + ft_standalone script.m + ft_standalone script1.m script2.m ... + ft_standalone jobfile.mat + or after compilation on the Linux/macOS command line as + fieldtrip.sh script.m + fieldtrip.sh script1.m script2.m ... + fieldtrip.sh jobfile.mat + + It is possible to pass additional options on the MATLAB command line like + this on the MATLAB command line + ft_standalone --option value scriptname.m + or on the Linux/macOS command line + fieldtrip.sh --option value scriptname.m + The options and their values are automatically made available as local + variables in the script execution environment. + + See also FT_COMPILE_STANDALONE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_standalone.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_actvsblT` + +```{text} + FT_STATFUN_ACTVSBLT calculates the activation-versus-baseline T-statistic on the + biological data (the dependent variable), using the information on the independent + variable (ivar) in design. + + Note that it does not make sense to use this test statistic when baseline + correction was performed by subtracting the mean of the baseline period from the + whole data (for ERP data) or by dividing by the mean (for TFR data). If baseline + correction is desired, you should subtract the full baseline and activation period. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_actvsblT' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + cfg.uvar = unit variable, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2) + + The first condition, indicated by 1, corresponds to the activation period and the second, + indicated by 2, corresponds to the baseline period. The labels for the unit of observation + should be integers ranging from 1 to the number of observations (subjects or trials). + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_actvsblT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_bayesfactor` + +```{text} + FT_STATFUN_BAYESFACTOR computes the Bayes factor for a H0 of the data in two + conditions having the same mean, versus H1 of the data having different means. This + function supports both unpaired and paired designs and assumes flat priors. + + Lee and Wagenmakers (2013) provide these guidelines for its interpretation + IF B10 IS... THEN YOU HAVE... + > 100 Extreme evidence for H1 + 30 – 100 Very strong evidence for H1 + 10 – 30 Strong evidence for H1 + 3 – 10 Moderate evidence for H1 + 1 – 3 Anecdotal evidence for H1 + 1 No evidence + 1/3 – 1 Anecdotal evidence for H0 + 1/3 – 1/10 Moderate evidence for H0 + 1/10 – 1/30 Strong evidence for H0 + 1/30 – 1/100 Very strong evidence for H0 + < 1/100 Extreme evidence for H0 + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_bayesfactor' + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + cfg.uvar = optional, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2) + + The labels for the independent variable should be specified as the number 1 and 2. + The labels for the unit of observation should be integers ranging from 1 to the + total number of observations (subjects or trials). + + The cfg.uvar option is only needed for paired data, you should leave it empty + for non-paired data. + + See https://www.statisticshowto.datasciencecentral.com/bayes-factor-definition/ for some background. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_bayesfactor.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_cohensd` + +```{text} + FT_STATFUN_COHENSD computes the effect size according to Cohen's d. This function + supports both unpaired and paired designs. + + The table below contains descriptors for magnitudes of Cohen's d. + Very small 0.01 + Small 0.20 + Medium 0.50 + Large 0.80 + Very large 1.20 + Huge 2.00 + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_cohensd' + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + cfg.uvar = optional, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2) + + The labels for the independent variable should be specified as the number 1 and 2. + The labels for the unit of observation should be integers ranging from 1 to the + total number of observations (subjects or trials). + + The cfg.uvar option is only needed for paired data, you should leave it empty + for non-paired data. + + See https://en.wikipedia.org/wiki/Effect_size#Cohen.27s_d for a description + and https://www.psychometrica.de/effect_size.html for an online computation tool. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_cohensd.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_correlationT` + +```{text} + FT_STATFUN_CORRELATIONT calculates correlation coefficient T-statistics on the + biological data in dat (the dependent variable), using the information on the + independent variable (predictor) in design. The correlation coefficients themselves + are stored in the output structure as rho. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_correlationT' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + cfg.type = 'Pearson' to compute Pearson's correlation (default), + see 'help corr' for other options. + + The experimental design is specified as: + cfg.ivar = row number of the design that contains the independent variable, i.e. the predictor (default=1) + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_correlationT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_depsamplesFmultivariate` + +```{text} + FT_STATFUN_DEPSAMPLESFMULTIVARIATE calculates the MANOVA dependent samples + F-statistic on the biological data in dat (the dependent variable), using the + information on the independent variable (ivar) in design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_depsamplesFmultivariate' + + You can specify the following configuration options: + cfg.contrastcoefs = matrix of contrast coefficients determining the + effect being tested. The number of columns of this + matrix has to be equal to the number of conditions. + The default is a matrix that specifies the + main effect of the independent variable. This matrix + has size [(ncond-1),ncond]. + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + cfg.uvar = unit variable, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2) + + The labels for the independent variable should be specified as numbers ranging + from 1 to the number of conditions. The labels for the unit of observation should + be integers ranging from 1 to the total number of observations (subjects or trials). + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_depsamplesFmultivariate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_depsamplesFunivariate` + +```{text} + FT_STATFUN_DEPSAMPLESFUNIIVARIATE calculates the univariate repeated-mesures ANOVA + on the biological data (the dependent variable), using the information on the + independent variable (ivar) in design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_depsamplesFunivariate' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1). For the + Fstatistic only cfg.tail = 1 makes sense. + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + cfg.uvar = unit variable, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2) + + The labels for the independent variable should be specified as numbers ranging + from 1 to the number of conditions. The labels for the unit of observation should + be integers ranging from 1 to the total number of observations (subjects or trials). + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_depsamplesFunivariate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_depsamplesT` + +```{text} + FT_STATFUN_DEPSAMPLEST calculates the dependent samples t-statistic on the + biological data (the dependent variable), using the information on the independent + variable (ivar) in the design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_depsamplesT' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + cfg.uvar = unit variable, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2) + + The labels for the independent variable should be specified as the number 1 and 2. + The labels for the unit of observation should be integers ranging from 1 to the + total number of observations (subjects or trials). + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_depsamplesT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_depsamplesregrT` + +```{text} + FT_STATFUN_DEPSAMPLESREGRT calculates independent samples regression coefficient + t-statistics on the biological data (the dependent variable), using the information + on the independent variable (predictor) in the design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_depsamplesregrT' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + + The experimental design is specified as: + cfg.ivar = row number of the design that contains the independent variable, i.e. the predictor (default=1) + cfg.uvar = unit variable, row number of design that contains the labels of the units-of-observation, i.e. subjects or trials (default=2) + + The labels for the unit of observation should be integers ranging from 1 to the + total number of observations (subjects or trials). + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_depsamplesregrT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_diff` + +```{text} + FT_STATFUN_DIFF demonstrates how to compute the difference of the mean in two + conditions. Although it can be used for statistical testing, it will have rather + limited sensitivity and is not really suited for inferential testing. + + This function serves as an example for a statfun. You can use such a function with + the statistical framework in FieldTrip using FT_TIMELOCKSTATISTICS, + FT_FREQSTATISTICS or FT_SOURCESTATISTICS to perform a statistical test, without + having to worry about the representation of the data. + + Use this function by calling the high-level statistic functions as + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_diff_itc' + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + + The labels for the independent variable should be specified as the number 1 and 2. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS, and see FT_STATFUN_MEAN for a similar example + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_diff.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_diff_itc` + +```{text} + FT_STATFUN_DIFF_ITC computes the difference in the inter-trial coherence between + two conditions. The input data for this test should consist of complex-values + spectral estimates, e.g. computed using FT_FREQANALYSIS with cfg.method='mtmfft', + 'wavelet' or 'mtmconvcol'. + + The ITC is a measure of phase consistency over trials. By randomlly shuffling the + trials between the two consitions and repeatedly computing the ITC difference, you + can test the significance of the two conditions having a different ITC. + + A difference in the number of trials poer condition will affect the ITC, however + since the number of trials remains the same for each random permutation, this bias + is reflected in the randomization distribution. + + Use this function by calling the high-level statistic functions as + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_diff_itc' + + For this specific statistic there is no known parametric distribution, hence the + probability and critical value cannot be computed analytically. This specific + statistic can therefore only be used with cfg.method='montecarlo'. If you want to + do this in combination with cfg.correctm='cluster', you also need to specify + cfg.clusterthreshold='nonparametric_common' or 'nonparametric_individual'. + + You can specify the following configuration options: + cfg.complex = string, 'diffabs' (default) to compute the difference of the absolute ITC values, + or 'absdiff' to compute the absolute value of the difference in the complex ITC values. + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + + The labels for the independent variable should be specified as the number 1 and 2. + + See also FT_FREQSTATISTICS and FT_STATISTICS_MONTECARLO + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_diff_itc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_gcmi` + +```{text} + FT_STATFUN_GCMI computes mutual information between the dependent variable + and a discrete-valued design vector. + + You can specify the following configuration options: + cfg.preconditionflag = 0 (default), or 1, performs Gaussian copula transform + Preconditioning is computationally efficient, because for given data it needs to be done only once. + cfg.gcmi.method = ['cc', 'cd_model' 'cd_mixture'], type of calculation + cfg.gcmi.complex = ['abs' 'real' 'imag' 'complex' 'angle' ], how to treat complex data + cfg.gcmi.tra = matrix which specifies multivariate structure + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_gcmi.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_indepsamplesF` + +```{text} + FT_STATFUN_INDEPSAMPLESF calculates the independent samples F-statistic on the + biological data in dat (the dependent variable), using the information on the + independent variable (ivar) in design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_indepsamplesF' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default= 'yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + + The labels for the independent variable should be specified as numbers ranging + from 1 to the number of conditions. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_indepsamplesF.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_indepsamplesT` + +```{text} + FT_STATFUN_INDEPSAMPLEST calculates the independent samples T-statistic on the + biological data in dat (the dependent variable), using the information on the + independent variable (ivar) in design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option: + cfg.statistic = 'ft_statfun_indepsamplesT' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1). + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + + The labels for the independent variable should be specified as the number 1 and 2. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_indepsamplesT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_indepsamplesZcoh` + +```{text} + FT_STATFUN_INDEPSAMPLESCOHZ calculates the independent samples coherence + Z-statistic on the biological data in dat (the dependent variable), using the + information on the independent variable (ivar) in design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option + cfg.statistic = 'ft_statfun_indepsamplesZcoh' + + The samples-dimension of the dat-variable must be the result of a reshaping + operation applied to a data structure with dimord chan_(freq_time) or + pos_(freq_time). The configuration must contain channel labels in cfg.label or + position information in cfg.pos. This information is used to determine the number + of channels. The dimord of the output fields is [prod(nchancmb,nfreq,ntime),1]. The + channel combinations are the elements of the lower diagonal of the cross-spectral + density matrix. + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default='yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default='no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default='no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + + The labels for the independent variable should be specified as the number 1 and 2. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_indepsamplesZcoh.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_indepsamplesregrT` + +```{text} + FT_STATFUN_INDEPSAMPLESREGRT calculates independent samples regression coefficient + t-statistics on the biological data (the dependent variable), using the information + on the independent variable (predictor) in the design. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option + cfg.statistic = 'ft_statfun_indepsamplesregrT' + + You can specify the following configuration options: + cfg.computestat = 'yes' or 'no', calculate the statistic (default = 'yes') + cfg.computecritval = 'yes' or 'no', calculate the critical values of the test statistics (default = 'no') + cfg.computeprob = 'yes' or 'no', calculate the p-values (default = 'no') + + The following options are relevant if cfg.computecritval='yes' and/or cfg.computeprob='yes': + cfg.alpha = critical alpha-level of the statistical test (default=0.05) + cfg.tail = -1, 0, or 1, left, two-sided, or right (default=1) + cfg.tail in combination with cfg.computecritval='yes' + determines whether the critical value is computed at + quantile cfg.alpha (with cfg.tail=-1), at quantiles + cfg.alpha/2 and (1-cfg.alpha/2) (with cfg.tail=0), or at + quantile (1-cfg.alpha) (with cfg.tail=1) + + The experimental design is specified as: + cfg.ivar = row number of the design that contains the independent variable, i.e. the predictor (default=1) + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_indepsamplesregrT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_mean` + +```{text} + FT_STATFUN_MEAN demonstrates how to compute the mean over all conditions in the + data. Since this does NOT depend on the experimental design, it cannot be used for + testing for differences between conditions. + + This function serves as an example for a statfun. You can use such a function with + the statistical framework in FieldTrip using FT_TIMELOCKSTATISTICS, + FT_FREQSTATISTICS or FT_SOURCESTATISTICS to perform a statistical test, without + having to worry about the representation of the data. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS, and see FT_STATFUN_DIFF for a similar example + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_mean.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_pooledT` + +```{text} + FT_STATFUN_POOLEDT computes the pooled t-value over a number of replications. The + idea behind this function is that you first (prior to calling this function) + compute a contrast between two conditions per subject, and that subsequently you + test this over subjects using random sign-flipping. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option + cfg.statistic = 'ft_statfun_pooledT' + + The expected values for the pooled-t, which is zero according to H0, have to be + passed as pseudo-values. The subject-specific t-values will be randomly swapped with + the pseudo-values and the difference is computed; in effect this implements random + sign-flipping. + + The randimization distribution (with optional clustering) of the randomly + sign-flipped pooled-t values is computed and used for statistical inference. + + Note that, although the output of this function is to be interpreted as a + fixed-effects statistic, the statistical inference based on the comparison of the + observed pooled t-values with the randomization distribution is not a fixed-effect + statistic, one or a few outlier will cause the randomization distribution to + broaden and result in the conclusion of "not significant". + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be sign-flipped (default=1) + + The labels independent variable should be specified as the number 1 for the + observed t-values and 2 for the pseudo-values. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_pooledT.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statfun_roc` + +```{text} + FT_STATFUN_ROC computes the area under the curve (AUC) of the Receiver Operator + Characteristic (ROC). This is a measure of the separability of the data observed in + two conditions. The AUC can be used for statistical testing whether the two + conditions can be distinguished on the basis of the data. + + Use this function by calling one of the high-level statistics functions as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) + [stat] = ft_sourcestatistics(cfg, source1, source2, ...) + with the following configuration option + cfg.statistic = 'ft_statfun_roc' + + The experimental design is specified as: + cfg.ivar = independent variable, row number of the design that contains the labels of the conditions to be compared (default=1) + + The labels for the independent variable should be specified as the number 1 and 2. + + Note that this statfun performs a one sided test in which condition "1" is assumed + to be larger than condition "2". This function does not compute an analytic + probability of condition "1" being larger than condition "2", but can be used in a + randomization test, including clustering. + + A low-level example with 10 channel-time-frequency points and 1000 observations per + condition goes like this: + dat1 = randn(10,1000) + 1; + dat2 = randn(10,1000); + design = [1*ones(1,1000) 2*ones(1,1000)]; + stat = ft_statfun_roc([], [dat1 dat2], design); + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS or FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/statfun/ft_statfun_roc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statistics_analytic` + +```{text} + FT_STATISTICS_ANALYTIC performs a parametric statistical test on the data, based on + a known (i.e. analytic) distribution of the test statistic. This function should + not be called directly, instead you should call the function that is associated + with the type of data on which you want to perform the test. + + Use as + stat = ft_timelockstatistics(cfg, data1, data2, data3, ...) + stat = ft_freqstatistics (cfg, data1, data2, data3, ...) + stat = ft_sourcestatistics (cfg, data1, data2, data3, ...) + + where the data is obtained from FT_TIMELOCKANALYSIS, FT_FREQANALYSIS or + FT_SOURCEANALYSIS respectively, or from FT_TIMELOCKGRANDAVERAGE, + FT_FREQGRANDAVERAGE or FT_SOURCEGRANDAVERAGE respectively + and with cfg.method = 'analytic' + + The configuration options that can be specified are: + cfg.statistic = string, statistic to compute for each sample or voxel (see below) + cfg.correctm = string, apply multiple-comparison correction, 'no', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no') + cfg.alpha = number, critical value for rejecting the null-hypothesis (default = 0.05) + cfg.tail = number, -1, 1 or 0 (default = 0) + cfg.ivar = number or list with indices, independent variable(s) + cfg.uvar = number or list with indices, unit variable(s) + cfg.wvar = number or list with indices, within-block variable(s) + + The parametric statistic that is computed for each sample (and for + which the analytic probability of the null-hypothesis is computed) is + specified as + cfg.statistic = 'indepsamplesT' independent samples T-statistic, + 'indepsamplesF' independent samples F-statistic, + 'indepsamplesregrT' independent samples regression coefficient T-statistic, + 'indepsamplesZcoh' independent samples Z-statistic for coherence, + 'depsamplesT' dependent samples T-statistic, + 'depsamplesFmultivariate' dependent samples F-statistic MANOVA, + 'depsamplesregrT' dependent samples regression coefficient T-statistic, + 'actvsblT' activation versus baseline T-statistic. + or you can specify your own low-level statistical function. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS + FT_STATISTICS_MONTECARLO, FT_STATISTICS_STATS, FT_STATISTICS_MVPA, + FT_STATISTICS_CROSSVALIDATE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_statistics_analytic.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statistics_crossvalidate` + +```{text} + FT_STATISTICS_CROSSVALIDATE performs cross-validation using a prespecified + multivariate analysis. This function should not be called directly, instead you + should call the function that is associated with the type of data on which you want + to perform the test. + + Use as + stat = ft_timelockstatistics(cfg, data1, data2, data3, ...) + stat = ft_freqstatistics (cfg, data1, data2, data3, ...) + stat = ft_sourcestatistics (cfg, data1, data2, data3, ...) + + where the data is obtained from FT_TIMELOCKANALYSIS, FT_FREQANALYSIS or + FT_SOURCEANALYSIS respectively, or from FT_TIMELOCKGRANDAVERAGE, + FT_FREQGRANDAVERAGE or FT_SOURCEGRANDAVERAGE respectively + and with cfg.method = 'crossvalidate' + + The configuration options that can be specified are: + cfg.mva = a multivariate analysis (default = {dml.standardizer dml.svm}) + cfg.statistic = a cell-array of statistics to report (default = {'accuracy' 'binomial'}) + cfg.nfolds = number of cross-validation folds (default = 5) + cfg.resample = true/false; upsample less occurring classes during + training and downsample often occurring classes + during testing (default = false) + + This returns: + stat.statistic = the statistics to report + stat.model = the models associated with this multivariate analysis + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS + FT_STATISTICS_ANALYTIC, FT_STATISTICS_MONTECARLO, FT_STATISTICS_MVPA, + FT_STATISTICS_CROSSVALIDATE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_statistics_crossvalidate.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statistics_montecarlo` + +```{text} + FT_STATISTICS_MONTECARLO performs a nonparametric statistical test by calculating + Monte-Carlo estimates of the significance probabilities and/or critical values from + the permutation distribution. This function should not be called directly, instead + you should call the function that is associated with the type of data on which you + want to perform the test. + + Use as + stat = ft_timelockstatistics(cfg, data1, data2, data3, ...) + stat = ft_freqstatistics (cfg, data1, data2, data3, ...) + stat = ft_sourcestatistics (cfg, data1, data2, data3, ...) + + where the data is obtained from FT_TIMELOCKANALYSIS, FT_FREQANALYSIS or + FT_SOURCEANALYSIS respectively, or from FT_TIMELOCKGRANDAVERAGE, + FT_FREQGRANDAVERAGE or FT_SOURCEGRANDAVERAGE respectively + and with cfg.method = 'montecarlo' + + The configuration options that can be specified are: + cfg.numrandomization = number of randomizations, can be 'all' + cfg.correctm = string, apply multiple-comparison correction, 'no', 'max', cluster', 'tfce', 'bonferroni', 'holm', 'hochberg', 'fdr' (default = 'no') + cfg.alpha = number, critical value for rejecting the null-hypothesis per tail (default = 0.05) + cfg.tail = number, -1, 1 or 0 (default = 0) + cfg.correcttail = string, correct p-values or alpha-values when doing a two-sided test, 'alpha','prob' or 'no' (default = 'no') + cfg.ivar = number or list with indices, independent variable(s) + cfg.uvar = number or list with indices, unit variable(s) + cfg.wvar = number or list with indices, within-cell variable(s) + cfg.cvar = number or list with indices, control variable(s) + cfg.feedback = string, 'gui', 'text', 'textbar' or 'no' (default = 'text') + cfg.randomseed = string, 'yes', 'no' or a number (default = 'yes') + + If you use a cluster-based statistic, you can specify the following options that + determine how the single-sample or single-voxel statistics will be thresholded and + combined into one statistical value per cluster. + cfg.clusterstatistic = how to combine the single samples that belong to a cluster, 'maxsum', 'maxsize', 'wcm' (default = 'maxsum') + the option 'wcm' refers to 'weighted cluster mass', a statistic that combines cluster size and intensity; + see Hayasaka & Nichols (2004) NeuroImage for details + cfg.clusterthreshold = method for single-sample threshold, 'parametric', 'nonparametric_individual', 'nonparametric_common' (default = 'parametric') + cfg.clusteralpha = for either parametric or nonparametric thresholding per tail (default = 0.05) + cfg.clustercritval = for parametric thresholding (default is determined by the statfun) + cfg.clustertail = -1, 1 or 0 (default = 0) + + To include the channel dimension for clustering of channel level data, you should specify + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS + If you specify an empty neighbourhood structure, clustering will only be done + over frequency and/or time and not over neighbouring channels. + + The statistic that is computed for each sample in each random reshuffling + of the data is specified as + cfg.statistic = 'indepsamplesT' independent samples T-statistic, + 'indepsamplesF' independent samples F-statistic, + 'indepsamplesregrT' independent samples regression coefficient T-statistic, + 'indepsamplesZcoh' independent samples Z-statistic for coherence, + 'depsamplesT' dependent samples T-statistic, + 'depsamplesFmultivariate' dependent samples F-statistic MANOVA, + 'depsamplesregrT' dependent samples regression coefficient T-statistic, + 'actvsblT' activation versus baseline T-statistic. + or you can specify your own low-level statistical function. + + You can also use a custom statistic of your choice that is sensitive to the + expected effect in the data. You can implement the statistic in a "statfun" that + will be called for each randomization. The requirements on a custom statistical + function is that the function is called ft_statfun_xxx, and that the function returns + a structure with a "stat" field containing the single sample statistical values. + Have a look at the functions in the fieldtrip/statfun directory (e.g. + FT_STATFUN_INDEPSAMPLEST) for the correct format of the input and output. + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS, + FT_STATISTICS_ANALYTIC, FT_STATISTICS_STATS, FT_STATISTICS_MVPA, + FT_STATISTICS_CROSSVALIDATE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_statistics_montecarlo.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statistics_mvpa` + +```{text} + FT_STATISTICS_MVPA performs multivariate pattern classification or regression using + the MVPA-Light toolbox. The function supports cross-validation, searchlight + analysis, generalization, nested preprocessing, a variety of classification and + regression metrics, as well as statistical testing of these metrics. This function + should not be called directly, instead you should call the function that is + associated with the type of data on which you want to perform the test. + + Use as + stat = ft_timelockstatistics(cfg, data1, data2, data3, ...) + stat = ft_freqstatistics (cfg, data1, data2, data3, ...) + stat = ft_sourcestatistics (cfg, data1, data2, data3, ...) + + where the data is obtained from FT_TIMELOCKANALYSIS, FT_FREQANALYSIS or + FT_SOURCEANALYSIS respectively, or from FT_TIMELOCKGRANDAVERAGE, + FT_FREQGRANDAVERAGE or FT_SOURCEGRANDAVERAGE respectively + and with cfg.method = 'mvpa' + + The configuration options that can be specified are: + cfg.features = specifies the name or index of the dimension(s) + that serve(s) as features for the classifier or + regression model. Dimensions that are not + samples or features act as search + dimensions. For instance, assume the data is a + 3D array of size [samples x channels x time]. + If mvpa.features = 2, the channels serve as + features. A classification is then performed for + each time point (we call time a searchlight + dimension). Conversely, if mvpa.features = 3, the + time points serve as features. A classification + is performed for each channel (channel is a + searchlight dimension). + If cfg.features = [], then all non-sample + dimensions serve as searchlight dimensions. + If the dimensions have names (i.e. cfg.dimord + exists), then instead of numbers the feature can + be specified as a string (e.g. 'chan'). + Default value is chosen based on the (optional) + specification of the other searchlight options (see + below). If nothing is defined, the default will be 'chan'/2. + cfg.generalize = specifies the name or index of the dimensions + that serves for generalization (if any). For + instance, if the data is [samples x channels x + time], and mvpa.generalize = 3, a time x time + generalization is performed. If mvpa.generalize = + 2, a electrode x electrode generalization is + performed. mvpa.generalize must refer to a + searchlight dimension, therefore its value must + be different from the value of mvpa.features. + (default []) + + The configuration contains a substruct cfg.mvpa that contains detailed + options for the MVPA. Possible fields + cfg.mvpa.classifier = string specifying the classifier + Available classifiers: + 'ensemble' Ensemble of classifiers. Any of the other + classifiers can be used as a learner. + 'kernel_fda' Kernel Fisher Discriminant Analysis + 'lda' Regularized linear discriminant analysis + (LDA) (for two classes) + 'logreg' Logistic regression + 'multiclass_lda' LDA for more than two classes + 'naive_bayes' Naive Bayes + 'svm' Support Vector Machine (SVM) + More details on the classifiers: https://github.com/treder/MVPA-Light#classifiers-for-two-classes- + Additionally, you can choose 'libsvm' or + 'liblinear' as a model. They provide interfaces + for logistic regression, SVM, and Support Vector + Regression. Note that they can act as either + classifiers or regression models. An installation + of LIBSVM or LIBLINEAR is required. + cfg.mvpa.model = string specifying the regression model. If a + regression model has been specified, + cfg.mvpa.classifier should be empty (and vice + versa). If neither a classifier nor regression + model is specified, a LDA classifier is used by + default. + + Available regression models: + 'ridge Ridge regression + 'kernel_ridge' Kernel Ridge regression + More details on the regression models: https://github.com/treder/MVPA-Light#regression-models- + cfg.mvpa.metric = string, classification or regression metric, or + cell array with multiple metrics. + Classification metrics: accuracy auc confusion + dval f1 kappa precision recall tval + Regression metrics: mae mse r_squared + + cfg.mvpa.hyperparameter = struct, structure with hyperparameters for the + classifier or regression model (see HYPERPARAMETERS below) + cfg.mvpa.feedback = 'yes' or 'no', whether or not to print feedback on the console (default 'yes') + + To obtain a realistic estimate of classification performance, cross-validation + is used. It is controlled by the following parameters: + cfg.mvpa.cv = string, cross-validation type, either 'kfold', 'leaveout' + 'holdout', or 'predefined'. If 'none', no cross-validation is + used and the model is tested on the training + set. (default 'kfold') + cfg.mvpa.k = number of folds in k-fold cross-validation (default 5) + cfg.mvpa.repeat = number of times the cross-validation is repeated + with new randomly assigned folds (default 5) + cfg.mvpa.p = if cfg.cv is 'holdout', p is the fraction of test + samples (default 0.1) + cfg.mvpa.stratify = if 1, the class proportions are approximately + preserved in each test fold (default 1) + cfg.mvpa.fold = if cv='predefined', fold is a vector of length + #samples that specifies the fold each sample belongs to + + More information about each classifier is found in the documentation of + MVPA-Light (github.com/treder/MVPA-Light/). + + HYPERPARAMETERS: + Each classifier comes with its own set of hyperparameters, such as + regularization parameters and the kernel. Hyperparameters can be set + using the cfg.mvpa.hyperparameter substruct. For instance, in LDA, + cfg.mvpa.hyperparameter = 'auto' sets the lambda regularization parameter. + + The specification of the hyperparameters is found in the training function + for each model at github.com/treder/MVPA-Light/tree/master/model + If a hyperparameter is not specified, default values are used. + + SEARCHLIGHT ANALYSIS: + Data dimensions that are not samples or features serve as 'search + dimensions'. For instance, if the data is [samples x chan x time] + and mvpa.features = 'time', then the channel dimension serves as search + dimension: a separate analysis is carried out for each channel. Instead + of considering each channel individually, a searchlight can be defined + such that each channel is used together with its neighbours. Neighbours + can be specified using the cfg.neighbours field: + + cfg.neighbours = neighbourhood structure, see FT_PREPARE_NEIGHBOURS + cfg.timwin = integer, if MVPA is performed for each time point, + timwin specfies the total size of the time window + that is considered as features. + Example: for cfg.timwin = 3 a given time point is considered + together with the immediately preceding and following + time points. Increasing timwin typially + leads to smoother results along the time axis. + cfg.freqwin = integer, acts like cfg.timwin but across frequencies + + This returns: + stat.metric = this contains the requested metric + + See also FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS, FT_SOURCESTATISTICS, + FT_STATISTICS_ANALYTIC, FT_STATISTICS_STATS, FT_STATISTICS_MONTECARLO, FT_STATISTICS_CROSSVALIDATE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_statistics_mvpa.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_statistics_stats` + +```{text} + FT_STATISTICS_STATS performs a massive univariate statistical test using the MATLAB + statistics toolbox. This function should not be called directly, instead you should + call the function that is associated with the type of data on which you want to + perform the test. + + Use as + stat = ft_timelockstatistics(cfg, data1, data2, data3, ...) + stat = ft_freqstatistics (cfg, data1, data2, data3, ...) + stat = ft_sourcestatistics (cfg, data1, data2, data3, ...) + + where the data is obtained from FT_TIMELOCKANALYSIS, FT_FREQANALYSIS or + FT_SOURCEANALYSIS respectively, or from FT_TIMELOCKGRANDAVERAGE, + FT_FREQGRANDAVERAGE or FT_SOURCEGRANDAVERAGE respectively + and with cfg.method = 'stats' + + The configuration options that can be specified are: + cfg.alpha = number, critical value for rejecting the null-hypothesis (default = 0.05) + cfg.tail = number, -1, 1 or 0 (default = 0) + cfg.feedback = string, 'gui', 'text', 'textbar' or 'no' (default = 'textbar') + cfg.method = 'stats' + cfg.statistic = 'ttest' test against a mean of zero + 'ttest2' compare the mean in two conditions + 'paired-ttest' + 'anova1' + 'kruskalwallis' + 'signtest' + 'signrank' + 'pearson' + 'kendall' + 'spearman' + + See also TTEST, TTEST2, KRUSKALWALLIS, SIGNTEST, SIGNRANK, FT_TIMELOCKSTATISTICS, + FT_FREQSTATISTICS, FT_SOURCESTATISTICS FT_STATISTICS_ANALYTIC, FT_STATISTICS_STATS, + FT_STATISTICS_MONTECARLO, FT_STATISTICS_CROSSVALIDATE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_statistics_stats.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_steadystatesimulation` + +```{text} + FT_STEADYSTATESIMULATION creates a simulated EEG/MEG dataset. This function + allows to simulate the effect of several independent stimulus trains. These can + be presented as a periodic sequence, or as single (or few) transient stimuli. + This function creates a single block of data. You can call it repeatedly and use + FT_APPENDDATA to combine different blocks. + + Use as + data = ft_steadystatesimulation(cfg) + where cfg is a configuration structure that should contain + cfg.fsample = scalar, sampling frequency in Hz (default = 512) + cfg.duration = scalar, trial length in seconds (default = 4.56) + cfg.baseline = scalar, baseline length in seconds (default = 0) + cfg.ntrials = integer N, number of trials (default = 320) + cfg.iti = scalar, inter-trial interval in seconds (default = 1) + cfg.randomseed = 'yes' or a number or vector with the seed value (default = 'yes') + + Each trial can contain multiple nested experimental manipulations + cfg.level1.condition = scalar, or vector of length L1 (default = 1) + cfg.level1.gain = scalar, or vector of length L1 (default = 1) + cfg.level2.condition = scalar, or vector of length L2 (default = 1) + cfg.level2.gain = scalar, or vector of length L2 (default = 1) + cfg.level3.condition = scalar, or vector of length L3 (default = 1) + cfg.level3.gain = scalar, or vector of length L3 (default = 1) + If you don't need level 2 and up, specify the condition and gain as empty. + Idem for level 3 and up. + + Stimuli are created at the lowest experimental level, and are modulated according to the product of the gain of all levels. + Each trial can contain one or multiple stimuli. + The behavior of each stimuli is specified with + cfg.stimulus1.mode = 'periodic', 'transient' or 'off' (default = 'periodic') + cfg.stimulus2.mode = 'periodic', 'transient' or 'off' (default = 'transient') + + If the stimulus is periodic (below as example for stimulus1), the following options apply + cfg.stimulus1.number = does not apply for periodic stimuli + cfg.stimulus1.onset = in seconds, first stimulus relative to the start of the trial (default = 0) + cfg.stimulus1.onsetjitter = in seconds, max jitter that is added to the onset (default = 0) + cfg.stimulus1.isi = in seconds, i.e. for 10Hz you would specify 0.1 seconds as the interstimulus interval (default = 0.1176) + cfg.stimulus1.isijitter = in seconds, max jitter relative to the previous stimulus (default = 0) + cfg.stimulus2.condition = does not apply for periodic stimuli + cfg.stimulus2.gain = does not apply for periodic stimuli + cfg.stimulus1.kernelshape = 'sine' + cfg.stimulus1.kernelduration = in seconds (default = isi) + + If the stimulus is transient (below as example for stimulus2), the following options apply + cfg.stimulus2.number = scalar M, how many transients are to be presented per trial (default = 4) + cfg.stimulus2.onset = in seconds, first stimulus relative to the start of the trial (default = 0.7) + cfg.stimulus2.onsetjitter = in seconds, max jitter that is added to the onset (default = 0.2) + cfg.stimulus2.isi = in seconds as the interstimulus interval (default = 0.7) + cfg.stimulus2.isijitter = in seconds, max jitter relative to the previous stimulus (default = 0.2) + cfg.stimulus2.condition = 1xM vector with condition codes for each transient within a trial (default = [1 1 2 2]) + cfg.stimulus2.gain = 1xM vector with gain for each condition for each transient within a trial (default = [1 1 1 1]) + cfg.stimulus2.kernelshape = 'hanning' + cfg.stimulus2.kernelduration = in seconds (default = 0.75*isi) + + RANDOMIZATIONS: + - The onsetjitter is randomized between 0 and the value given, and is always added to the onset. + - The isijitter is randomized between 0 and the value given, and is always added to the interstimulus interval (isi). + - For periodic stimuli, which are constant within a trial, the condition code and gain are shuffled over all trials. + - For transient stimuli, the condition code and gain are shuffled within each trial. + + Using the default settings, we model a peripherally presented flickering stimulus + that appears at different excentricities together with a centrally presented + transient stimulus that appears 4x per trial. To simulate the experiment described + at , you have to call this 4 times with a different cfg.configuration and + cfg.gain to model the task load and use FT_APPENDDATA to concatenate the trials. In + this case cfg.condition models the factor "task load" (2 levels, low and high), + cfg.stimulus1.condition models the factor "excentricity" (4 levels), and + cfg.stimulation2.condition models the factor "stimulus type" (2 levels, non-target + or target). + + See also FT_DIPOLESIMULATION, FT_TIMELOCKSIMULATION, FT_FREQSIMULATION, + FT_CONNECTIVITYSIMULATION, FT_APPENDDATA + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_steadystatesimulation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_stratify` + +```{text} + FT_STRATIFY tries to reduce the variance in a specific feature in the data + that is not related to an effect in two or multiple conditions, but where + that feature may confound the analysis. Stratification is implemented by + randomly removing elements from the data, making the distribution of the + data equal on that feature. + + Use as + [output] = ft_stratify(cfg, input1, input2, ...), or + [output, binaxis] = ft_stratify(cfg, input1, input2, ...) + + For the histogram and the split method, each input is a Nchan X Nobs + matrix. The output is a cell-array with in each cell the same data as in + the corresponding input, except that the observations that should be + removed are marked with a NaN. + + For the equatespike method, each input is a Ntrials X 1 cell-array. Each + trial should contain the spike firing moments (i.e. a logical Nchans X + Nsamples matrix). The output is a cell-array with in each cell the same + data as in the corresponding input, except that spike numbers have been + equated in each trial and channel. + + The configuration should contain + cfg.method = 'histogram' + 'splithilo' + 'splitlohi' + 'splitlolo' + 'splithihi' + 'equatespike' + + The following options apply only to histogram and split methods. + cfg.equalbinavg = 'yes' + cfg.numbin = 10 + cfg.numiter = 2000 + + The following options apply only to the equatespike method. + cfg.pairtrials = 'spikesort', 'linkage' or 'no' (default = 'spikesort') + cfg.channel = 'all' or list with indices ( default = 'all') + + See also FT_FREQSTATISTICS, FT_TIMELOCKSTATISTICS, FT_SOURCESTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_stratify.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_struct2char` + +```{text} + FT_STRUCT2CHAR converts all string elements in a structure + into char-arrays. + + Use as + x = ft_struct2char(x) + + See also FT_STRUCT2STRING, FT_STRUCT2SINGLE, FT_STRUCT2DOUBLE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_struct2char.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_struct2double` + +```{text} + FT_STRUCT2DOUBLE converts all single precision numeric data in a structure + into double precision. It will also convert plain matrices and + cell-arrays. + + Use as + x = ft_struct2double(x) + + Starting from MATLAB 7.0, you can use single precision data in your + computations, i.e. you do not have to convert back to double precision. + + MATLAB version 6.5 and older only support single precision for storing + data in memory or on disk, but do not allow computations on single + precision data. Therefore you should converted your data from single to + double precision after reading from file. + + See also FT_STRUCT2SINGLE, FT_STRUCT2CHAR, FT_STRUCT2STRING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_struct2double.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_struct2single` + +```{text} + FT_STRUCT2SINGLE converts all double precision numeric data in a structure + into single precision, which takes up half the amount of memory compared + to double precision. It will also convert plain matrices and cell-arrays. + + Use as + x = ft_struct2single(x) + + Starting from MATLAB 7.0, you can use single precision data in your + computations, i.e. you do not have to convert back to double precision. + + MATLAB version 6.5 and older only support single precision for storing + data in memory or on disk, but do not allow computations on single + precision data. After reading a single precision structure from file, you + can convert it back with FT_STRUCT2DOUBLE. + + See also FT_STRUCT2DOUBLE, FT_STRUCT2CHAR, FT_STRUCT2STRING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_struct2single.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_struct2string` + +```{text} + FT_STRUCT2STRING converts all char-array elements in a structure + into strings. + + Use as + x = ft_struct2string(x) + + See also FT_STRUCT2CHAR, FT_STRUCT2SINGLE, FT_STRUCT2DOUBLE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_struct2string.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_test` + +```{text} + FT_TEST performs selected FieldTrip test scripts, finds and updates the dependencies of test scripts, finds which high-level FieldTrip functions are not tested, or reports on previous test + results from the dashboard database. + + Use as + ft_test inventorize ... + ft_test run ... + ft_test find_dependency ... + ft_test update_dependency ... + ft_test untested_functions ... + ft_test moxunit_run ... % this is obsolete + ft_test report ... % this is obsolete + ft_test compare ... % this is obsolete + + ========= INVENTORIZE ========= + + To list the tests based on their dependencies, you would do + ft_test inventorize + to list all test functions, or + ft_test inventorize data no + to list test functions that don't need any external data to run. + + Additional optional arguments are specified as key-value pairs and can include + dependency = string or cell-array of strings + upload = string, upload test results to the dashboard, can be 'yes' or 'no' (default = 'yes') + dccnpath = string, allow files to be read from the DCCN path, can be 'yes' or 'no' (default is automatic) + maxmem = number (in bytes) or string such as 10GB + maxwalltime = number (in seconds) or string such as HH:MM:SS + data = string or cell-array of strings with 'no', 'public' and/or 'private' + sort = string, can be 'alphabetical', 'walltime', 'mem' or 'random' (default = 'alphabetical') + returnerror = string, whether give an error upon detecting a failed script, can be 'immediate', 'final', 'no' (default = 'no') + + ========= RUN ========= + + To execute a test and submit the results to the dashboard database, you would do + ft_test run + to run all test functions, or + ft_test run test_bug46 + to run a selected test. + + Test functions should not require any input arguments. Any output arguments will + not be considered. + + Additional optional arguments are specified as key-value pairs and can include + dependency = string or cell-array of strings + upload = string, upload test results to the dashboard, can be 'yes' or 'no' (default = 'yes') + dccnpath = string, allow files to be read from the DCCN path, can be 'yes' or 'no' (default is automatic) + maxmem = number (in bytes) or string such as 10GB + maxwalltime = number (in seconds) or string such as HH:MM:SS + data = string or cell-array of strings with 'no', 'public' and/or 'private' + sort = string, can be 'alphabetical', 'walltime', 'mem' or 'random' (default = 'alphabetical') + returnerror = string, whether give an error upon detecting a failed script, can be 'immediate', 'final', 'no' (default = 'no') + + ========= FIND_DEPENDENCY ========= + + To find on what functions test scripts depend on, you would do + ft_test find_dependency test_bug46 + to find on what functions test_bug46 depends on. + + It outputs: + inlist = Nx1 cell-array, describes the rows and lists the test scripts + outlist = 1xM cell-array, describes the columns and lists the dependencies + depmat = NxM dependency matrix, see below + + The dependency matrix contains the following values: + - 0 if there is no dependency + - 2 for a direct dependency + + ========= UPDATE_DEPENDENCY ========= + + To update the DEPENDENCY header in a specific test script, you would do: + ft_test update_dependency test_bug46 + + ========= UNTESTED_FUNCTIONS ========= + + To find FieldTrip high-level functions not tested by any test scripts, + you would do + ft_test untested_functions + + ========= MOXUNIT_RUN ========= + + To execute tests using MOxUNit, you would do + ft_test moxunit_run + + This feature is still experimental, but should support the same + options as ft_test run (see above), and in addition: + xmloutput = string, filename for JUnit-like XML file with test + results (used for shippable CI). + exclude_if_prefix_equals_failed = string, if set to false (or 'no') + then tests are also run if their filename starts + with 'failed'. If set to true (or 'yes'), which is + the default, then filenames starting with 'failed' + are skipped. + + ========= REPORT ========= + + To print a table with the results on screen, you would do + ft_test report + to show all, or for a specific one + ft_test report test_bug46 + + Additional query arguments are specified as key-value pairs and can include + matlabversion = string, for example 2016b + fieldtripversion = string + branch = string + arch = string, can be glnxa64, maci64. win32 or win64 + hostname = string + user = string + + Optionally, you may capture the output to get the results as a Matlab table + array, in which case they are not automatically displayed. + rslt = ft_test('report', 'fieldtripversion', 'cef3396'); + + ========= COMPARE ========= + + To print a table comparing different test results, you would do + ft_test compare matlabversion 2015b 2016b + ft_test compare fieldtripversion ea3c2b9 314d186 + ft_test compare arch glnxa64 win32 + + Additional query arguments are specified as key-value pairs and can include + matlabversion = string, for example 2016b + fieldtripversion = string + branch = string + arch = string, can be glnxa64, maci64. win32 or win64 + hostname = string + user = string + + See also DCCNPATH, FT_VERSION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_test.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_timelockanalysis` + +```{text} + FT_TIMELOCKANALYSIS computes the timelocked average ERP/ERF and optionally computes + the covariance matrix over the specified time window. + + Use as + [timelock] = ft_timelockanalysis(cfg, data) + + The data should be organised in a structure as obtained from FT_PREPROCESSING. + The configuration should be according to + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.latency = [begin end] in seconds, or 'all', 'minperiod', 'maxperiod', 'prestim', 'poststim' (default = 'all') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.keeptrials = 'yes' or 'no', return individual trials or average (default = 'no') + cfg.nanmean = string, can be 'yes' or 'no' (default = 'yes') + cfg.normalizevar = 'N' or 'N-1' (default = 'N-1') + cfg.covariance = 'no' or 'yes' (default = 'no') + cfg.covariancewindow = [begin end] in seconds, or 'all', 'minperiod', 'maxperiod', 'prestim', 'poststim' (default = 'all') + cfg.removemean = 'yes' or 'no', for the covariance computation (default = 'yes') + + 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_TIMELOCKGRANDAVERAGE, FT_TIMELOCKSTATISTICS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_timelockanalysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_timelockbaseline` + +```{text} + FT_TIMELOCKBASELINE performs baseline correction for ERF and ERP data. To apply + baseline correction to data that is not timelocked, use ft_preprocessing instead. + + Use as + [timelock] = ft_timelockbaseline(cfg, timelock) + where the timelock data is the output from FT_TIMELOCKANALYSIS, and the + configuration should contain + cfg.baseline = [begin end] (default = 'no') + cfg.channel = cell-array, see FT_CHANNELSELECTION + cfg.parameter = field for which to apply baseline normalization, or + cell-array of strings to specify multiple fields to normalize + (default = 'avg') + 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_TIMELOCKANALYSIS, FT_FREQBASELINE, FT_TIMELOCKGRANDAVERAGE, FT_DATATYPE_TIMELOCK + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_timelockbaseline.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_timelockgrandaverage` + +```{text} + FT_TIMELOCKGRANDAVERAGE computes ERF/ERP average and variance + over multiple subjects or over blocks within one subject + + Use as + [grandavg] = ft_timelockgrandaverage(cfg, avg1, avg2, avg3, ...) + + where + avg1..N are the ERF/ERP averages as obtained from FT_TIMELOCKANALYSIS + + and cfg is a configuration structure with + cfg.method = string, 'across' or 'within' (default = 'across'), see below for details + cfg.parameter = string, which parameter to average (default = 'avg') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.latency = [begin end] in seconds or 'all' (default = 'all') + cfg.keepindividual = string, 'yes' or 'no' (default = 'no') + cfg.nanmean = string, can be 'yes' or 'no' (default = 'yes') + cfg.normalizevar = string, 'N' or 'N-1' (default = 'N-1') + + If cfg.method = 'across', a plain average is performed, i.e. the requested + parameter in each input argument is weighted equally in the average. This is useful + when averaging across subjects. The variance-field will contain the variance across + the parameter of interest, and the output dof-field will contain the number of + input arguments. + + If cfg.method = 'within', a weighted average is performed, i.e. the requested + parameter in each input argument is weighted according to the degrees of freedom in + the dof-field. This is useful when averaging within subjects across blocks, e.g. + when each block was recorded in a separate file. The variance-field will contain + the variance across all input observations, and the output dof-field will contain + the total number of observations. + + 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. For this particular function, the input should be + structured as a cell-array. + + See also FT_TIMELOCKANALYSIS, FT_TIMELOCKSTATISTICS, FT_TIMELOCKBASELINE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_timelockgrandaverage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_timelocksimulation` + +```{text} + FT_TIMELOCKSIMULATION computes simulated data that consists of multiple trials in + with each trial contains an event-related potential or field. Following + construction of the time-locked signal in each trial by this function, the signals + can be passed into FT_TIMELOCKANALYSIS to obtain the average and the variance. + + Use as + [data] = ft_timelockstatistics(cfg) + which will return a raw data structure that resembles the output of + FT_PREPROCESSING. + + The number of trials and the time axes of the trials can be specified by + cfg.fsample = simulated sample frequency (default = 1000) + cfg.trllen = length of simulated trials in seconds (default = 1) + cfg.numtrl = number of simulated trials (default = 10) + cfg.baseline = number (default = 0.3) + or by + cfg.time = cell-array with one time axis per trial, which are for example obtained from an existing dataset + + The signal is constructed from three underlying functions. The shape is + controlled with + cfg.s1.numcycli = number (default = 1) + cfg.s1.ampl = number (default = 1.0) + cfg.s2.numcycli = number (default = 2) + cfg.s2.ampl = number (default = 0.7) + cfg.s3.numcycli = number (default = 4) + cfg.s3.ampl = number (default = 0.2) + cfg.noise.ampl = number (default = 0.1) + Specifying numcycli=1 results in a monophasic signal, numcycli=2 is a biphasic, + etc. The three signals are scaled to the indicated amplitude, summed up and a + certain amount of noise is added. + + Other configuration options include + cfg.numchan = number (default = 5) + cfg.randomseed = 'yes' or a number or vector with the seed value (default = 'yes') + + See also FT_TIMELOCKANALYSIS, FT_TIMELOCKSTATISTICS, FT_FREQSIMULATION, + FT_DIPOLESIMULATION, FT_CONNECTIVITYSIMULATION + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_timelocksimulation.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_timelockstatistics` + +```{text} + FT_TIMELOCKSTATISTICS computes significance probabilities and/or critical values of a parametric statistical test + or a non-parametric permutation test. + + Use as + [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) + where the input data is the result from either FT_TIMELOCKANALYSIS or + FT_TIMELOCKGRANDAVERAGE. + + The configuration can contain the following options for data selection + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), + see FT_CHANNELSELECTION for details + cfg.latency = [begin end] in seconds or 'all' (default = 'all') + cfg.avgoverchan = 'yes' or 'no' (default = 'no') + cfg.avgovertime = 'yes' or 'no' (default = 'no') + cfg.parameter = string (default = 'trial' or 'avg') + + Furthermore, the configuration should contain + cfg.method = different methods for calculating the significance probability and/or critical value + 'montecarlo' get Monte-Carlo estimates of the significance probabilities and/or critical values from the permutation distribution, + 'analytic' get significance probabilities and/or critical values from the analytic reference distribution (typically, the sampling distribution under the null hypothesis), + 'stats' use a parametric test from the MATLAB statistics toolbox, + 'mvpa' use functionality from the MVPA-light toolbox for classification or multivariate regression + + The other cfg options depend on the method that you select. You + should read the help of the respective subfunction FT_STATISTICS_XXX + for the corresponding configuration options and for a detailed + explanation of each method. + + 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_TIMELOCKANALYSIS, FT_TIMELOCKGRANDAVERAGE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_timelockstatistics.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_topoplotCC` + +```{text} + FT_TOPOPLOTCC plots the coherence or connectivity between channel pairs + + Use as + ft_topoplotCC(cfg, freq) + + The configuration should contain: + cfg.feedback = string (default = 'textbar') + cfg.layout = specification of the layout, see FT_PREPARE_LAYOUT + cfg.foi = the frequency of interest which is to be plotted (default is the first frequency bin) + cfg.widthparam = string, parameter to be used to control the line width (see below) + cfg.alphaparam = string, parameter to be used to control the opacity (see below) + cfg.colorparam = string, parameter to be used to control the line color + cfg.visible = string, 'on' or 'off' whether figure will be visible (default = 'on') + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.position = location and size of the figure, specified as [left bottom width height] (default is automatic) + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + + The widthparam should be indicated in pixels, e.g. usefull numbers are 1 and + larger. + + The alphaparam should be indicated as opacity between 0 (fully transparent) + and 1 (fully opaque). + + The default is to plot the connections as lines, but you can also use + bidirectional arrows: + cfg.arrowhead = string, 'none', 'stop', 'start', 'both' (default = 'none') + cfg.arrowsize = scalar, size of the arrow head in figure units, + i.e. the same units as the layout (default is automatically determined) + cfg.arrowoffset = scalar, amount that the arrow is shifted to the side in figure units, + i.e. the same units as the layout (default is automatically determined) + cfg.arrowlength = scalar, amount by which the length is reduced relative to the complete line (default = 0.8) + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. For this particular function, the input should be + structured as a cell-array. + + See also FT_PREPARE_LAYOUT, FT_MULTIPLOTCC, FT_CONNECTIVITYPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_topoplotCC.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_topoplotER` + +```{text} + FT_TOPOPLOTER plots the topographic distribution over the head of a 2-dimensional + data representations such as the event-related potentials or fields, or a power + or connectivity spectrum. + + Use as + ft_topoplotER(cfg, timelock) + or + ft_topoplotER(cfg, freq) + + The data can be an ERP/ERF produced by FT_TIMELOCKANALYSIS, a power spectrum + (without time dimension) produced by FT_FREQANALYSIS or a connectivity spectrum + produced by FT_CONNECTIVITYANALYSIS. Also, the output to FT_FREQSTATISTICS and + FT_TIMELOCKSTATISTICS can be visualised. + + The configuration can have the following parameters + cfg.parameter = field that contains the data to be plotted as color, for example 'avg', 'powspctrm' or 'cohspctrm' (default is automatic) + cfg.maskparameter = field in the data to be used for masking of data. It should have alues between 0 and 1, where 0 corresponds to transparent. + cfg.xlim = limit for 1st dimension in data (e.g., time), can be 'maxmin' or [xmin xmax] (default = 'maxmin') + cfg.zlim = limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' + cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE + cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + cfg.marker = 'on', 'labels', 'numbers', 'off' + cfg.markersymbol = channel marker symbol (default = 'o') + cfg.markercolor = channel marker color (default = [0 0 0] (black)) + cfg.markersize = channel marker size (default = 2) + cfg.markerfontsize = font size of channel labels (default = 8 pt) + cfg.highlight = 'off', 'on', 'labels', 'numbers' + cfg.highlightchannel = Nx1 cell-array with selection of channels, or vector containing channel indices see FT_CHANNELSELECTION + cfg.highlightsymbol = highlight marker symbol (default = 'o') + cfg.highlightcolor = highlight marker color (default = [0 0 0] (black)) + cfg.highlightsize = highlight marker size (default = 6) + cfg.highlightfontsize = highlight marker size (default = 8) + cfg.hotkeys = enables hotkeys (pageup/pagedown/m) for dynamic zoom and translation (ctrl+) of the color limits + cfg.colorbar = whether to show a colorbar alongside the figure (default = 'no') + 'no' do not show a colorbar + 'yes' at the default MATLAB location + 'North' inside plot box near top + 'South' inside bottom + 'East' inside right + 'West' inside left + 'NorthOutside' outside plot box near top + 'SouthOutside' outside bottom + 'EastOutside' outside right + 'WestOutside' outside left + cfg.colorbartext = string indicating the text next to colorbar + cfg.interplimits = limits for interpolation (default = 'head') + 'sensors' to furthest sensor + 'head' to edge of head + cfg.interpolation = 'linear', 'cubic', 'nearest', 'v4' (default = 'v4') see GRIDDATA + cfg.style = plot style (default = 'both') + 'straight' colormap only + 'contour' contour lines only + 'both' both colormap and contour lines + 'fill' constant color between lines + 'blank' only the head shape + 'straight_imsat' colormap only, vector-graphics friendly + 'both_imsat' both colormap and contour lines, vector-graphics friendly + cfg.gridscale = scaling grid size that determines resolution of figure (default = 67) + cfg.shading = 'flat' or 'interp' (default = 'flat') + cfg.comment = 'no', 'auto' or 'xlim' (default = 'auto') + 'auto': date, xparam and zparam limits are printed + 'xlim': only xparam limits are printed + cfg.commentpos = string or two numbers, position of the comment (default = 'leftbottom') + 'lefttop' 'leftbottom' 'middletop' 'middlebottom' 'righttop' 'rightbottom' + 'title' to place comment as title + 'layout' to place comment as specified for COMNT in layout + [x y] coordinates + cfg.interactive = Interactive plot 'yes' or 'no' (default = 'yes') + In a interactive plot you can select areas and produce a new + interactive plot when a selected area is clicked. Multiple areas + can be selected by holding down the SHIFT key. + cfg.directionality = '', 'inflow' or 'outflow' specifies for + connectivity measures whether the inflow into a + node, or the outflow from a node is plotted. The + (default) behavior of this option depends on the dimord + of the input data (see below). + cfg.layout = specify the channel layout for plotting using one of the supported ways (see below). + cfg.interpolatenan = 'yes' or 'no', whether to interpolate over channels containing NaNs (default = 'yes') + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + + For the plotting of directional connectivity data the cfg.directionality option + determines what is plotted. The default value and the supported functionality + depend on the dimord of the input data. If the input data is of dimord + 'chan_chan_XXX', the value of directionality determines whether, given the + reference channel(s), the columns (inflow), or rows (outflow) are selected for + plotting. In this situation the default is 'inflow'. Note that for undirected + measures, inflow and outflow should give the same output. If the input data is of + dimord 'chancmb_XXX', the value of directionality determines whether the rows in + data.labelcmb are selected. With 'inflow' the rows are selected if the + refchannel(s) occur in the right column, with 'outflow' the rows are selected if + the refchannel(s) occur in the left column of the labelcmb-field. Default in this + case is '', which means that all rows are selected in which the refchannel(s) + occur. This is to robustly support linearly indexed undirected connectivity + metrics. In the situation where undirected connectivity measures are linearly + indexed, specifying 'inflow' or 'outflow' can result in unexpected behavior. + + The layout defines how the channels are arranged. You can specify the + layout in a variety of ways: + - you can provide a pre-computed layout structure, see FT_PREPARE_LAYOUT + - you can give the name of an ascii layout file with extension *.lay + - you can give the name of an electrode file + - you can give an electrode definition, i.e. "elec" structure + - you can give a gradiometer definition, i.e. "grad" structure + If you do not specify any of these and the data structure contains an + electrode or gradiometer structure, that will be used for creating a + layout. If you want to have more fine-grained control over the layout + of the subplots, you should create your own layout file. + + See also FT_SINGLEPLOTER, FT_MULTIPLOTER, FT_SINGLEPLOTTFR, FT_MULTIPLOTTFR, + FT_TOPOPLOTTFR, FT_PREPARE_LAYOUT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_topoplotER.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_topoplotIC` + +```{text} + FT_TOPOPLOTIC plots the topographic distribution of an independent + component that was computed using the FT_COMPONENTANALYSIS function, + as a 2-D circular view (looking down at the top of the head). + + Use as + ft_topoplotIC(cfg, comp) + where the input comp structure should be obtained from FT_COMPONENTANALYSIS. + + The configuration should have the following parameters: + cfg.component = field that contains the independent component(s) to be plotted as color + cfg.layout = specification of the layout, see below + + The configuration can have the following parameters: + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + cfg.zlim = plotting limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.marker = 'on', 'labels', 'numbers', 'off' + cfg.markersymbol = channel marker symbol (default = 'o') + cfg.markercolor = channel marker color (default = [0 0 0] (black)) + cfg.markersize = channel marker size (default = 2) + cfg.markerfontsize = font size of channel labels (default = 8 pt) + cfg.highlight = 'on', 'labels', 'numbers', 'off' + cfg.highlightchannel = Nx1 cell-array with selection of channels, or vector containing channel indices see FT_CHANNELSELECTION + cfg.highlightsymbol = highlight marker symbol (default = 'o') + cfg.highlightcolor = highlight marker color (default = [0 0 0] (black)) + cfg.highlightsize = highlight marker size (default = 6) + cfg.highlightfontsize = highlight marker size (default = 8) + cfg.colorbar = 'yes' + 'no' (default) + 'North' inside plot box near top + 'South' inside bottom + 'East' inside right + 'West' inside left + 'NorthOutside' outside plot box near top + 'SouthOutside' outside bottom + 'EastOutside' outside right + 'WestOutside' outside left + cfg.colorbartext = string indicating the text next to colorbar + cfg.interplimits = limits for interpolation (default = 'head') + 'sensors' to furthest sensor + 'head' to edge of head + cfg.interpolation = 'linear','cubic','nearest','v4' (default = 'v4') see GRIDDATA + cfg.style = plot style (default = 'both') + 'straight' colormap only + 'contour' contour lines only + 'both' both colormap and contour lines + 'fill' constant color between lines + 'blank' only the head shape + 'straight_imsat' colormap only, vector-graphics friendly + 'both_imsat' both colormap and contour lines, vector-graphics friendly + cfg.gridscale = scaling grid size (default = 67) + determines resolution of figure + cfg.shading = 'flat' 'interp' (default = 'flat') + cfg.comment = string 'no' 'auto' or 'xlim' (default = 'auto') + 'auto': date, xparam and zparam limits are printed + 'xlim': only xparam limits are printed + cfg.commentpos = string or two numbers, position of comment (default 'leftbottom') + 'lefttop' 'leftbottom' 'middletop' 'middlebottom' 'righttop' 'rightbottom' + 'title' to place comment as title + 'layout' to place comment as specified for COMNT in layout + [x y] coordinates + cfg.title = string or 'auto' or 'off', specify a figure title, or use 'component N' (default) as the title + cfg.figure = 'yes' or 'no', whether to open a new figure. You can also specify a figure handle from FIGURE, GCF or SUBPLOT. (default = 'yes') + cfg.renderer = string, 'opengl', 'zbuffer', 'painters', see RENDERERINFO (default is automatic, try 'painters' when it crashes) + + The layout defines how the channels are arranged. You can specify the + layout in a variety of ways: + - you can provide a pre-computed layout structure (see prepare_layout) + - you can give the name of an ascii layout file with extension *.lay + - you can give the name of an electrode file + - you can give an electrode definition, i.e. "elec" structure + - you can give a gradiometer definition, i.e. "grad" structure + If you do not specify any of these and the data structure contains an + electrode or gradiometer structure, that will be used for creating a + layout. If you want to have more fine-grained control over the layout + of the subplots, you should create your own layout file. + + See also FT_COMPONENTANALYSIS, FT_REJECTCOMPONENT, FT_TOPOPLOTTFR, + FT_SINGLEPLOTTFR, FT_MULTIPLOTTFR, FT_PREPARE_LAYOUT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_topoplotIC.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_topoplotTFR` + +```{text} + FT_TOPOPLOTTFR plots the topographic distribution over the head + of a 3-dimensional data representations such as time-frequency + representation of the power or coherence spectrum. + + Use as + ft_topoplotTFR(cfg, freq) + + The input freq structrure should contain a time-resolved power or + coherence spectrum from FT_FREQANALYSIS or FT_FREQDESCRIPTIVES. + + The configuration can have the following parameters + cfg.parameter = field that contains the data to be plotted as color, for example 'avg', 'powspctrm' or 'cohspctrm' (default is automatic) + cfg.maskparameter = field in the data to be used for masking of data. It should have alues between 0 and 1, where 0 corresponds to transparent. + cfg.xlim = limit for 1st dimension in data (e.g., time), can be 'maxmin' or [xmin xmax] (default = 'maxmin') + cfg.ylim = limit for 2nd dimension in data (e.g., freq), can be 'maxmin' or [ymin ymax] (default = 'maxmin') + cfg.zlim = limits for color dimension, 'maxmin', 'maxabs', 'zeromax', 'minzero', or [zmin zmax] (default = 'maxmin') + cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see FT_CHANNELSELECTION for details + cfg.refchannel = name of reference channel for visualising connectivity, can be 'gui' + cfg.baseline = 'yes','no' or [time1 time2] (default = 'no'), see FT_TIMELOCKBASELINE or FT_FREQBASELINE + cfg.baselinetype = 'absolute' or 'relative' (default = 'absolute') + cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') + cfg.colormap = string, or Nx3 matrix, see FT_COLORMAP + cfg.marker = 'on', 'labels', 'numbers', 'off' + cfg.markersymbol = channel marker symbol (default = 'o') + cfg.markercolor = channel marker color (default = [0 0 0] (black)) + cfg.markersize = channel marker size (default = 2) + cfg.markerfontsize = font size of channel labels (default = 8 pt) + cfg.highlight = 'off', 'on', 'labels', 'numbers' + cfg.highlightchannel = Nx1 cell-array with selection of channels, or vector containing channel indices see FT_CHANNELSELECTION + cfg.highlightsymbol = highlight marker symbol (default = 'o') + cfg.highlightcolor = highlight marker color (default = [0 0 0] (black)) + cfg.highlightsize = highlight marker size (default = 6) + cfg.highlightfontsize = highlight marker size (default = 8) + cfg.hotkeys = enables hotkeys (pageup/pagedown/m) for dynamic zoom and translation (ctrl+) of the color limits + cfg.colorbar = 'yes' + 'no' (default) + 'North' inside plot box near top + 'South' inside bottom + 'East' inside right + 'West' inside left + 'NorthOutside' outside plot box near top + 'SouthOutside' outside bottom + 'EastOutside' outside right + 'WestOutside' outside left + cfg.colorbartext = string indicating the text next to colorbar + cfg.interplimits = limits for interpolation (default = 'head') + 'sensors' to furthest sensor + 'head' to edge of head + cfg.interpolation = 'linear','cubic','nearest','v4' (default = 'v4') see GRIDDATA + cfg.style = plot style (default = 'both') + 'straight' colormap only + 'contour' contour lines only + 'both' both colormap and contour lines + 'fill' constant color between lines + 'blank' only the head shape + 'straight_imsat' colormap only, vector-graphics friendly + 'both_imsat' both colormap and contour lines, vector-graphics friendly + cfg.gridscale = scaling grid size (default = 67) + determines resolution of figure + cfg.shading = 'flat' or 'interp' (default = 'flat') + cfg.comment = 'no', 'auto' or 'xlim' (default = 'auto') + 'auto': date, xparam, yparam and parameter limits are printed + 'xlim': only xparam limits are printed + 'ylim': only yparam limits are printed + cfg.commentpos = string or two numbers, position of the comment (default = 'leftbottom') + 'lefttop' 'leftbottom' 'middletop' 'middlebottom' 'righttop' 'rightbottom' + 'title' to place comment as title + 'layout' to place comment as specified for COMNT in layout + [x y] coordinates + cfg.interactive = Interactive plot 'yes' or 'no' (default = 'yes') + In a interactive plot you can select areas and produce a new + interactive plot when a selected area is clicked. Multiple areas + can be selected by holding down the SHIFT key. + cfg.directionality = '', 'inflow' or 'outflow' specifies for + connectivity measures whether the inflow into a + node, or the outflow from a node is plotted. The + (default) behavior of this option depends on the dimor + of the input data (see below). + cfg.layout = specify the channel layout for plotting using one of + the supported ways (see below). + cfg.interpolatenan = string 'yes', 'no' (default = 'yes') + interpolate over channels containing NaNs + + For the plotting of directional connectivity data the cfg.directionality + option determines what is plotted. The default value and the supported + functionality depend on the dimord of the input data. If the input data + is of dimord 'chan_chan_XXX', the value of directionality determines + whether, given the reference channel(s), the columns (inflow), or rows + (outflow) are selected for plotting. In this situation the default is + 'inflow'. Note that for undirected measures, inflow and outflow should + give the same output. If the input data is of dimord 'chancmb_XXX', the + value of directionality determines whether the rows in data.labelcmb are + selected. With 'inflow' the rows are selected if the refchannel(s) occur in + the right column, with 'outflow' the rows are selected if the + refchannel(s) occur in the left column of the labelcmb-field. Default in + this case is '', which means that all rows are selected in which the + refchannel(s) occur. This is to robustly support linearly indexed + undirected connectivity metrics. In the situation where undirected + connectivity measures are linearly indexed, specifying 'inflow' or + 'outflow' can result in unexpected behavior. + + The layout defines how the channels are arranged. You can specify the + layout in a variety of ways: + - you can provide a pre-computed layout structure (see prepare_layout) + - you can give the name of an ascii layout file with extension *.lay + - you can give the name of an electrode file + - you can give an electrode definition, i.e. "elec" structure + - you can give a gradiometer definition, i.e. "grad" structure + If you do not specify any of these and the data structure contains an + electrode or gradiometer structure, that will be used for creating a + layout. If you want to have more fine-grained control over the layout + of the subplots, you should create your own layout file. + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. For this particular function, the input should be + structured as a cell-array. + + See also FT_TOPOPLOTER, FT_TOPOPLOTIC, FT_SINGLEPLOTTFR, FT_MULTIPLOTTFR, FT_PREPARE_LAYOUT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_topoplotTFR.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trackusage` + +```{text} + FT_TRACKUSAGE tracks the usage of specific FieldTrip components using a central + tracking server. This involves sending a small snippet of information to the + server. Tracking is only used to gather data on the usage of the FieldTrip + toolbox, to get information on the number of users and on the frequency of use + of specific toolbox functions. This allows the toolbox developers to improve the + FIeldTrip toolbox source code, documentation and to provide better support. + + This function will NOT upload any information about the data, nor about the + configuration that you are using in your analyses. + + This function will NOT upload any identifying details about you. Your username + and computer name are "salted" and subsequently converted with the MD5 + cryptographic hashing function into a unique identifier. Not knowing the salt, + it is impossible to decode these MD5 hashes and recover the original + identifiers. + + It is possible to disable the tracking for all functions by specifying + the following + global ft_defaults + ft_default.trackusage = 'no' + + See the following online documentation for more information + http://en.wikipedia.org/wiki/MD5 + http://en.wikipedia.org/wiki/Salt_(cryptography) + http://www.fieldtriptoolbox.org/faq/tracking + + See also FT_DEFAULTS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_trackusage.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_transform_geometry` + +```{text} + FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to a + structure with geometric information, for example a volume conduction model for the + head, gradiometer of electrode structure containing EEG or MEG sensor positions and + MEG coil orientations, a head shape or a source model. + + Use as + [output] = ft_transform_geometry(transform, input) + where the transform should be a 4x4 homogeneous transformation matrix and the input + data structure can be any of the FieldTrip data structures that describes + geometrical data, or + [output] = ft_transform_geometry(transform, input, method) + where the transform contains a set of parameters that can be converted into a 4x4 + homogeneous transformation matrix, using one of the supported methods: + 'rotate', 'scale', 'translate', 'rigidbody'. All methods require a 3-element vector + as parameters, apart from rigidbody, which requires 6 parameters. + + The units of the transformation matrix must be the same as the units in which the + geometric object is expressed. + + The type of geometric object constrains the type of allowed transformations. + + For sensor arrays: + If the input is an MEG gradiometer array, only a rigid-body translation plus + rotation are allowed. If the input is an EEG electrode or fNIRS optodes array, + global rescaling and individual axis rescaling is also allowed. + + For volume conduction models: + If the input is a volume conductor model of the following type: + localspheres model + singleshell model with the spherical harmonic coefficients already computed + BEM model with system matrix already computed + FEM model with volumetric elements + only a rigid-body translation plus rotation are allowed. + + If the input is a volume conductor model of the following type: + BEM model with the system matrix not yet computed + singleshell model with the spherical harmonic coefficients not yet computed + rotation, translation, global rescaling and individual axis rescaling is allowed. + + If the input is a volume conductor model of the following type: + single sphere + concentric spheres + rotation, translation and global rescaling is allowed. + + For source models, either defined as a 3D regular grid, a 2D mesh or unstructred + point cloud, rotation, translation, global rescaling and individual axis rescaling + is allowed. + + For anatomical MRIs and functional volumetric data, rotation, translation, global + rescaling and individual axis rescaling are allowed. + + See also FT_WARP_APPLY, FT_HEADCOORDINATES, FT_SCALINGFACTOR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_transform_geometry.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_transform_headmodel` + +```{text} + This function is a backward compatibility wrapper for existing MATLAB scripts + that call a function that is not part of the FieldTrip toolbox any more. + + Please update your code to make it future-proof. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_transform_headmodel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_transform_headshape` + +```{text} + This function is a backward compatibility wrapper for existing MATLAB scripts + that call a function that is not part of the FieldTrip toolbox any more. + + Please update your code to make it future-proof. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_transform_headshape.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_transform_sens` + +```{text} + This function is a backward compatibility wrapper for existing MATLAB scripts + that call a function that is not part of the FieldTrip toolbox any more. + + Please update your code to make it future-proof. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_transform_sens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_transform_vol` + +```{text} + This function is a backward compatibility wrapper for existing MATLAB scripts + that call a function that is not part of the FieldTrip toolbox any more. + + Please update your code to make it future-proof. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_transform_vol.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_balert` + +```{text} + FT_TRIALFUN_BALERT extract trials from B-Alert data using an intermediate CSV file. + FieldTrip cannot yet directly interpret the event markers from B-Alert data. + Therefore, it is necessary to have B-Alert LAB. This is (paid) software from + Advanced Brain Monitoring, in which you extract the eventmakers using the function: + readevents(*.Events.edf, *.Signals.Raw.edf) to write a *.csv file. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the *.csv filename + cfg.trialfun = 'ft_trialfun_balert' + + See also FT_DEFINETRIAL, FT_PREPROCESSING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_balert.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_bids` + +```{text} + FT_TRIALFUN_BIDS determines trials/segments to be used for subsequent analysis, on + the basis of the BIDS "events.tsv" file. This function should in general not be + called directly, it will be called by FT_DEFINETRIAL. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialdef = structure with the details of trial definition, see below + cfg.trialfun = 'ft_trialfun_bids' + + The trialdef structure should either contain the following + cfg.trialdef.prestim = latency in seconds + cfg.trialdef.poststim = latency in seconds + or the duration and offset relative to the event of interest + cfg.trialdef.duration = latency in seconds + cfg.trialdef.offset = latency in seconds + + You can specify your selection of events as + cfg.trialdef.columnname = columnvalue + where the column name and value have to match those present in the events.tsv file. + + For example + cfg.trialdef.prestim = 0.2; + cfg.trialdef.poststim = 0.8; + cfg.trialdef.task = 'notarget'; + cfg.trialdef.category = 'tools'; + cfg.trialdef.modality = {'written', 'spoken'}; + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_bids.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_brainvision_segmented` + +```{text} + FT_TRIALFUN_BRAINVISION_SEGMENTED creates trials for a Brain Vision Analyzer + dataset that was segmented in the BVA software. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_brainvision_segmented' + + Optionally, you can specify: + cfg.stimformat = 'S %d' + + The stimformat instruct this function to parse stimulus triggers according to + the specific format. The default is 'S %d'. The cfg.stimformat always + needs to contain exactly one %d code. The trigger values parsed in this way + will be stored in columns 4 and upwards of the output 'trl' matrix, and + after FT_PREPROCESSING will end up in data.trialinfo. + + A BrainVision dataset consists of three files: an .eeg, .vhdr, and a .vmrk + file. The option cfg.dataset should refer to the .vhdr file. + + See also FT_DEFINETRIAL, FT_PREPROCESSING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_brainvision_segmented.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_edf` + +```{text} + FT_TRIALFUN_EDF is an example trial function for EDF data. It searches for events + of type "up" in an analog data channel, as indentified by thresholding. This + threshold can be a hard threshold, i.e. a numeric, or can flexibly be defined + depending on the data, for example calculating the 'median' of an analog signal. + + You can use this as a template for your own conditial trial definitions. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_edf' + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_edf.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_emgdetect` + +```{text} + Note that there are some parameters, like the EMG channel name and the + processing that is done on the EMG channel data, which are hardcoded in + this trial function. You should change these parameters if necessary. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_emgdetect.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_example1` + +```{text} + FT_TRIALFUN_EXAMPLE1 is an example trial function. It searches for events + of type "trigger" and specifically for a trigger with value 7, followed + by a trigger with value 64. + + You can use this as a template for your own conditial trial definitions. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_example1' + cfg.trialdef.prestim = number, in seconds + cfg.trialdef.poststim = number, in seconds + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_example1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_example2` + +```{text} + FT_TRIALFUN_EXAMPLE2 is an example trial function that detects muscle activity in + an EMG channel and defines variable length trials from the EMG onset up to the EMG + offset. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_example2' + + Note that there are some parameters, like the EMG channel name and the processing + that is done on the EMG channel data, which are hardcoded in this trial function. + You should change these parameters according to your data. + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_example2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_general` + +```{text} + FT_TRIALFUN_GENERAL reads events from the dataset using FT_READ_EVENT and + constructs a trial definition. This function should in general not be called + directly, it will be called by FT_DEFINETRIAL. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialdef = structure with the details of trial definition, see below + cfg.trialfun = 'ft_trialfun_general' + + The cfg.trialdef structure can contain the following specifications + cfg.trialdef.eventtype = string, or cell-array with strings + cfg.trialdef.eventvalue = number, string, or list with numbers or strings + cfg.trialdef.prestim = number, latency in seconds (optional) + cfg.trialdef.poststim = number, latency in seconds (optional) + + You can specify these options that are passed to FT_READ_EVENT for trigger detection + cfg.trialdef.detectflank = string, can be 'up', 'updiff', 'down', 'downdiff', 'both', 'any', 'biton', 'bitoff' + cfg.trialdef.trigshift = integer, number of samples to shift from flank to detect trigger value + cfg.trialdef.chanindx = list with channel numbers for the trigger detection, specify -1 in case you don't want to detect triggers + cfg.trialdef.threshold = threshold for analog trigger channels + cfg.trialdef.tolerance = tolerance in samples when merging analogue trigger channels, only for Neuromag + + If you want to read all data from a continuous file in segments, you can specify + cfg.trialdef.length = duration of the segments in seconds (can be Inf) + cfg.trialdef.ntrials = number of trials (optional, can be 1) + cfg.trialdef.overlap = single number (between 0 and 1 (exclusive)) specifying the fraction of overlap between snippets (0 = no overlap) + + See also FT_DEFINETRIAL, FT_TRIALFUN_GUI, FT_TRIALFUN_SHOW + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_general.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_gui` + +```{text} + FT_TRIALFUN_GUI reads events from the dataset, displays a graphical user interface + dialog to select the event types and values of interest, and constructs a trial + definition. This function should in general not be called directly, it will be + called by FT_DEFINETRIAL. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_gui' + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL, FT_TRIALFUN_SHOW + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_gui.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_hed` + +```{text} + FT_TRIALFUN_HED is a trial function that can be used with HED tags. It demonstrates + some basic functionality for selecting specific events, but mainly serves as an + example or template for your own conditial trial definitions. For that you would + copy this function and giuve it your own name, e.g. FT_TRIALFUN_MYEXPERIMENT. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_hed' % or your own copy + + The selection of events and timing of the epochs is specified with + cfg.trialdef.regexp = regular expression that is applied to the HED tags + cfg.trialdef.prestim = number, in seconds + cfg.trialdef.poststim = number, in seconds + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL, FT_TRIALFUN_EXAMPLE1, + FT_TRIALFUN_EXAMPLE2 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_hed.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_imotions` + +```{text} + FT_TRIALFUN_IMOTIONS makes a trial definition for an iMotions event structure. + Note that this returns the trial definition as a table rather than as a numeric array. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.event = event structure + cfg.fsample = number, samplijng rate in Hz + cfg.trialfun = 'ft_trialfun_imotions' + cfg.trialdef.eventtype = string or cell-array of strings (default = 'StimulusName') + cfg.trialdef.eventvalue = string or cell-array of strings (default = []) + cfg.trialdef.offset = string, 'absolute' or 'relative' (default = 'absolute') + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_imotions.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_neuromagSTI016fix` + +```{text} + FT_TRIALFUN_NEUROMAGSTI106FIX is supposed to fix the error with STI016 in + Neuromag/Elekta/MEGIN data. It reads the channels STI001 up to STI016, combines the + values into a new "STI101" channel and then uses the new channel to define trials. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string, containing filename or directory + cfg.trialdef.prestim = pre stimulus time in s + cfg.trialdef.poststim = post stimulus time in seconds + cfg.trialdef.eventvalue = list with trigger values + cfg.trialfun = 'ft_trialfun_neuromagSTI016fix'; + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_neuromagSTI016fix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_realtime` + +```{text} + FT_TRIALFUN_REALTIME can be used to segment a continuous stream of + data in real-time. Trials are defined as [begsample endsample offset + condition] + + The configuration structure can contain the following specifications + cfg.minsample = the last sample number that was already considered (passed from rt_process) + cfg.blocksize = in seconds. In case of events, offset is with respect to the trigger. + cfg.offset = the offset wrt the 0 point. In case of no events, offset is wrt + prevSample. E.g., [-0.9 1] will read 1 second blocks with + 0.9 second overlap + cfg.bufferdata = {'first' 'last'}. If 'last' then only the last block of + interest is read. Otherwise, all well-defined blocks are read (default = 'first') + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_realtime.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_show` + +```{text} + FT_TRIALFUN_SHOW will show a summary of the event information on screen. It will + not return an actual trial definition. This function should in general not be + called directly, it will be called by FT_DEFINETRIAL. + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_show' + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL, FT_TRIALFUN_GUI + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_show.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_trial` + +```{text} + FT_TRIALFUN_TRIAL creates a trial definition that corresponds to the events that + are returned by FT_READ_EVENT with type='trial' + + Use this function by calling + [cfg] = ft_definetrial(cfg) + where the configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_trial' + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_trial.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_trialfun_twoclass_classification` + +```{text} + FT_TRIALFUN_TWOCLASS_CLASSIFICATION can be used to train and test a real-time + classifier in offline and online mode. It selects pieces of data in the two classes + based on two trigger values. The first N occurences in each class are marked as + training items. All subsequent occurrences are marked as test items. + + This function can be used in conjunction with FT_REALTIME_CLASSIFICATION. The + configuration structure should contain + cfg.dataset = string with the filename + cfg.trialfun = 'ft_trialfun_twoclass_classification' + cfg.trialdef.numtrain = number of training items, e.g. 20 + cfg.trialdef.eventvalue1 = trigger value for the 1st class + cfg.trialdef.eventvalue2 = trigger value for the 2nd class + cfg.trialdef.eventtype = string, e.g. 'trigger' + cfg.trialdef.prestim = latency in seconds, e.g. 0.3 + cfg.trialdef.poststim = latency in seconds, e.g. 0.7 + + See also FT_DEFINETRIAL, FT_TRIALFUN_GENERAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/trialfun/ft_trialfun_twoclass_classification.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_uilayout` + +```{text} + FT_UILAYOUT is a helper function to make a consistent graphical user interafce with + multiple control elements. This function will find all elements with a specific tag + and style, and update or position them consistently. + + Use as + ft_uilayout(h, 'tag', '...', 'style', '...', ...) + where h is the figure handle and 'tag' and 'style' are used to specifying which + user control elements in the figure should be selected. + + You can pass most options from UICONTROL as key-value pair, such as + 'BackgroundColor', 'CallBack', 'Clipping', 'Enable', 'FontAngle', 'FontName', + 'FontSize', 'FontUnits', 'FontWeight', 'ForegroundColor', 'HorizontalAlignment', + 'Max', 'Min', 'Position', 'Selected', 'String', 'Units', 'Value', 'Visible'. + + In addition to the options from UICONTROL, you can use the following key-value + pairs for a consistent placement of multiple GUI elements relative to each other: + 'hpos' = 'auto' puts elements in horizontal adjacent order with a fixed distance of 0.01 + 'align' adjusts the horizontal position of all elements to the first element + 'distribute' puts elements in horizontal adjacent order such that they distribute evenly + scalar sets the horizontal position of elements to the specified scalar + 'vpos' = 'auto' puts elements in vertical adjacent order with a fixed distance of 0.01 + 'align' adjusts the vertical position of all elements to the first element + 'distribute' puts elements in vertical adjacent order such that they distribute evenly + scalar sets the vertical position of elements to the specified scalar + 'width' = scalar sets the width of elements to the specified scalar + 'height' = scalar sets the height of elements to the specified scalar + 'halign' = 'left' aligns the horizontal position of elements to the left + 'right' aligns the horizontal position of elements to the right + 'valign' = 'top' aligns the vertical position of elements to the top + 'bottom' aligns the vertical position of elements to the bottom + 'halign' = 'left' aligns the horizontal position of elements to the left + 'right' aligns the horizontal position of elements to the right + 'hshift' = scalar shift the elements in horizontal direction + 'vshift' = scalar shift the elements in vertical direction + + Here is an example that positions a number of buttons in a 2x3 grid. It makes use + of regular expressions to match the tags to the rows and columns. + + h = figure; + uicontrol('style', 'pushbutton', 'string', '11', 'tag', 'row1_column1'); + uicontrol('style', 'pushbutton', 'string', '12', 'tag', 'row1_column2'); + uicontrol('style', 'pushbutton', 'string', '13', 'tag', 'row1_column3'); + uicontrol('style', 'pushbutton', 'string', '21', 'tag', 'row2_column1'); + uicontrol('style', 'pushbutton', 'string', '22', 'tag', 'row2_column2'); + uicontrol('style', 'pushbutton', 'string', '23', 'tag', 'row2_column3'); + + ft_uilayout(h, 'tag', '^row1', 'vpos', 100); + ft_uilayout(h, 'tag', '^row2', 'vpos', 200); + + ft_uilayout(h, 'tag', 'column1$', 'hpos', 100); + ft_uilayout(h, 'tag', 'column2$', 'hpos', 200); + ft_uilayout(h, 'tag', 'column3$', 'hpos', 300); + + ft_uilayout(h, 'tag', '.*', 'BackGroundColor', [1 0 0]); + + See also UICONTROL, ALIGN, UISTACK + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/plotting/ft_uilayout.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_version` + +```{text} + FT_VERSION returns the version of FieldTrip and the path where it is installed + + FieldTrip is not released with version numbers as "2.0", "2.1", etc. Instead, we + share our development version on http://github.com/fieldtrip/fieldtrip. You can use + git to make a local clone of the development version. Furthermore, we make + more-or-less daily releases of the code available on + https://github.com/fieldtrip/fieldtrip/releases and as zip file on our FTP server. + + If you use git with the development version, the version is labeled with the hash + of the latest commit like "128c693". You can access the specific version "XXXXXX" + at https://github.com/fieldtrip/fieldtrip/commit/XXXXXX. + + If you download the daily released version from our FTP server, the version is part + of the file name "fieldtrip-YYYYMMDD.zip", where YYY, MM and DD correspond to year, + month and day. + + Use as + ft_version + to display the latest revision number on screen, or + [ftver, ftpath] = ft_version + to get the version and the installation root directory. + + When using git with the development version, you can also get additional information with + ft_version revision + ft_version branch + ft_version clean + + On macOS you might have installed git along with Xcode instead of with homebrew, + which then requires that you agree to the Apple license. In that case it can + happen that this function stops, as in the background (invisible to you) it is + asking whether you agree. You can check this by typing "/usr/bin/git", which will + show the normal help message, or which will mention the license agreement. To + resolve this please open a terminal and type "sudo xcodebuild -license" + + See also FT_PLATFORM_SUPPORTS, VERSION, VER, VERLESSTHAN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_version.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_virtualchannel` + +```{text} + FT_VIRTUALCHANNEL creates virtual channel data, combining numeric data from a data + structure defined at the channel level with spatial filter information from a + source data structure, and optional parcellation information. + + Use as + output = ft_virtualchannel(cfg, data, source) + or + output = ft_virtualchannel(cfg, data, source, parcellation) + + where the input "data" is a channel-level data structure that can be linearly + mapped onto the virtual channel level, e.g. a raw data structure obtained with + FT_PREPROCESSING, a timelock structure, obtained with FT_TIMELOCKANALYSIS, or a + freq structure with fourierspectra, obtained with FT_FREQANALYSIS. + + The input "source" is a source structure that has been obtained with + FT_SOURCEANALYSIS, and which contains spatial filter information for at least one + dipole location, in the source.filter, or source.avg.filter field. + + The optional input "parcellation" is described in detail in + FT_DATATYPE_PARCELLATION (2-D) or FT_DATATYPE_SEGMENTATION (3-D) and can be + obtained from FT_READ_ATLAS or from a custom parcellation/segmentation for your + individual subject. Alternatively, the input "source" can already contain a + parcellation. + + The configuration "cfg" is a structure that should either contain + cfg.pos = Nx3 matrix containing the dipole positions for the virtual + channel(s). These positions should match the entries in + the source.pos field. (default = []) + or + cfg.parcellation = string, name of the field that is used for the + parcel labels. (default = []) + cfg.parcel = string, or cell-array of strings, specifying for which + parcels to return the output. (default = 'all') + + Moreover, the cfg structure can contain + cfg.method = string, determines how the components of the specified virtual + channel(s) are to to be combined. 'svd' (default), 'none', 'pca', + 'runica', 'fastica', 'dss'. + cfg.numcomponent = scalar (or 'all'), determines the number of components per virtual + channel in the output. (default = 1) + + See also FT_SOURCEANALYSIS, FT_DATATYPE_PARCELLATION, FT_DATATYPE_SEGMENTATION, + FT_SOURCEPARCELLATE, FT_COMPONENTANALYSIS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_virtualchannel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumebiascorrect` + +```{text} + FT_VOLUMEBIASCORRECT corrects the image inhomogeneity bias in an anatomical MRI + + Use as + mri_unbias = ft_volumebiascorrect(cfg, mri) + where the input mri should be a single anatomical volume organised in a structure + as obtained from the FT_READ_MRI function + + The configuration structure can contain + cfg.spmversion = string, 'spm8', 'spm12' (default = 'spm12') + cfg.opts = struct, containing spmversion specific options. + See the code below and the SPM-documentation for + more information. + + See also FT_VOLUMEREALIGN FT_VOLUMESEGMENT FT_VOLUMENORMALISE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumebiascorrect.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumedownsample` + +```{text} + FT_VOLUMEDOWNSAMPLE downsamples, or more precisely decimates an anatomical MRI or + source reconstruction and optionally normalizes its coordinate axes, keeping the + homogenous transformation matrix correct. + + Use as + [downsampled] = ft_volumedownsample(cfg, data) + where the input data structure should be an anatomical MRI that was for example + read with FT_READ_MRI or should be a volumetric source reconstruction from + FT_SOURCEANALYSIS or FT_SOURCEINTERPOLATE. + + The configuration can contain + cfg.downsample = integer number (default = 1, i.e. no downsampling) + cfg.parameter = string, data field to downsample (default = 'all') + cfg.smooth = 'no' or the FWHM of the gaussian kernel in voxels (default = 'no') + cfg.keepinside = 'yes' or 'no', keep the inside/outside labeling (default = 'yes') + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + + 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_SOURCEINTERPOLATE, FT_VOLUMEWRITE and FT_VOLUMENORMALISE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumedownsample.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumelookup` + +```{text} + FT_VOLUMELOOKUP can be used in to combine an anatomical or functional + atlas with the source reconstruction results. You can use it for forward + and reverse lookup. + + Given the region of interest (ROI) as anatomical or functional label, it + looks up the locations and creates a mask (as a binary volume) based on + the label. Given the ROI as point in the brain, it creates a sphere or + box around that point. In these two case the function is to be used as: + mask = ft_volumelookup(cfg, volume) + + Given a binary volume that indicates a ROI or a point of interest (POI), + it looks up the corresponding anatomical or functional labels from the + atlas. In this case the function is to be used as: + labels = ft_volumelookup(cfg, volume) + + In both cases the input volume can be: + mri is the output of FT_READ_MRI source is the output of FT_SOURCEANALYSIS + stat is the output of FT_SOURCESTATISTICS + + The configuration options for a mask according to an atlas: + cfg.atlas = string, filename of atlas to use, see FT_READ_ATLAS + cfg.roi = string or cell-array of strings, ROI from anatomical atlas + + The configuration options for a spherical/box mask around a POI: + cfg.roi = Nx3 vector, coordinates of the POI + cfg.sphere = radius of each sphere in cm/mm dep on unit of input + cfg.box = Nx3 vector, size of each box in cm/mm dep on unit of input + cfg.round2nearestvoxel = 'yes' or 'no' (default = 'no'), voxel closest to point of interest is calculated + and box/sphere is centered around coordinates of that voxel + + The configuration options for labels from a mask: + cfg.atlas = string, filename of atlas to use, see FT_READ_ATLAS + cfg.maskparameter = string, field in volume to be looked up, data in field should be logical + cfg.minqueryrange = number, should be odd and <= to maxqueryrange (default = 1) + cfg.maxqueryrange = number, should be odd and >= to minqueryrange (default = 1) + + The configuration options for labels around POI: + cfg.output = 'single' always outputs one label; if several POI are provided, they are considered together as describing a ROI (default) + 'multiple' outputs one label per POI (e.g., choose to get labels for different electrodes) + cfg.roi = Nx3 vector, coordinates of the POI + cfg.atlas = string, filename of atlas to use, see FT_READ_ATLAS + cfg.minqueryrange = number, should be odd and <= to maxqueryrange (default = 1) + cfg.maxqueryrange = number, should be odd and >= to minqueryrange (default = 1) + cfg.querymethod = 'sphere' searches voxels around the ROI in a sphere (default) + = 'cube' searches voxels around the ROI in a cube + cfg.round2nearestvoxel = 'yes' or 'no', voxel closest to POI is calculated (default = 'yes') + + The label output has a field "names", a field "count" and a field "usedqueryrange". + To get a list of areas of the given mask you can do for instance: + [tmp ind] = sort(labels.count,1,'descend'); + sel = find(tmp); + for j = 1:length(sel) + found_areas{j,1} = [num2str(labels.count(ind(j))) ': ' labels.name{ind(j)}]; + end + In the "found_areas" variable you can then see how many times which labels are + found. Note that in the AFNI brick one location can have 2 labels. + + Dependent on the input coordinates and the coordinates of the atlas, the + input MRI is transformed betweem MNI and Talairach-Tournoux coordinates + See http://www.mrc-cbu.cam.ac.uk/Imaging/Common/mnispace.shtml for more details. + + See http://www.fieldtriptoolbox.org/template/atlas for a list of templates and + atlasses that are included in the FieldTrip release. + + See also FT_READ_ATLAS, FT_SOURCEPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumelookup.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumenormalise` + +```{text} + FT_VOLUMENORMALISE normalises anatomical and functional volume data + to a template anatomical MRI. + + Use as + [mri] = ft_volumenormalise(cfg, mri) + where the input mri should be a single anatomical volume that was for + example read with FT_READ_MRI. + + The configuration options can be + cfg.parameter = cell-array with the functional data to be normalised (default = 'all') + cfg.keepinside = 'yes' or 'no', keep the inside/outside labeling (default = 'yes') + cfg.downsample = integer number (default = 1, i.e. no downsampling) + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + cfg.spmmethod = 'old', 'new' or 'mars', to switch between the different + spm12 implementations. The methods 'new' or 'mars' + uses SPM tissue probability maps instead of the + template MRI specified in cfg.template. + cfg.opts = structure with normalisation options, see SPM documentation for details + cfg.template = string, filename of the template anatomical MRI (default = 'T1.mnc' + for spm2 or 'T1.nii' for spm8 and for spm12). + cfg.templatecoordsys = the coordinate system of the template when using a template other + than the default + cfg.templatemask = string, filename of a mask for the template + anatomical MRI spcified in cfg.template, e.g. a + brain mask (optional). + cfg.tpm = string, file name of the SPM tissue probablility map to use in + case spmversion is 'spm12' and spmmethod is 'new' or 'mars' + cfg.write = 'yes' or 'no' (default = 'no'), writes the segmented volumes to SPM2 + compatible analyze-file, with the suffix + _anatomy for the anatomical MRI volume + _param for each of the functional volumes + cfg.name = string for output filename + cfg.keepintermediate = 'yes' or 'no' (default = 'no') + cfg.intermediatename = string, prefix of the the coregistered images and of the original + images in the original headcoordinate system + cfg.nonlinear = 'yes' (default) or 'no', estimates a nonlinear transformation + in addition to the linear affine registration. If a reasonably + accurate normalisation is sufficient, a purely linearly transformed + image allows for 'reverse-normalisation', which might come in handy + when for example a region of interest is defined on the normalised + group-average + cfg.spmparams = you can feed in the parameters from a prior normalisation, for example + to apply the parameters determined from an aantomical MRI to an + interpolated source resontruction + cfg.initial = optional hard-coded alignment between target and template, the default is + to use FT_CONVERT_COORDSYS to estimate it based on the data (default = []) + + 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_READ_MRI, FT_VOLUMEDOWNSAMPLE, FT_SOURCEINTERPOLATE, FT_SOURCEPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumenormalise.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumerealign` + +```{text} + FT_VOLUMEREALIGN spatially aligns an anatomical MRI with head coordinates based on + external fiducials or anatomical landmarks. This function typically does not change + the anatomical MRI volume itself, but only adjusts the homogeneous transformation + matrix that describes the mapping from voxels to the coordinate system. It also + appends a coordsys-field to the output data, or it updates it. This field specifies + how the x/y/z-axes of the coordinate system should be interpreted. Occasionally, + the orientation and handedness of the output volume may be different from the orientation + and handedness of the input volume. This is determined by the cfg.flip + argument. See the code for more details. + + For spatial normalisation and deformation (i.e. warping) an MRI to a template brain + you should use the FT_VOLUMENORMALISE function. + + Different methods for aligning the anatomical MRI to a coordinate system are + implemented, which are described in detail below: + + INTERACTIVE - Use a graphical user interface to click on the location of anatomical + landmarks or fiducials. The anatomical data can be displayed as three orthogonal + MRI slices or as a rendering of the head surface. The coordinate system is updated + according to the definition of the coordinates of these fiducials. + + FIDUCIAL - The coordinate system is updated according to the definition of the + coordinates of anatomical landmarks or fiducials that are specified in the + configuration. + + HEADSHAPE - Match the head surface from the MRI with a measured head surface using + an iterative closest point procedure. The MRI will be updated to match the measured + head surface. You can optionally do an initial manual coregistration of the two head + surfaces. + + SPM - Align the individual MRI to the coordinate system of a target or template MRI + by matching the two volumes. + + FSL - Align the individual MRI to the coordinate system of a target or template MRI + by matching the two volumes. + + Use as + [mri] = ft_volumerealign(cfg, mri) + or + [mri] = ft_volumerealign(cfg, mri, target) + where the first input is the configuration structure, the second input is an + anatomical or functional MRI volume and the third (optional) input is the the + target anatomical MRI for SPM or FSL. + + The configuration can contain the following options + cfg.method = string representing the method for aligning + 'interactive' use the GUI to specify the fiducials + 'fiducial' use pre-specified fiducials + 'headshape' match the MRI surface to a headshape + 'spm' match to template anatomical MRI + 'fsl' match to template anatomical MRI + cfg.coordsys = string specifying the origin and the axes of the coordinate + system. Supported coordinate systems are 'ctf', '4d', 'bti', + 'eeglab', 'neuromag', 'itab', 'yokogawa', 'asa', 'acpc', + and 'paxinos'. See http://tinyurl.com/ojkuhqz + cfg.clim = [min max], scaling of the anatomy color (default is automatic) + cfg.parameter = 'anatomy' the parameter which is used for the visualization + cfg.viewresult = string, 'yes' or 'no', whether or not to visualize aligned volume(s) + after realignment (default = 'no') + cfg.flip = string, 'yes' or 'no', to realign the volume approximately to the + input coordinate axes, this may reorient the output volume relative + to the input (default = 'yes', when cfg.method = 'interactive', and 'no' otherwise) + + When cfg.method = 'interactive', a user interface allows for the specification of + the fiducials or landmarks using the mouse, cursor keys and keyboard. The fiducials + can be specified by pressing the corresponding key on the keyboard (n/l/r or + a/p/z). When pressing q the interactive mode will stop and the transformation + matrix is computed. This method supports the following options: + cfg.viewmode = 'ortho' or 'surface', visualize the anatomical MRI as three + slices or visualize the extracted head surface (default = 'ortho') + cfg.snapshot = 'no' ('yes'), making a snapshot of the image once a + fiducial or landmark location is selected. The optional second + output argument to the function will contain the handles to these + figures. + cfg.snapshotfile = 'ft_volumerealign_snapshot' or string, the root of + the filename for the snapshots, including the path. If no path + is given the files are saved to the pwd. The consecutive + figures will be numbered and saved as png-file. + + When cfg.method = 'fiducial' and cfg.coordsys is based on external anatomical + landmarks, as is common for EEG and MEG, the following is required to specify the + voxel indices of the fiducials: + cfg.fiducial.nas = [i j k], position of nasion + cfg.fiducial.lpa = [i j k], position of LPA + cfg.fiducial.rpa = [i j k], position of RPA + cfg.fiducial.zpoint = [i j k], a point on the positive z-axis. This is + an optional 'fiducial', and can be used to determine + whether the input voxel coordinate axes are left-handed + (i.e. flipped in one of the dimensions). If this additional + point is specified, and the voxel coordinate axes are left + handed, the volume is flipped to yield right handed voxel + axes. + + When cfg.method = 'fiducial' and cfg.coordsys = 'acpc', as is common for fMRI, + the following is required to specify the voxel indices of the fiducials: + cfg.fiducial.ac = [i j k], position of anterior commissure + cfg.fiducial.pc = [i j k], position of posterior commissure + cfg.fiducial.xzpoint = [i j k], point on the midsagittal-plane with a + positive Z-coordinate, i.e. an interhemispheric + point above ac and pc + The coordinate system will be according to the RAS_Tal convention, i.e. + the origin corresponds with the anterior commissure the Y-axis is along + the line from the posterior commissure to the anterior commissure the + Z-axis is towards the vertex, in between the hemispheres the X-axis is + orthogonal to the YZ-plane, positive to the right. + + When cfg.method = 'fiducial' and cfg.coordsys = 'paxinos' for a mouse brain, + the following is required to specify the voxel indices of the fiducials: + cfg.fiducial.bregma = [i j k], position of bregma + cfg.fiducial.lambda = [i j k], position of lambda + cfg.fiducial.yzpoint = [i j k], point on the midsagittal-plane + + With the 'interactive' and 'fiducial' methods it is possible to define an + additional point (with the key 'z'), which should be a point on the positive side + of the xy-plane, i.e. with a positive z-coordinate in world coordinates. This point + will subsequently be used to check whether the input coordinate system is left or + right-handed. For the 'interactive' method you can also specify an additional + control point (with the key 'r'), that should be a point with a positive coordinate + on the left-right axis, i.e.', a point on the right of the head. + + When cfg.method = 'headshape', the function extracts the scalp surface from the + anatomical MRI, and aligns this surface with the user-supplied headshape. + Additional options pertaining to this method should be defined in the subcfg + cfg.headshape. The following option is required: + cfg.headshape.headshape = string pointing to a headshape structure or a + file containing headshape, see FT_READ_HEADSHAPE + + Additional options pertaining to the headshape method should be specified in + the sub-structure cfg.headshape and can include: + cfg.headshape.scalpsmooth = scalar, smoothing parameter for the scalp + extraction (default = 2) + cfg.headshape.scalpthreshold = scalar, threshold parameter for the scalp + extraction (default = 0.1) + cfg.headshape.interactive = 'yes' or 'no', use interactive realignment to + align headshape with scalp surface (default = 'yes') + cfg.headshape.icp = 'yes' or 'no', use automatic realignment + based on the icp-algorithm. If both 'interactive' + and 'icp' are executed, the icp step follows the + interactive realignment step (default = 'yes') + + When cfg.method = 'spm', a third input argument is required. The input volume is + coregistered to this target volume, using SPM. You can specify the version of + the SPM toolbox to use with + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + + Additional options pertaining to SPM2 and SPM8 should be defined in the + sub-structure cfg.spm and can include: + cfg.spm.regtype = 'subj', 'rigid' + cfg.spm.smosrc = scalar value + cfg.spm.smoref = scalar value + + Additional options pertaining to SPM12 should be defined in the + sub-structure cfg.spm and can include: + cfg.spm.sep = optimisation sampling steps (mm), default: [4 2] + cfg.spm.params = starting estimates (6 elements), default: [0 0 0 0 0 0] + cfg.spm.cost_fun = cost function string: + 'mi' - Mutual Information (default) + 'nmi' - Normalised Mutual Information + 'ecc' - Entropy Correlation Coefficient + 'ncc' - Normalised Cross Correlation + cfg.spm.tol = tolerences for accuracy of each param, default: [0.02 0.02 0.02 0.001 0.001 0.001] + cfg.spm.fwhm = smoothing to apply to 256x256 joint histogram, default: [7 7] + + When cfg.method is 'fsl', a third input argument is required. The input volume is + coregistered to this target volume, using FSL-flirt. Additional options pertaining + to the FSL method should be defined in the sub-structure cfg.fsl and can include: + cfg.fsl.path = string, specifying the path to fsl + cfg.fsl.costfun = string, specifying the cost-function used for + coregistration + cfg.fsl.interpmethod = string, specifying the interpolation method, can be + 'trilinear', 'nearestneighbour', or 'sinc' + cfg.fsl.dof = scalar, specifying the number of parameters for the + affine transformation. 6 (rigid body), 7 (global + rescale), 9 (traditional) or 12. + cfg.fsl.reslice = string, specifying whether the output image will be + resliced conform the target image (default = 'yes') + + 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_READ_MRI, FT_VOLUMERESLICE, FT_INTERACTIVEREALIGN, FT_ELECTRODEREALIGN, + FT_DETERMINE_COORDSYS, SPM_AFFREG, SPM_NORMALISE, SPM_COREG + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumerealign.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumereslice` + +```{text} + FT_VOLUMERESLICE flips, permutes, interpolates and/or reslices a volume along the + principal axes of the coordinate system according to a specified resolution. + + Use as + mri = ft_volumereslice(cfg, mri) + where the input MRI should be a single anatomical or functional MRI volume that + results from FT_READ_MRI or FT_VOLUMEREALIGN. You can visualize the the input and + output using FT_SOURCEPLOT. + + The configuration structure can contain + cfg.method = string, 'flip', 'nearest', 'linear', 'cubic' or 'spline' (default = 'linear') + cfg.downsample = integer number (default = 1, i.e. no downsampling) + + If you specify the method as 'flip', it will only permute and flip the volume, but + not perform any interpolation. For the other methods the input volumetric data will + also be interpolated on a regular voxel grid. + + For the interpolation methods you should specify + cfg.resolution = number, in units of distance (e.g. mm) + cfg.xrange = [min max], in units of distance (e.g. mm) + cfg.yrange = [min max], in units of distance (e.g. mm) + cfg.zrange = [min max], in units of distance (e.g. mm) + or alternatively with + cfg.dim = [nx ny nz], size of the volume in each direction + + If the input MRI has a coordsys-field and you don't specify explicit the + xrange/yrange/zrange, the centre of the volume will be shifted (with respect to the + origin of the coordinate system), for the brain to fit nicely in the box. + + 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_VOLUMEREALIGN, FT_VOLUMEDOWNSAMPLE, FT_SOURCEINTERPOLATE, FT_SOURCEPLOT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumereslice.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumesegment` + +```{text} + FT_VOLUMESEGMENT segments an anatomical MRI. The behavior depends on the output requested. It can + return probabilistic tissue maps of gray/white/csf compartments, a skull-stripped anatomy, or + binary masks representing the brain surface, skull, or scalp surface. + + Use as + segmented = ft_volumesegment(cfg, mri) + where the input mri should be a single anatomical volume that was for example read with + FT_READ_MRI. For the purpose of creating binary masks of the brain or of the skull, you can also + provide either the anatomical volume or the already segmented volume (with the probabilistic + tissue maps) as input. + + The configuration structure can contain + cfg.output = string or cell-array of strings, see below (default = 'tpm') + cfg.spmversion = string, 'spm2', 'spm8', 'spm12' (default = 'spm12') + cfg.spmmethod = string, 'old', 'new', 'mars', the algorithm used when + cfg.spmversion='spm12' (default = 'old') + cfg.opts = structure with spm-version specific options. See the + code and/or the SPM-documentation for more detail. + cfg.template = filename of the template anatomical MRI (default = + '/spm2/templates/T1.mnc' or '/spm8/templates/T1.nii') + cfg.tpm = cell-array containing the filenames of the tissue probability maps + cfg.name = string for output filename + cfg.write = 'no' or 'yes' (default = 'no'), writes the probabilistic tissue maps + to SPM compatible analyze (spm2), or nifti (spm8 or spm12) files, + with the following suffix for spm2 + _seg1, for the gray matter segmentation + _seg2, for the white matter segmentation + _seg3, for the csf segmentation + or with the following prefix for spm8 and spm12 with spmmethod='old' + c1, for the gray matter segmentation + c2, for the white matter segmentation + c3, for the csf segmentation + and with spm12 with spmmethod='new' there will be 3 additional tissue types + c4, for the bone segmentation + c5, for the soft tissue segmentation + c6, for the air segmentation + When using spm12 with spmmethod='mars', the tpms will be postprocessed + with the mars toolbox, yielding smoother segmentations in general. + cfg.brainsmooth = 'no', or scalar, the FWHM of the gaussian kernel in voxels, (default = 5) + cfg.scalpsmooth = 'no', or scalar, the FWHM of the gaussian kernel in voxels, (default = 5) + cfg.skullsmooth = 'no', or scalar, the FWHM of the gaussian kernel in voxels, (default = 5) + this parameter is only used when the segmentation contains 6 tisuse types, + % including 'bone' + cfg.brainthreshold = 'no', or scalar, relative threshold value which is used to threshold the + tpm in order to create a volumetric brainmask (see below), (default = 0.5) + cfg.scalpthreshold = 'no', or scalar, relative threshold value which is used to threshold the + anatomical data in order to create a volumetric scalpmask (see below), + (default = 0.1) + cfg.skullthreshold = 'no', or scalar, relative threshold value which is used to threshold the + anatomical data in order to create a volumetric scalpmask (see below), + (default = 0.5). this parameter is only used when the segmentation + contains 6 tissue types, including 'bone' + cfg.downsample = integer, amount of downsampling before segmentation (default = 1, which + means no downsampling) + + The desired segmentation output is specified with cfg.output as a string or cell-array of strings + and can contain + 'tpm' - tissue probability map for csf, white and gray matter + 'brain' - binary representation of the brain (the combination of csf, white and gray matter) + 'skull' - binary representation of the skull + 'scalp' - binary representation of the scalp + 'skullstrip' - anatomy with only the brain + + Example use: + cfg = []; + segmented = ft_volumesegment(cfg, mri) will segmented the anatomy and will output the + segmentation result as 3 probabilistic masks in gray, white and csf. + + cfg = []; + cfg.output = 'skullstrip'; + segmented = ft_volumesegment(cfg, mri) will generate a skull-stripped anatomy based on a + brainmask generated from the probabilistic tissue maps. The skull-stripped anatomy + is stored in the field segmented.anatomy. + + cfg = []; + cfg.output = {'brain' 'scalp' 'skull'}; + segmented = ft_volumesegment(cfg, mri) will produce a volume with 3 binary masks, representing + the brain surface, scalp surface, and skull which do not overlap. + + cfg = []; + cfg.output = {'scalp'}; + segmented = ft_volumesegment(cfg, mri) will produce a volume with a binary mask (based on the + anatomy), representing the border of the scalp surface (i.e., everything inside the + surface is also included). Such representation of the scalp is produced faster, + because it doesn't require to create the tissue probabilty maps prior to creating + the mask. + + It is not possible to request tissue-probability maps (tpm) in combination with binary masks + (brain, scalp or skull) or with a skull-stripped anatomy. The output will return only the probabilistic + maps in gray, white and csf. However, when a segmentation with the probabilistic gray, white + and csf representations is available, it is possible to use it as input to create the brain or skull + binary mask. For example: + cfg = []; + cfg.output = {'tpm'}; + segment_tpm = ft_volumesegment(cfg, mri); + cfg.output = {'brain'}; + segment_brain = ft_volumesegment(cfg, segment_tpm); + + For the SPM-based segmentation to work, the coordinate frame of the input MRI needs to be + approximately coregistered to the templates of the probabilistic tissue maps. The templates + are defined in SPM/MNI-space. FieldTrip attempts to do an automatic alignment based on the + coordsys-field in the MRI, and if this is not present, based on the coordsys-field in the cfg. + If none of them is specified the FT_DETERMINE_COORDSYS function is used to interactively + assess the coordinate system in which the MRI is expressed. + + The template MRI is defined in SPM/MNI-coordinates, see also http://bit.ly/2sw7eC4 + x-axis pointing to the right ear + y-axis along the acpc-line + z-axis pointing to the top of the head + origin in the anterior commissure. + Note that the segmentation requires the template MRI to be in SPM coordinates. + + 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_READ_MRI, FT_DETERMINE_COORDSYS, FT_PREPARE_HEADMODEL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumesegment.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_volumewrite` + +```{text} + FT_VOLUMEWRITE exports anatomical or functional volume data to a Analyze + or BrainVoyager file. The data in the resulting file(s) can be + further analyzed and/or visualized in MRIcro, SPM, BrainVoyager, + AFNI or similar packages. + + Use as + ft_volumewrite(cfg, volume) + where the input volume structure should represent an anatomical MRI + that was for example obtained from FT_READ_MRI, the source + reconstruction results from FT_SOURCEANALYSIS, the statistical + results from FT_SOURCESTATISTICS or an otherwise processed anatomical + or functional volume. + + The configuration structure should contain the following elements + cfg.parameter = string, describing the functional data to be processed, + e.g. 'pow', 'coh', 'nai' or 'anatomy' + cfg.filename = filename without the extension + + To determine the file format, the following option can be specified + cfg.filetype = 'analyze_old', 'nifti' (default), 'nifti_img', 'analyze_spm', + 'nifti_spm', 'nifti_gz', 'mgz', 'mgh', 'vmp' or 'vmr' + + Depending on the filetype, the cfg should also contain + cfg.vmpversion = 1 or 2, version of the vmp format to use (default = 2) + cfg.spmversion = string, version of SPM to be used (default = 'spm12') + + The default filetype is 'nifti', which means that a single *.nii file will be + written using code from the freesurfer toolbox. The 'nifti_img' filetype uses SPM + for a dual file (*.img/*.hdr) nifti-format file. The 'nifti_spm' filetype uses SPM + for a single 'nifti' file. + + The analyze, analyze_spm, nifti, nifti_img, nifti_spm and mgz filetypes support a + homogeneous transformation matrix, the other filetypes do not support a homogeneous + transformation matrix and hence will be written in their native coordinate system. + + You can specify the datatype for the nifti, analyze_spm and analyze_old + formats. If not specified, the class of the input data will be preserved, + if the file format allows. Although the higher level function may make an + attempt to typecast the data, only the nifti fileformat preserves the + datatype. Also, only when filetype = 'nifti', the slope and intercept + parameters are stored in the file, so that, when reading the data from + file, the original values are restored (up to the bit resolution). + cfg.datatype = 'uint8', 'int8', 'int16', 'int32', 'single' or 'double' + + By default, integer datatypes will be scaled to the maximum value of the + physical or statistical parameter, floating point datatypes will not be + scaled. This can be modified, for instance if the data contains only integers with + indices into a parcellation, by + cfg.scaling = 'yes' or 'no' + + Optional configuration items are + cfg.downsample = integer number (default = 1, i.e. no downsampling) + cfg.fiducial.nas = [x y z] position of nasion + cfg.fiducial.lpa = [x y z] position of LPA + cfg.fiducial.rpa = [x y z] position of RPA + cfg.markfiducial = 'yes' or 'no', mark the fiducials + cfg.markorigin = 'yes' or 'no', mark the origin + cfg.markcorner = 'yes' or 'no', mark the first corner of the volume + + To facilitate data-handling and distributed computing you can use + cfg.inputfile = ... + If you specify this option the input data will be read from a *.mat + file on disk. This mat files should contain only a single variable named 'data', + corresponding to the input structure. + + See also FT_SOURCEANALYSIS, FT_SOURCESTATISTICS, FT_SOURCEINTERPOLATE, FT_WRITE_MRI + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_volumewrite.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_warning` + +```{text} + FT_WARNING prints a warning message on screen, depending on the verbosity + settings of the calling high-level FieldTrip function. This function works + similar to the standard WARNING function, but also features the "once" mode. + + Use as + ft_warning(...) + with arguments similar to fprintf, or + ft_warning(msgId, ...) + with arguments similar to warning. + + You can switch of all warning messages using + ft_warning off + or for specific ones using + ft_warning off msgId + + To switch them back on, you would use + ft_warning on + or for specific ones using + ft_warning on msgId + + Warning messages are only printed once per timeout period using + ft_warning timeout 60 + ft_warning once + or for specific ones using + ft_warning once msgId + + You can see the most recent messages and identifier using + ft_warning last + + You can query the current on/off/once state for all messages using + ft_warning query + + See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_warning.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_warp_apply` + +```{text} + FT_WARP_APPLY performs a 3D linear or nonlinear transformation on the input + coordinates, similar to those in AIR. You can find technical documentation + on warping in general at http://air.bmap.ucla.edu/AIR5 + + Use as + [output] = ft_warp_apply(M, input, method, tol) + where + M vector or matrix with warping parameters + input Nx3 matrix with input coordinates + output Nx3 matrix with the transformed or warped output coordinates + method string describing the transformation or warping method + tol (optional) value determining the numerical precision of the + output, to deal with numerical round-off imprecisions due to + the warping + + The methods 'nonlin0', 'nonlin2' ... 'nonlin5' specify a polynomial transformation. + The size of the transformation matrix depends on the order of the warp + zeroth order : 1 parameter per coordinate (translation) + first order : 4 parameters per coordinate (total 12, affine) + second order : 10 parameters per coordinate + third order : 20 parameters per coordinate + fourth order : 35 parameters per coordinate + fifth order : 56 parameters per coordinate (total 168) + The size of M should be 3xP, where P is the number of parameters per coordinate. + Alternatively, you can specify the method to be 'nonlinear', in which case the + order will be determined from the size of the matrix M. + + If the method 'homogeneous' is selected, the input matrix M should be a 4x4 + homogenous transformation matrix. + + If the method 'sn2individual' or 'individual2sn' is selected, the input M should be + a structure with the nonlinear spatial normalisation (warping) parameters created + by SPM8 or SPM12 for alignment between an individual subject and a template brain. + When using the 'old' method, M will have subfields like this: + Affine: [4x4 double] + Tr: [4-D double] + VF: [1x1 struct] + VG: [1x1 struct] + flags: [1x1 struct] + When using the 'new' or the 'mars' method, M will have subfields like this: + + If any other method is selected, it is assumed that it specifies the name of an + auxiliary function that will, when given the input parameter vector M, return an + 4x4 homogenous transformation matrix. Supplied functions are 'translate', 'rotate', + 'scale', 'rigidbody', 'globalrescale', 'traditional', 'affine', 'perspective', + 'quaternion'. + + See also FT_AFFINECOORDINATES, FT_HEADCOORDINATES, FT_WARP_OPTIM, FT_WARP_ERROR, + MAKETFORM, AFFINE2D, AFFINE3D + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_warp_apply.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_warp_error` + +```{text} + FT_WARP_ERROR computes the mean distance after linear or non-linear warping + and can be used as the goalfunction in a 3D warping minimalisation + + Use as + dist = ft_warp_error(M, input, target, 'method') + + It returns the mean Euclidean distance (i.e. the residual) for an interactive + optimalization to transform the input towards the target using the + transformation M with the specified warping method. + + See also FT_WARP_OPTIM, FT_WARP_APPLY + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_warp_error.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_warp_optim` + +```{text} + FT_WARP_OPTIM determine intermediate positions using warping (deformation) + the input cloud of points is warped to match the target. + The strategy is to start with simpelest linear warp, followed by a more + elaborate linear warp, which then is followed by the nonlinear warps up + to the desired order. + + [result, M] = ft_warp_pnt(input, target, method) + input contains the Nx3 measured 3D positions + target contains the Nx3 template 3D positions + method should be any of + 'rigidbody' + 'globalrescale' + 'traditional' (default) + 'nonlin1' + 'nonlin2' + 'nonlin3' + 'nonlin4' + 'nonlin5' + + The default warping method is a traditional linear warp with individual + rescaling in each dimension. Optionally you can select a nonlinear warp + of the 1st (affine) up to the 5th order. + + When available, this function will use the MATLAB optimization toolbox. + + See also FT_WARP_APPLY, FT_WARP_ERRROR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/ft_warp_optim.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_wizard` + +```{text} + FT_WIZARD is a graphical user interface to evaluate a FieldTrip analysis + script one step at a time, allowing you to go to the next step if you are + content with the data so far, or to the previous step if you want to repeat it + with different configuration settings. + + Use as + ft_wizard scriptname + or + ft_wizard('scriptname') + + Use the functional form of FT_WIZARD, such as FT_WIZARD('scriptname'), when + the name of the script is stored in a string, when an output argument is + requested, or if the name of the script contains spaces. If you do not + specify an output argument, the results will be stored as variables in + the main MATLAB workspace. + + Besides the buttons, you can use the following key combinations + Ctrl-O load a new script from a file + Ctrl-S save the script to a new file + Ctrl-E open the current script in editor + Ctrl-P go to previous step + Ctrl-N go to next step + Ctrl-Q quit, do not save the variables + Ctrl-X exit, save the variables to the workspace + + See also FT_ANALYSISPROTOCOL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/ft_wizard.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_cifti` + +```{text} + FT_WRITE_CIFTI writes functional data or functional connectivity to a cifti-2 + file. The geometrical description of the brainordinates can consist of + triangulated surfaces or voxels in a regular 3-D volumetric grid. The functional + data can consist of a dense or a parcellated representation. Furthermore, it + writes the geometrical description of the surfaces to one or multiple gifti + files. + + Use as + ft_write_cifti(filename, data, ...) + where the filename is a string and the data according to the description below. + + If the input data describes a dense representation of functional data, the data + structure should conform to the FT_DATATYPE_SOURCE or FT_DATATYPE_VOLUME + definition. + + If the input data describes a parcellated representation of functional data, the + data structure should conform to the FT_DATATYPE_TIMELOCK or FT_DATATYPE_FREQ + definition. In addition, the description of the geometry should be specified in + the data.brainordinate field, which should conform to the FT_DATATYPE_SOURCE or + FT_DATATYPE_VOLUME definition. + + Any optional input arguments should come in key-value pairs and may include + 'parameter' = string, fieldname that contains the functional data + 'brainstructure' = string, fieldname that describes the brain structures (default = 'brainstructure') + 'parcellation' = string, fieldname that describes the parcellation (default = 'parcellation') + 'precision' = string, can be 'single', 'double', 'int32', etc. (default ='single') + 'writesurface' = boolean, can be false or true (default = true) + 'debug' = boolean, write a debug.xml file (default = false) + + The brainstructure refers to the global anatomical structure, such as CortexLeft, Thalamus, etc. + The parcellation refers to the the detailled parcellation, such as BA1, BA2, BA3, etc. + + See also FT_READ_CIFTI, FT_READ_MRI, FT_WRITE_MRI + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_cifti.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_data` + +```{text} + FT_WRITE_DATA exports electrophysiological data such as EEG to a file. + + Use as + ft_write_data(filename, dat, ...) + + The specified filename can contain the filename extension. If it has no filename + extension not, it will be added automatically. + + Additional options should be specified in key-value pairs and can be + 'header' = header structure that describes the data, see FT_READ_HEADER + 'event' = event structure that corresponds to the data, see FT_READ_EVENT + 'chanindx' = 1xN array, for selecting a subset of channels from header and data + 'dataformat' = string, see below + 'append' = boolean, not supported for all formats + + The supported dataformats for writing are + edf + gdf + anywave_ades + brainvision_eeg + neuralynx_ncs + neuralynx_sdma + plexon_nex + fcdc_matbin + fcdc_mysql + fcdc_buffer + flac, m4a, mp4, oga, ogg, wav (audio formats) + matlab + homer_nirs + snirf + + For EEG data, the input data is assumed to be scaled in microvolt. + For NIRS data, the input data is assumed to represent optical densities. + + See also FT_READ_HEADER, FT_READ_DATA, FT_READ_EVENT, FT_WRITE_EVENT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_event` + +```{text} + FT_WRITE_EVENT writes an event structure to a file, a message daemon listening on a + network socked, or to another computer connected through the serial port. Note that + this function is mostly for real-time streaming of events. For most data files on + disk the writing of events is done simultaneously with the header and data in + FT_WRITE_DATA. + + Use as + ft_write_event(filename, event, ...) + + The first argument is a string containing the filename. The second argument is a + structure with the event. Multiple events can be represented as a structure array. + Events are represented in the same format as those returned by FT_READ_EVENT. + event.type = string + event.sample = expressed in samples, the first sample of a recording is 1 + event.value = number or string + event.offset = expressed in samples + event.duration = expressed in samples + event.timestamp = expressed in timestamp units, which vary over systems (optional) + + Additional options should be specified in key-value pairs and can be + 'eventformat' = string, see below + 'append' = boolean, not supported for all formats + + Events can be written to special communication streams by specifying the target as + URI instead of a filename. Supported are + buffer://: + fifo:// + tcp://: + udp://: + mysql://:@: + rfb://@: + serial:?key1=value1&key2=value2&... + rfb://@: + + See also FT_READ_HEADER, FT_READ_DATA, FT_READ_EVENT, FT_WRITE_DATA + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_event.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_headshape` + +```{text} + FT_WRITE_HEADSHAPE writes a head surface, cortical sheet or geometrical descrition + of the volume conduction model or source model to a file for further processing in + external software. + + Use as + ft_write_headshape(filename, mesh, ...) + or + ft_write_headshape(filename, pos, ...) + where the input mesh is a structure containing the vertices and triangles (mesh.pos + and mesh.tri), or where the input pos is a Nx3 matrix that describes the surface + vertices. + + Required input arguments should be specified as key-value pairs and should include + 'format' = string, see below + + Optional input arguments should be specified as key-value pairs and can include + 'data' = data vector or matrix, the size along the 1st dimension should correspond to the number of vertices + 'unit' = string, desired geometrical units for the data, for example 'mm' + 'coordsys' = string, desired coordinate system for the data + 'jmeshopt' = cell-array with {'name', 'value'} pairs, options for writing JSON/JMesh files + + Supported output formats are + 'freesurfer' Freesurfer surf-file format, using write_surf from FreeSurfer + 'gifti' see https://www.nitrc.org/projects/gifti/ + 'gmsh_ascii' see https://gmsh.info + 'gmsh_binary' see https://gmsh.info + 'mne_pos' MNE source grid in ascii format, described as 3D points + 'mne_tri' MNE surface desciption in ascii format + 'neurojson_bmesh' NeuroJSON binary JSON-based format + 'neurojson_jmesh' NeuroJSON ascii JSON-based format + 'off' see http://www.geomview.org/docs/html/OFF.html + 'ply' Stanford Polygon file format, for use with Paraview or Meshlab + 'stl' STereoLithography file format, for use with CAD and generic 3D mesh editing programs + 'tetgen' see https://wias-berlin.de/software/tetgen/ + 'vista' see http://www.cs.ubc.ca/nest/lci/vista/vista.html + 'vtk' Visualization ToolKit file format, for use with Paraview + + See also FT_READ_HEADSHAPE, FT_WRITE_DATA, FT_WRITE_MRI, FT_WRITE_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_headshape.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_json` + +```{text} + FT_WRITE_JSON writes a MATLAB structure to a JSON file. Compared to the builtin + MATLAB function, this implementation deals a bit different with missing values, + booleans, and NaNs, and results in a more human-readable file. + + Use as + ft_write_json(filename, struct) + + See also FT_READ_JSON, JSONDECODE, JSONENCODE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_json.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_mri` + +```{text} + FT_WRITE_MRI exports volumetric data such as anatomical and functional MRI + to a file. + + Use as + ft_write_mri(filename, dat, ...) + where the input argument dat represents the 3D array with the values. + + The 3-D array with the values can be further described with + 'transform' = 4x4 homogenous transformation matrix, specifying the transformation from voxel coordinates to head or world coordinates + 'unit' = string, desired geometrical units for the data, for example 'mm' + 'coordsys' = string, desired coordinate system for the data + + Additional options should be specified in key-value pairs and can be + 'dataformat' = string, see below + 'spmversion' = string, version of SPM to be used (default = 'spm12') + 'scl_slope' = slope parameter for nifti files + 'scl_inter' = intersect parameter for nifti files + 'vmpversion' = 1 or 2, version of the vmp format to use (default = 2) + + The specified filename can already contain the filename extention. If not present, + it will be added automatically. + + The supported dataformats are + 'analyze' outdated format and not recommended + 'mgz' FreeSurfer specific format + 'mgh' FreeSurfer specific format + 'nifti' uses FreeSurfer code + 'nifti2' uses FreeSurfer code + 'nifti_gz' uses FreeSurfer code + 'nifti_spm' uses SPM + 'seg3d_mat' MATLAB file for Seg3D with a scirunnrrd structure + 'vista' SIMBIO specific format + 'vmr' Brainvoyager specific format + 'vmp' Brainvoyager specific format + 'vtk' Visualization ToolKit file format, for use with Paraview + + See also FT_READ_MRI, FT_DATATYPE_VOLUME, FT_WRITE_DATA, FT_WRITE_HEADSHAPE, FT_WRITE_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_mri.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_sens` + +```{text} + FT_WRITE_SENS writes electrode information to an external file for further processing in external software. + + Use as + ft_write_sens(filename, sens, ...) + + The specified filename can already contain the filename extention, + but that is not required since it will be added automatically. + + Additional options should be specified in key-value pairs and can be + 'format' string, see below + + The supported file formats are + bioimage_mgrid + besa_sfp + polhemus_pos + matlab + + See also FT_READ_SENS, FT_DATATYPE_SENS, FT_WRITE_DATA, FT_WRITE_MRI, FT_WRITE_SENS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_sens.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_spike` + +```{text} + FT_WRITE_SPIKE writes animal electrophysiology spike timestamps and/or waveforms + to file + + Use as + ft_write_spike(filename, spike, ...) + + Additional options should be specified in key-value pairs and can be + 'dataformat' string, see below + 'fsample' sampling frequency of the waveforms + 'chanindx' index of selected channels + 'TimeStampPerSample' number of timestamps per sample + + The supported dataformats are + neuralynx_nse + neuralynx_nts + plexon_nex + matlab + + See also FT_READ_SPIKE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_spike.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ft_write_tsv` + +```{text} + FT_WRITE_TSV writes a MATLAB table to a tab-separated-values file. Compared to the + builtin MATLAB function, this implementation deals a bit different with missing + values, booleans, and NaNs. + + Use as + ft_write_tsv(filename, table) + + See also FT_READ_TSV, FT_READ_JSON, FT_WRITE_JSON, READTABLE, WRITETABLE, TBLWRITE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/fileio/ft_write_tsv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `gen_finger` + +```{text} + Generate finger movement data + FORMAT [yy,P,M,U] = gen_finger(sim) + + sim Simulation data structure: + + .Nt number of trials + .m first or 2nd order PIF + .init 'partial': initial phase diff + restricted to small range + 'full': initial phase diff + uniform in 0 to 2 pi + .noise_dev STD of additive noise + .do_plot plot data (1) + + yy yy{n} for nth trial data + P model parameters + M model structure + U input structure + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/man/example_scripts/gen_finger.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `gencode` + +```{text} + GENCODE Generate code to recreate any MATLAB struct/cell variable. + For any MATLAB variable, this function generates a .m file that + can be run to recreate it. Classes can implement their class specific + equivalent of gencode with the same calling syntax. By default, classes + are treated similar to struct variables. + + [str, tag, cind] = gencode(item, tag, tagctx) + Input arguments: + item - MATLAB variable to generate code for (the variable itself, not its + name) + tag - optional: name of the variable, i.e. what will be displayed left + of the '=' sign. This can also be a valid struct/cell array + reference, like 'x(2).y'. If not provided, inputname(1) will be + used. + tagctx - optional: variable names not to be used (e.g. keywords, + reserved variables). A cell array of strings. + Output arguments: + str - cellstr containing code lines to reproduce the input variable + tag - name of the generated variable (equal to input tag) + cind - index into str to the line where the variable assignment is coded + (usually 1st line for non-object variables) + + See also GENCODE_RVALUE, GENCODE_SUBSTRUCT, GENCODE_SUBSTRUCTCODE. + + This code has been developed as part of a batch job configuration + system for MATLAB. See + http://sourceforge.net/projects/matlabbatch + for details about the original project. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/gencode.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `gencode_rvalue` + +```{text} + GENCODE_RVALUE Code for right hand side of MATLAB assignment + Generate the right hand side for a valid MATLAB variable + assignment. This function is a helper to GENCODE, but can be used on + its own to generate code for the following types of variables: + * scalar, 1D or 2D numeric, logical or char arrays + * scalar or 1D cell arrays, where each item can be one of the supported + array types (i.e. nested cells are allowed) + + function [str, sts] = gencode_rvalue(item, cflag) + Input argument: + item - value to generate code for + cflag - (optional) if true, try to generate 1-line code also for 2D + arrays. This may reduce readability of the generated code. + Defaults to false. + Output arguments: + str - cellstr with generated code, line per line + sts - true, if successful, false if code could not be generated + + See also GENCODE, GENCODE_SUBSTRUCT, GENCODE_SUBSTRUCTCODE. + + This code has been developed as part of a batch job configuration + system for MATLAB. See + http://sourceforge.net/projects/matlabbatch + for details about the original project. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/gencode_rvalue.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `gencode_substruct` + +```{text} + GENCODE_SUBSTRUCT String representation of subscript structure. + Generate MATLAB code equivalent to subscript structure subs. See help + on SUBSTRUCT, SUBSASGN and SUBSREF for details how subscript structures + are used. + + str = gencode_substruct(subs, name) + Input arguments: + subs - a subscript structure + name - optional: name of variable to be dereferenced + Output arguments: + str - a one-line cellstr containing a string representation of the + subscript structure + If name is given, it is prepended to the string. + For '()' and '{}' also pseudo subscripts are allowed: if subs.subs{...} + is a string, it will be printed literally, even if it is not equal to + ':'. This way, it is possible create code snippets that contain + e.g. references to a loop variable by name. + + See also GENCODE, GENCODE_RVALUE, GENCODE_SUBSTRUCTCODE. + + This code has been developed as part of a batch job configuration + system for MATLAB. See + http://sourceforge.net/projects/matlabbatch + for details about the original project. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/gencode_substruct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `gencode_substructcode` + +```{text} + GENCODE_SUBSTRUCTCODE Create code for a subscript structure + Generate MATLAB code (using SUBSTRUCT) to create subscript structure + subs. See help on SUBSTRUCT, SUBSASGN and SUBSREF for details how + subscript structures are used. + + str = gencode_substructcode(subs, name) + Input arguments: + subs - a subscript structure + name - optional: name of variable + Output arguments: + str - a one-line cellstr containing a call to SUBSTRUCT that returns + an substruct equivalent to subs. + If name is supplied as input argument, the generated code will assign + the output of SUBSTRUCT to the variable 'name'. + then only the rhs of the expression will be returned. + For '()' and '{}' also pseudo subscripts are allowed: if subs.subs{...} + is a string, it will be printed literally, even if it is not equal to + ':'. This way, one can create code snippets that contain e.g. references + to a loop variable by name. + + See also GENCODE, GENCODE_RVALUE, GENCODE_SUBSTRUCT. + + This code has been developed as part of a batch job configuration + system for MATLAB. See + http://sourceforge.net/projects/matlabbatch + for details about the original project. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/gencode_substructcode.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `getCTFdata` + +```{text} + getCTFdata.m Reads specified trials from .meg4 files in CTF-format data set. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/ctf/getCTFdata.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `getpid` + +```{text} + GETPID returns the process identifier (PID) of the current Matlab + process. + + Use as + num = getpid; + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/getpid.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `getsubfield` + +```{text} + GETSUBFIELD returns a field from a structure just like the standard + GETFIELD function, except that you can also specify nested fields + using a '.' in the fieldname. The nesting can be arbitrary deep. + + Use as + f = getsubfield(s, 'fieldname') + or as + f = getsubfield(s, 'fieldname.subfieldname') + + See also GETFIELD, ISSUBFIELD, SETSUBFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/getsubfield.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `glm_phi` + +```{text} + Estimate connectivity parameters using GLM/EMA method + FORMAT [A,fint] = glm_phi(phi,dt,fb) + + phi - [N x Nr] matrix of phase time series + - (N time points, Nr regions) + dt - sample period + fb - bandwidth parameter + + A - [Nr x Nr] normalised connectivities + fint - [Nr x 1] intrinsic frequencies + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/man/example_scripts/glm_phi.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `hanning` + +```{text} + HANNING Hanning window. + HANNING(N) returns the N-point symmetric Hanning window in a column + vector. Note that the first and last zero-weighted window samples + are not included. + + HANNING(N,'symmetric') returns the same result as HANNING(N). + + HANNING(N,'periodic') returns the N-point periodic Hanning window, + and includes the first zero-weighted window sample. + + NOTE: Use the HANN function to get a Hanning window which has the + first and last zero-weighted samples. + + See also BARTLETT, BLACKMAN, BOXCAR, CHEBWIN, HAMMING, HANN, KAISER + and TRIANG. + + This is a drop-in replacement to bypass the signal processing toolbox + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/signal/hanning.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `hasyokogawa` + +```{text} + HASYOKOGAWA tests whether the data input toolbox for MEG systems by + Yokogawa (www.yokogawa.com, designed by KIT/EagleTechnology) is + installed. Only the newest version of the toolbox is accepted. + + Use as + string = hasyokogawa; + which returns a string describing the toolbox version, e.g. "12bitBeta3", + "16bitBeta3", or "16bitBeta6" for preliminary versions, or '1.5' for the + official Yokogawa MEG Reader Toolbox. An empty string is returned if the toolbox + is not installed. The string "unknown" is returned if it is installed but + the version is unknown. + + Alternatively you can use it as + [boolean] = hasyokogawa(desired); + where desired is a string with the desired version. + + See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_DATA, READ_YOKOGAWA_EVENT, + YOKOGAWA2GRAD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/hasyokogawa.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `help2cell` + +```{text} + HELP2CELL - translate help texts into cell arrays + cellhelp = help2cell(topic) + Create a cell array of help strings from the MATLAB help on 'topic'. + If a line ends with a ' ', it is assumed to be continued and the next + line will be appended, thus creating one cell per paragraph. + + This code is part of a batch job configuration system for MATLAB. See + help matlabbatch + for a general overview. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/help2cell.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `hgsave_pre2008a` + +```{text} + HGSAVE_PRE2008A + Starting with MATLAB 2008a, GUIDE saves figures with '%automatic' + functions (e.g. Callbacks, ResizeFcn ...) as anonymous function handles, + where previous versions used strings instead. The problem is that MATLAB + R14SP3 crashes on loading these anonymous function handles. + + The problem can be resolved in 2 ways: + a) replacing anonymous function handles with string callbacks or + b) generating code with anonymous function handles which must be run in + MATLAB R14SP3 to save a valid .fig or .mat file. + + function outfile = hgsave_pre2008a(figname,doreplace) + Input arguments: + figname - string containing full path and file of .fig/.mat file to + repair + doreplace - how to treat function handles + true - try to replace function handles with strings. Useful + if one needs to be compatible, but has no R14SP3 at + hand. + false - create .m file that must be run in MATLAB R14SP3 to + save a compatible .mat file. + Output argument: + outfile - file name of output file. Depending on doreplace, this is + either a .fig/.mat file, or a .m file. + + Details of the correction procedure: + 1) load a MATLAB 2008a .fig or .mat file as variable + 2) generate code for it using GENCODE + if doreplace + 3) look for the characteristic regexp + @\(hObject,eventdata\)figname\(([^,]*).* + 4) if found, replace it with string + figname($1,gcbo,[],guidata(gcbo)) + if success + 5) re-evaluate the code + 6) save the new variable + else + generate semi-correct code + end + else + generate code without replacements + end + + If there are other anonymous function handles left, the tool will create + an m-file with instructions which function handles may need to be + corrected. After editing, this m-file can be run to save the corrected + figure. + + See also GENCODE, GENCODE_RVALUE, GENCODE_SUBSTRUCT, GENCODE_SUBSTRUCTCODE. + + This code has been developed as part of a batch job configuration + system for MATLAB. See + http://sourceforge.net/projects/matlabbatch + for details about the original project. + _______________________________________________________________________ + Copyright (C) 2007 Freiburg Brain Imaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/matlabbatch/hgsave_pre2008a.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `hilbert` + +```{text} + Computes analytic signal + FORMAT [x] = hilbert(xr) + + Returns analytic signal x = xr + i*xi such that + xi is the Hilbert transform of real vector xr. + __________________________________________________________________________ + Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/signal/hilbert.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `homer2fieldtrip` + +```{text} + HOMER2FIELDTRIP converts a continuous raw data structure from Homer to FieldTrip + format. + + Use as + data = homer2fieldtrip(filename) + where the input is a file name, or + data = homer2fieldtrip(nirs) + where the input nirs structure is according to the Homer format and the output data + structure is formatted according to the output of FT_PREPROCESSING. + + See https://www.nitrc.org/plugins/mwiki/index.php/homer2:Homer_Input_Files#NIRS_data_file_format + for a description of the Homer data structure. + + See also FIELDTRIP2HOMER, FT_PREPROCESSING, FT_DATATYPE_RAW + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/homer2fieldtrip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `imotions2fieldtrip` + +```{text} + IMOTIONS2FIELDTRIP imports an iMotions *.txt file and represents it as a FieldTrip + raw data structure. + + Use as + data = imotions2fieldtrip(filename, ...) + + Additional options should be specified in key-value pairs and can be + interpolate = 'no', 'time' or 'data' (default = 'no') + isnumeric = cell-array with labels corresponding to numeric data (default = {}) + isinteger = cell-array with labels corresponding to integer data that should be interpolated with nearest where applicable (default = {}) + isnotnumeric = cell-array with labels not corresponding to numeric data (default = {}) + isevent = cell-array with labels corresponding to events (default = {}) + isnotevent = cell-array with labels not corresponding to events (default = {}) + + The options 'isnumeric' and 'isnotnumeric' are mutually exclusive. Idem for + 'isevent' and 'isnotevent'. + + When using the interpolate='data' option, both the data and the time are interpolated + to a regularly sampled representation, when using the interpolate='time' option, only + the time axis is interpolated to a regularly sampled representation. This addresses + the case that the data was actually acquired with a regular sampling rate, but the time + stamps in the file are not correctly representing this (a known bug with some type of + iMotions data). + + See also FT_DATATYPE_RAW, FT_PREPROCESSING, FT_HEARTRATE, FT_ELECTRODERMALACTIVITY + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/imotions2fieldtrip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `inv2x2` + +```{text} + INV2X2 computes inverse of matrix x, using explicit analytic definition + if size(x,1) < 4, otherwise use MATLAB inv-function + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/inv2x2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `inv3x3` + +```{text} + INV3X3 computes inverse of matrix x, using explicit analytic definition + if size(x) = [3 3 K M] + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/inv3x3.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `issubfield` + +```{text} + ISSUBFIELD tests for the presence of a field in a structure just like the standard + Matlab ISFIELD function, except that you can also specify nested fields + using a '.' in the fieldname. The nesting can be arbitrary deep. + + Use as + f = issubfield(s, 'fieldname') + or as + f = issubfield(s, 'fieldname.subfieldname') + + This function returns true if the field is present and false if the field + is not present. + + See also ISFIELD, GETSUBFIELD, SETSUBFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/issubfield.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `istrue` + +```{text} + ISTRUE converts an input argument like "yes/no", "true/false" or "on/off" into a + boolean. If the input is boolean, then it will remain like that. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/istrue.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `keepfields` + +```{text} + KEEPFIELDS makes a selection of the fields in a structure + + Use as + s = keepfields(s, fields); + + See also REMOVEFIELDS, COPYFIELDS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/keepfields.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `keyval` + +```{text} + KEYVAL returns the value that corresponds to the requested key in a + key-value pair list of variable input arguments + + Use as + [val] = keyval(key, varargin) + + See also VARARGIN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/keyval.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `keyvalcheck` + +```{text} + KEYVALCHECK is a helper function for parsing optional key-value input pairs. + + Use as + keyvalcheck(argin, 'required', {'key1', 'key2', ...}) + keyvalcheck(argin, 'forbidden', {'key1', 'key2', ...}) + keyvalcheck(argin, 'optional', {'key1', 'key2', ...}) + + See also KEYVAL + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/keyvalcheck.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `lbessi` + +```{text} + GPU single precision f = log(besseli(nu, z)) + FORMAT f = lbessi(nu,z) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Spatial/lbessi.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `lmoutr` + +```{text} + LMOUTR computes the la/mu parameters of a point projected to a triangle + + Use as + [la, mu, dist] = lmoutr(v1, v2, v3, r) + where v1, v2 and v3 are three vertices of the triangle, and r is + the point that is projected onto the plane spanned by the vertices + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/lmoutr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `loadxml` + +```{text} + LOADXML Load workspace variables from disk (XML file). + LOADXML FILENAME retrieves all variables from a file given a full + pathname or a MATLABPATH relative partial pathname (see PARTIALPATH). + If FILENAME has no extension LOAD looks for FILENAME and FILENAME.xml + and treats it as an XML file. + + LOAD, by itself, uses the XML file named 'matlab.xml'. It is an error + if 'matlab.xml' is not found. + + LOAD FILENAME X loads only X. + LOAD FILENAME X Y Z ... loads just the specified variables. The + wildcard '*' loads variables that match a pattern. + Requested variables from FILENAME are created in the workspace. + + S = LOAD(...) returns the contents of FILENAME in variable S. S is + a struct containing fields matching the variables retrieved. + + Use the functional form of LOAD, such as LOAD('filename'), when the + file name is stored in a string, when an output argument is requested, + or if FILENAME contains spaces. + + See also LOAD, XML2MAT, XMLTREE. + + + [Matlab code]( https://github.com/spm/spm/blob/main/compat/loadxml.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `loreta2fieldtrip` + +```{text} + LORETA2FIELDTRIP reads and converts a LORETA source reconstruction into a + FieldTrip data structure, which subsequently can be used for statistical + analysis or other analysis methods implemented in Fieldtrip. + + Use as + [source] = loreta2fieldtrip(filename, ...) + where optional arguments can be passed as key-value pairs. + + filename can be the binary file from LORETA or a LORETA file exported as + a text file (using the format converter in LORETA-KEY). + + The following optional arguments are supported + 'timeframe' = integer number, which timepoint to read (default is to read all) + + See also EEGLAB2FIELDTRIP, SPM2FIELDTRIP, NUTMEG2FIELDTRIP, SPASS2FIELDTRIP + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/loreta2fieldtrip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ltrisect` + +```{text} + LTRISECT intersects a line with a plane spanned by three vertices + + Use as + [sect] = ltrisect(v1, v2, v3, l1, l2) + where v1, v2 and v3 are three vertices spanning the plane, and l1 and l2 + are two points on the line + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/ltrisect.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `markdown2matlab` + +```{text} + MARKDOWN2MATLAB converts a Markdown file to a MATLAB script or function. All text + is converted to comments, headings are converted to comment lines starting with %% + sections with code are properly formatted, and words that appear in bold, italic or + monospace are converted. + + Use as + markdown2matlab(infile, outfile) + + If no outfile is specified, it will write it to a .m file with the same name as + the infile. In case the file exists, it will be written with a numeric suffix. + + The best is to provide the full filepath, otherwise it will look for the file within + the current path. + + Optional input arguments can be specified as key-value pairs and can include + ... + + See also MATLAB2MARKDOWN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/markdown2matlab.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `match_str` + +```{text} + MATCH_STR looks for matching labels in two lists of strings + and returns the indices into both the 1st and 2nd list of the matches. + They will be ordered according to the first input argument. + + Use as + [sel1, sel2] = match_str(strlist1, strlist2) + + The strings can be stored as a char matrix or as an vertical array of + cells, the matching is done for each row. + + When including a 1 as the third input argument, the output lists of + indices will be expanded to the size of the largest input argument. + Entries that occur only in one of the two inputs will correspond to a 0 + in the output, in this case. This can be convenient in rare cases if the + size of the input lists is meaningful. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/match_str.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `match_val` + +```{text} + MATCH_VAL looks for matching values in two arrays of values + and returns the indices into both the 1st and 2nd list of the matches. + They will be ordered according to the first input argument. + + Use as + [sel1, sel2] = match_str(vallist1, vallist2) + + See also MATCH_STR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/match_val.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `matlab2markdown` + +```{text} + MATLAB2MARKDOWN converts a MATLAB script or function to Markdown format. All + comments are converted to text, comment lines starting with %% are converted to + headings, sections with code are properly formatted, and words that appear in bold, + italic or monospace are converted. + + Use as + matlab2markdown(infile, outfile, ...) + + If no outfile is specified, it will write it to a .md file with the same name as + the infile. In case the file exists, it will be written with a numeric suffix. + + The best is to provide the full filepath, otherwise it will look for the file within + the current path. + + Optional input arguments can be specified as key-value pairs and can include + imagestyle = 'none|inline|jekyll' + pageheader = 'none|jekyll' + overwrite = true/false, allow overwriting of the .md file (default = false) + highlight = string, 'matlab', 'plaintext' or '' (default = '') + ... + + See also MARKDOWN2MATLAB + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/matlab2markdown.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_approach_deriv` + +```{text} + Gradient of log-likelihood for approach model + FORMAT [dLdp,iCpY,L] = mci_approach_deriv (P,M,U,Y) + + dLdp gradient of log joint + iCpY curvature (Fisher Information) + L log joint + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/approach/mci_approach_deriv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_approach_gen` + +```{text} + Approach to limit model + FORMAT [y] = mci_approach_gen (P,M,U) + + P parameters + M,U as usual + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/approach/mci_approach_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_approach_like` + +```{text} + Log-likelihood for approach model + FORMAT [L,yhat,st] = mci_approach_like (P,M,U,Y) + + P parameters + M,U,Y as usual + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/approach/mci_approach_like.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_approach_struct` + +```{text} + Approach model structure + FORMAT [M,U] = mci_approach_struct (Nobs) + + Nobs Number of observations + M Model structure + U Input structure + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/approach/mci_approach_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_compare_forward` + +```{text} + Compare integration methods + FORMAT [els_sun,els_ode,els_spm] = mci_compare_forward (model) + + model 'phase', 'nmm-r2p2' + + Run integration 9 times - compare speed and accuracy + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/demo-gradients/mci_compare_forward.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_compare_gradients` + +```{text} + Compare methods for gradient computation + FORMAT [els,names] = mci_compare_gradients (model,cost,methods) + + model 'phase', 'nmm-r2p2' + cost 'loglike', 'spm_mci_joint' (default) + methods vector of integers indicating which methods to + compare eg. [1,2,3,4,5] (default) for 1. SensMat, + 2. SensSun, 3. AdjMat, 4. AdjSun, 5. FD + + els Computation times + names Names of compared methods + + Note: 4. AdjSun may not work for nmm2-r2p2. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/demo-gradients/mci_compare_gradients.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_compare_jacobians` + +```{text} + Compare user supplied and finite difference methods + FORMAT [Fx,Fp,FxFD,FpFD] = mci_compare_jacobians (model) + + model 'phase' + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/demo-gradients/mci_compare_jacobians.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_compare_setup` + +```{text} + Set up data structures for fwd/sens/grad comparisons + FORMAT [P,M,U,Y,ind] = mci_compare_setup (model) + + model 'phase', 'nmm-r2p2' + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/gradients/mci_compare_setup.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_discount_act` + +```{text} + Activation of discounting model + FORMAT [a,v1,v2,k] = mci_discount_act (P,M,U) + + P parameters + M model structure + U contains rewards and times + + a activation for discount model + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/discount/mci_discount_act.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_discount_deriv` + +```{text} + Gradient of likelihood for discounting model + FORMAT [dLdp,iCpY,L] = mci_discount_deriv (P,M,U,Y) + + P parameters + M model structure + U contains rewards and times + Y data + + dLdp gradient of log joint + iCpY curvature (Fisher Information) + L log joint + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/discount/mci_discount_deriv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_discount_gen` + +```{text} + Output of discounting model + FORMAT [g,y] = mci_discount_gen (P,M,U) + + P parameters + M model structure + U U.X contains design matrix + + g probability of taking option 1 + y binary decisions based on g + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/discount/mci_discount_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_discount_like` + +```{text} + Compute log likelihood of discount model + FORMAT [L,E,st] = mci_discount_like (P,M,U,Y) + + P parameters + M model + U inputs + Y data + + L Log likelihood + E Errors + st Status flag (0 for OK, -1 for problem) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/discount/mci_discount_like.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_discount_struct` + +```{text} + Set up data structures for discounting model + FORMAT [M,U] = mci_discount_struct (Nobs) + + Nobs number of data points + + M model structure + U U.X is the design matrix + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/discount/mci_discount_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_exp_init` + +```{text} + Exponentially interpolate to t=0 + FORMAT [w0,a] = mci_exp_init (Y,M,doplot) + + Y Cell of data from multiple subjects + Y{n}.y, Y{n}.ind for n=1..N + M Model structure + doplot plot fits + + w0 [d x N] matrix of initial states + where d is number of states + a [d x N] matrix of exponential coefficients + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_exp_init.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_interp_init` + +```{text} + Linear interpolate to t=0 + FORMAT [w0] = mci_interp_init (Y,M) + + Y Cell of data from multiple subjects + Y{n}.y, Y{n}.ind for n=1..N + M Model structure + + w0 [d x N] matrix of initial states + where d is number of states + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_interp_init.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_dfdx` + +```{text} + Jacobian for linear system, dx/dt=Ax, with constrained connectivity + FORMAT [A,Pt] = mci_lds_dfdx (x,u,P,M) + + x State vector + u input + P parameters (vectorised) + M model structure + + A f=Ax + Pt Parameters (transformed from latent pars) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_dfdx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_fx` + +```{text} + Flow for linear system, dx/dt=Ax, with constrained connectivity + FORMAT [f,A,Pt] = mci_lds_fx (x,u,P,M) + + x State vector + u input + P parameters (vectorised) + M model structure + + f Flow, dx/dt + A f=Ax + Pt Parameters (transformed from latent pars) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_fx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_gen` + +```{text} + LDS constrained: generate data + FORMAT [Y] = mci_lds_gen (M,U,P) + + M Model structure + U Inputs + P Parameters + + Y Data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_group_data` + +```{text} + Generate LDS data for a group of subjects + FORMAT [pinit,pflow,names,M,U,Y] = mci_lds_group_data (lds) + + lds Data structure with fields: + + .R R.pE, R.pC prior over initial conds + .sd Standard deviation of observation noise + .Nsub Number of subjects + .Nobs Number of observations per subject + .model 'lds_real','forward',etc. + .flow_par 'fixed' or 'random' + .init_par 'fixed' or 'random' + + pinit Initial params + pflow Flow params + names names of parameters + M Cell of models + U Cell of inputs + Y Cell of data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_group_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_gx` + +```{text} + Observation function for LDS + FORMAT [y,L] = mci_lds_gx (x,u,P,M) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_gx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_lat2par` + +```{text} + Convert latent params to params + FORMAT [Pt,a,b] = mci_lds_lat2par (P,M) + + P Parameters (latent) + M model structure + + Pt Parameters (transformed) + a diagonal values + b off-diagonal values + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_lat2par.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_par2lat` + +```{text} + Convert parmas to latent params + FORMAT [P] = mci_lds_par2lat (Pt,M) + + Pt params + M model struct + + P params (latent) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_par2lat.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_params` + +```{text} + LDS constrained: sample params from prior + FORMAT [P] = mci_lds_params (M,U) + + M Model structure + U Inputs + + P Parameters + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_params.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_plot_params` + +```{text} + Plot results of group LDS estimation + FORMAT [rmse] = mci_lds_plot_results (MCI,lds) + + MCI MCI-MFX data structure + lds true model data structure with fields: + + .pinit true init params + .pflow true flow params + + rmse root mean square errors + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_plot_params.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_lds_struct` + +```{text} + LDS constrained: Initialise model structure + FORMAT [M,U,names] = mci_lds_struct (M) + + M.d Number of regions + M.sd Observation noise SD + M.name 'uncoupled','forward','backward','bidirectional' + M.R Initial state + M.t Vector of Times + M.drop final value as proportion of initial value + eg. 0.5 indicates typical state at M.t(end) is + half of M.t(1). Used to set M.a_typical, typical + self connection values + + M Model structure + U Inputs + names Names of variables + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/lds/mci_lds_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linear_deriv` + +```{text} + Gradient of likelihood for linear regression + FORMAT [dLdp,iCpY,L] = mci_linear_deriv (P,M,U,Y) + + P parameters + M model + U inputs + Y data + + dLdp gradient of log joint + iCpY curvature (Fisher Information) + L log joint + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linear/mci_linear_deriv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linear_gen` + +```{text} + Output of linear model + FORMAT [y] = mci_linear_gen (theta,M,U) + + theta regression coefficients + M model structure + U U.X contains design matrix + + y outputs + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linear/mci_linear_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linear_like` + +```{text} + Compute log likelihood of linear model + FORMAT [L,E,st] = mci_linear_like (theta,M,U,Y) + + theta regression coefficients + M model + U inputs + Y data + + L Log likelihood + E Errors + st Status flag (0 for OK, -1 for problem) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linear/mci_linear_like.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linear_post` + +```{text} + Analytic posterior for linear regression + FORMAT [Ep,Cp,L] = mci_linear_post (M,U,Y) + + M Model Structure + U Inputs + Y Data + + Ep Posterior mean + Cp Posterior covariance + L Log evidence + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linear/mci_linear_post.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linear_struct` + +```{text} + Set up data structures for linear model + FORMAT [M,U,Xfull] = mci_linear_struct (Nobs,lambda,des) + + Nobs number of data points + lambda noise precision + des type of design + + M model structure + U U.X is the design matrix + Xfull Design matrix for data points [1:T] + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linear/mci_linear_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linsqr_deriv` + +```{text} + Gradient of likelihood for linear regression + FORMAT [dLdp,iCpY,L] = mci_linsqr_deriv (P,M,U,Y) + + P parameters + M model + U inputs + Y data + + dLdp gradient of log joint + iCpY curvature (Fisher Information) + L log joint + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linsqr/mci_linsqr_deriv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linsqr_gen` + +```{text} + Output of linear model with squared params + FORMAT [y] = mci_linsqr_gen (theta,M,U) + + theta regression coefficients + M model structure + U U.X contains design matrix + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linsqr/mci_linsqr_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linsqr_like` + +```{text} + Compute log likelihood of linear model + FORMAT [L,E,st] = mci_linsqr_like (theta,M,U,Y) + + theta regression coefficients + M model + U inputs + Y data + + L Log likelihood + E Errors + st Status flag (0 for OK, -1 for problem) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linsqr/mci_linsqr_like.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_linsqr_struct` + +```{text} + Set up data structures for linsqr model + FORMAT [M,U,Xfull] = mci_linsqr_struct (Nobs,lambda,des) + + Nobs number of data points + lambda noise precision + des type of design + + M model structure + U U.X is the design matrix + Xfull Design matrix for data points [1:T] + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/linsqr/mci_linsqr_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_logistic_act` + +```{text} + Activations of logistic model + FORMAT [a] = mci_logistic_act (P,M,U) + + P parameters + M model structure + U contains rewards and times + + a activations of logistic model + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/logistic/mci_logistic_act.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_logistic_deriv` + +```{text} + Gradient of likelihood for logistic model + FORMAT [dLdp,iCpY,L] = mci_logistic_deriv (P,M,U,Y) + + P parameters + M model + U inputs + Y data + + dLdp gradient of log joint + iCpY curvature (Fisher Information) + L log joint + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/logistic/mci_logistic_deriv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_logistic_gen` + +```{text} + Output of logistic regression model + FORMAT [g,y] = mci_logistic_gen (P,M,U) + + P parameters + M model structure + U U.X contains design matrix + + g probabilities of y=1 + y binary decisions based on g + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/logistic/mci_logistic_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_logistic_like` + +```{text} + Compute log likelihood of logistic model + FORMAT [L,E,st] = mci_logistic_like (P,M,U,Y) + + P parameters + M model + U inputs + Y data + + L Log likelihood + E Errors + st Status flag (0 for OK, -1 for problem) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/logistic/mci_logistic_like.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_logistic_struct` + +```{text} + Set up data structures for logistic model + FORMAT [M,U,Y] = mci_logistic_struct (log_data,T) + + log_data 'pima','ripley' or 'dct' + T for 'dct' we can specify number of samples + + M model structure + U U.X is the design matrix (independent variables) + Y dependent variable + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/logistic/mci_logistic_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_fx_delay` + +```{text} + State equations for a neural mass model of erps with first order delays + FORMAT [f] = mci_nmm_fx_delay (x,u,P,M) + + x - state vector + x(:,1) - voltage (spiny stellate cells) + x(:,2) - voltage (pyramidal cells) +ve + x(:,3) - voltage (pyramidal cells) -ve + x(:,4) - current (spiny stellate cells) depolarizing + x(:,5) - current (pyramidal cells) depolarizing + x(:,6) - current (pyramidal cells) hyperpolarizing + x(:,7) - voltage (inhibitory interneurons) + x(:,8) - current (inhibitory interneurons) depolarizing + x(:,9) - voltage (pyramidal cells) + + f - dx(t)/dt = f(x(t)) + + Prior fixed parameter scaling [Defaults] + + M.pF.E = [32 16 4]; % extrinsic rates (forward, backward, lateral) + M.pF.H = [1 4/5 1/4 1/4]*128; % intrinsic rates (g1, g2 g3, g4) + M.pF.D = [2 16]; % propogation delays (intrinsic, extrinsic) + M.pF.G = [4 32]; % receptor densities (excitatory, inhibitory) + M.pF.T = [8 16]; % synaptic constants (excitatory, inhibitory) + M.pF.R = [1 1/2]; % parameter of static nonlinearity + + __________________________________________________________________________ + David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and + neuronal dynamics. NeuroImage 20: 1743-1755 + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_fx_delay.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_gen` + +```{text} + Generate data from two region NMM + FORMAT [Y] = mci_nmm_gen (M,U,P) + + M Model structure + U Inputs + P Parameters + + Y Data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_params` + +```{text} + Generate parameters for two region NMM + FORMAT [P] = mci_nmm_params (M,U) + + M Model structure + U Inputs + + P Parameters + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_params.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_r2_gx` + +```{text} + Observation function for 2-region NMM + FORMAT [y,L] = mci_nmm_r2_gx (x,u,P,M) + + P Parameters + M Model structure + U Inputs + + y Output + L Lead field (dy/dx) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_r2_gx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_r2p2_dfdp` + +```{text} + Parameter Jacobian for two region, two parameter NMM + FORMAT [F] = mci_nmm_r2p2_dfdp (x,u,P,M) + + x State + u Inputs + P Parameters + M Model structure + + F F(i,j) = df(x)_i/dp_j + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_r2p2_dfdp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_r2p2_dfdx` + +```{text} + State Jacobian for two region, two parameter NMM + FORMAT [F] = mci_nmm_r2p2_dfdp (x,u,P,M) + + x State + u Inputs + P Parameters + M Model structure + + F F(i,j) = df(x)_i/dtheta_j + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_r2p2_dfdx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_r2p2_fx` + +```{text} + Flow for two region, two parameter NMM + FORMAT [f] = mci_nmm_r2p2_fx (x,u,P,M) + + x State + u Inputs + P Parameters + M Model structure + + f Flow, dx/dt + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_r2p2_fx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_r2p6_fx` + +```{text} + Flow for two region, six parameter NMM + FORMAT [f] = mci_nmm_r2p6_fx (x,u,P,M) + + x State + u Inputs + P Parameters + M Model structure + + f Flow, dx/dt + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_r2p6_fx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_nmm_struct` + +```{text} + Set up two region NMM + FORMAT [M,U] = mci_nmm_struct (back,sd,Np) + + back 1 to include backward connection (default) + sd Observation noise SD (default 0.01) + Np number of params (2,6 or 21) + + M Model structure + U Inputs + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/nmm/mci_nmm_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_pb_deriv` + +```{text} + Gradient of log-likelihood for Preece-Baines model + FORMAT [dLdp,iCpY,L] = mci_pb_deriv (P,M,U,Y) + + dLdp gradient of log joint + iCpY curvature (Fisher Information) + L log joint + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/growth/mci_pb_deriv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_pb_gen` + +```{text} + Preece-Baines growth model + FORMAT [y] = mci_pb_gen (P,M,U) + + P parameters + M model + U inputs + + y time series + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/growth/mci_pb_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_pb_like` + +```{text} + Log-likelihood for Preece-Baines model + FORMAT [L,yhat,st] = mci_pb_like (P,M,U,Y) + + P parameters + M,U,Y as usual + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/growth/mci_pb_like.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_pb_struct` + +```{text} + Preece-Baines model structure + FORMAT [M,U] = mci_pb_struct (Nobs) + + Nobs Number of observations + + M Model structure + U Input structure + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/growth/mci_pb_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_phase_dfdp` + +```{text} + Parameter sensitivity for phase model + FORMAT [dfdp] = mci_phase_dfdp (x,u,P,M) + + x State vector + u inputs + P parameter vector + M model structure + + dfdp Jacobian wrt. parameters, df/dp + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_phase_dfdp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_phase_dfdx` + +```{text} + State sensitivity for phase model + FORMAT [dfdx] = mci_phase_dfdx (x,u,P,M) + + x state vector + M model structure + P parameter vector + + dfdx Jacobian wrt states + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_phase_dfdx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_phase_fx` + +```{text} + Flow function for phase model + FORMAT [f] = mci_phase_fx (x,u,P,M) + + x state vector + u inputs + P parameter vector + M model structure + + f dx/dt + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_phase_fx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_phase_gx` + +```{text} + Observation function for phase model + FORMAT [y,L] = mci_phase_gx (x,u,P,M) + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_phase_gx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_phase_init` + +```{text} + Initialise weakly coupled oscillator model + FORMAT [P,M,U,Y] = mci_phase_init (d) + + d number of oscillators + + P parameters (drawn from prior) + M model structure + U inputs + Y data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_phase_init.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_plot_surface` + +```{text} + Plot log probability surface + FORMAT [log_prob,S,E] = mci_plot_surface (P,M,U,Y,S,dist) + + P Parameters + M Model structure + U Inputs + Y Data + S Surface data structure + dist 'prior', 'like' or 'post' + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/plotting/mci_plot_surface.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_ramsay_fx` + +```{text} + State equation for Ramsay model + FORMAT [F] = mci_ramsay_fx (x,U,P,M) + + x State vector + x(1) Voltage variable + x(2) Recovery variable + U inputs + P vector of model parameters - 2 params only + M model + + F dx/dt + + J Ramsay et al (2007) Parameter estimation for differential equations: + a generalised smoothing approach. J Roy Stat Soc B, 69(5):741-796. + + See also section 10 (page 26) and contribution by W.Penny on page 75 of: + + Girolami and Calderhead (2011) Riemann manifold Langevin and Hamiltonian + Monte Carlo methods. J Roy Stat Soc B,73(2):123-214. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/ramsay/mci_ramsay_fx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_ramsay_gen` + +```{text} + Generate data from Ramsay model + FORMAT [Y] = mci_ramsay_gen (P,M,U) + + P Parameters + M Model structure + U Inputs + + Y Data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/ramsay/mci_ramsay_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_ramsay_gx` + +```{text} + Observation equation for Ramsay model + FORMAT [y,L] = spm_ramsay_gx (x,u,P,M) + + x,u,P,M state,input,params,model + + y observations + L dy/dx + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/ramsay/mci_ramsay_gx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_ramsay_struct` + +```{text} + Data structures for Ramsay model + FORMAT [M,U] = mci_ramsay_struct (sigme_e) + + sigma_e Noise SD + + M,U model, input data structures + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/ramsay/mci_ramsay_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_rphase_dfdp` + +```{text} + Parameter sensitivity for phase model + FORMAT [dfdp] = mci_rphase_dfdp (x,u,P,M) + + x State vector + u inputs + P parameter vector + M model structure + + dfdp Jacobian wrt. parameters, df/dp + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_rphase_dfdp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_rphase_dfdx` + +```{text} + State sensitivity for phase model (reduced connectivity) + FORMAT [dfdx] = mci_rphase_dfdx (x,u,P,M) + + x state vector + M model structure + P parameter vector + + dfdx Jacobian wrt states + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_rphase_dfdx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_rphase_fx` + +```{text} + Flow function for phase model + FORMAT [f] = mci_rphase_fx (x,u,P,M) + + x state vector + u inputs + P parameter vector + M model structure + + f dx/dt + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_rphase_fx.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_rphase_gen` + +```{text} + Generate data from reduced WCO model + FORMAT [Y] = mci_rphase_gen (P,M,U) + + P parameters + M model structure + U inputs + + Y data + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_rphase_gen.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mci_rphase_struct` + +```{text} + Initialise weakly coupled oscillator model - reduced connectivity + FORMAT [M,U] = mci_rphase_init (d,conn) + + d number of oscillators + + M model structure + U inputs + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/mci/models/phase/mci_rphase_struct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `meg_leadfield1` + +```{text} + MEG_LEADFIELD1 magnetic leadfield for a dipole in a homogenous sphere + + [lf] = meg_leadfield1(R, pos, ori) + + with input arguments + R position dipole + pos position magnetometers + ori orientation magnetometers + + The center of the homogenous sphere is in the origin, the field + of the dipole is not dependent on the sphere radius. + + This function is also implemented as MEX file. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/meg_leadfield1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `memtic` + +```{text} + MEMTIC start a MATLAB memory recorder + + MEMTIC and MEMTOC functions work together to measure memory usage. + MEMTIC, by itself, saves the current memory footprint that MEMTOC + uses later to measure the memory that was used between the two. + + Use as + MEMTIC + MEMTOC + to print the estimated memory use on screen, or + MEMTIC + M = MEMTOC + to return the estimated memory (in bytes) in variable M, or + C = MEMTIC + M = MEMTOC(C) + to specifically estimate the memory use between a well-defined tic/toc pair. + + Note that MATLAB uses internal memory allocation, garbage collection, shallow + copies of variables, and virtual memory. Due to the advanced handling of + memory for its variables, it is not easy and in certain cases not possible to + make a reliable and reproducible estimate based on the memory information + provided by the operating system. + + Example: measure the memory increase due to allocating a lot of memory. + Doing a "clear x" following the allocation and prior to MEMTOC does not + affect the memory that is reported. + + memtic + n = 125; x = cell(1,n); + for i=1:n + x{i} = randn(1000,1000); % 8kB per item + disp(i); + end + whos x + memtoc + + See also TIC, TOC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/memtic.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `memtoc` + +```{text} + MEMTOC return the memory that was used + + MEMTIC and MEMTOC functions work together to measure memory usage. + MEMTIC, by itself, saves the current memory footprint that MEMTOC + uses later to measure the memory that was used between the two. + + Use as + MEMTIC + MEMTOC + to print the estimated memory use on screen, or + MEMTIC + M = MEMTOC + to return the estimated memory (in bytes) in variable M, or + C = MEMTIC + M = MEMTOC(C) + to specifically estimate the memory use between a well-defined tic/toc pair. + + Note that MATLAB uses internal memory allocation, garbage collection, shallow + copies of variables, and virtual memory. Due to the advanced handling of + memory for its variables, it is not easy and in certain cases not possible to + make a reliable and reproducible estimate based on the memory information + provided by the operating system. + + Example: measure the memory increase due to allocating a lot of memory. + Doing a "clear x" following the allocation and prior to MEMTOC does not + affect the memory that is reported. + + memtic + n = 125; x = cell(1,n); + for i=1:n + x{i} = randn(1000,1000); % 8kB per item + disp(i); + end + whos x + memtoc + + See also TIC, TOC + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/memtoc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_add_coil_defs` + +```{text} + [res] = mne_add_coil_defs(chs,accuracy,coil_def_templates) + + Add transformed coil definitions to the channel info + + chs - original channel definitions + accuracy - desired accuracy (0, 1, or 2, defaults to 1) + templates - coil definition templates + (defaults to $MNE_ROOT/setup/mne/coil_def.dat or $MNE_ROOT/share/mne/coil_def.dat) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_add_coil_defs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_babyMEG_dig_trig` + +```{text} + function mne_baby_meg_dig_trig(infile,outfile,threshold,invert,want_eeg); + + Read and write raw data in 60-sec blocks + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_babyMEG_dig_trig.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_block_diag` + +```{text} + function bd = mne_block_diag(A,n) + + Make or extract a sparse block diagonal matrix + + If A is not sparse, then returns a sparse block diagonal "bd", diagonalized from the + elements in "A". + "A" is ma x na, comprising bdn=(na/"n") blocks of submatrices. + Each submatrix is ma x "n", and these submatrices are + placed down the diagonal of the matrix. + + If A is already sparse, then the operation is reversed, yielding a block + row matrix, where each set of n columns corresponds to a block element + from the block diagonal. + + Routine uses NO for-loops for speed considerations. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_block_diag.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_combine_xyz` + +```{text} + function [comb] = mne_combine_xyz(vec) + + Compute the three Cartesian components of a vector together + + + vec - Input row or column vector [ x1 y1 z1 ... x_n y_n z_n ] + comb - Output vector [x1^2+y1^2+z1^2 ... x_n^2+y_n^2+z_n^2 ] + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_combine_xyz.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_compensate_to` + +```{text} + [newdata] = mne_compensate_to(data,to) + + Apply compensation to the data as desired + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_compensate_to.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_average_epochs` + +```{text} + An example of averaging over epochs + + function mne_ex_average_epochs(dataname,origname,outname) + + dataname - Name of a epoch data. The description file will + be _desc.mat and the epoch file .epochs + origname - Name of the file from which the epochs were extracted. + outname - Name of the output file (optional) + + Returns an evoked data structure identical to the ones + returned from fiff_read_evoked + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_average_epochs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_cancel_noise` + +```{text} + Do projection and compensation as needed + Return the appropriate operators + + [res,proj,comp] = mne_ex_cancel_noise(data,dest_comp) + + res - Data after noise cancellation + proj - The projection operator applied + comp - The compensator which brings uncompensated data to the + desired compensation grade (will be useful in forward + calculations) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_cancel_noise.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_compute_inverse` + +```{text} + [res] = mne_ex_compute_inverse(fname_data,setno,fname_inv,nave,lambda2,dSPM,sLORETA) + + An example on how to compute a L2-norm inverse solution + Actual code using these principles might be different because + the inverse operator is often reused across data sets. + + + fname_data - Name of the data file + setno - Data set number + fname_inv - Inverse operator file name + nave - Number of averages (scales the noise covariance) + If negative, the number of averages in the data will be + used + lambda2 - The regularization factor + dSPM - do dSPM? + sLORETA - do sLORETA? + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_compute_inverse.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_data_sets` + +```{text} + Find all evoked response data from a given file + + [res] = mne_ex_data_sets(fname) + + fname - Name of the file to look at + res - Structure containing the result + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_data_sets.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_evoked_grad_amp` + +```{text} + function [res] = mne_ex_evoked_grad_amp(inname,bmin,bmax,outname) + + Compute the magnitude of the tangential gradient at each + sensor location using the planar gradiometer data and + optionally output the result to a fif file. + + inname The input file name. All average data sets are + read and processed + bmin,bmax Baseline limits in seconds + outname Optional output file name + + + Function returns the data which was or would have been written + to the file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_evoked_grad_amp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_read_epochs` + +```{text} + Example of reading raw data + + [ data, times, ch_names ] = mne_ex_read_epochs(fname,event,eventname,tmin,tmax) + + Input : + + fname - The name of the input file + event - The event + eventname - Name of the event file + tmin - Starting time in seconds + tmax - Ending time in seconds + + Output : + + data - Array of structures corresponding to the epochs with fields: + + epoch the epoch, channel by channel + event event # + tmin starting time in the raw data file (initial skip omitted) + tmax ending stime in the raw data file (initial skip omitted) + + times - The time points of the samples, in seconds + ch_names - Names of the channels included + + + NOTE 1: The purpose of this function is to demonstrate the raw data reading + routines. You may need to modify this for your purposes + + NOTE 2: You need to run mne_process_raw once as + + mne_process_raw --raw mne_ex_read_epochs --projoff + + to create the fif-format event file (or open the file in mne_browse_raw). + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_read_epochs.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_read_evoked` + +```{text} + Load one evoked-response data set and do various kinds + of preprocessing + + [res] = mne_ex_read_evoked(fname,setno,apply_proj,dest_comp,use_ctf_head) + + fname - Name of the data file + setno - Data set number (default = 1) + apply_proj - Apply SSP to the data (default = true) + dest_comp - Desired (CTF/4D) compensation in the output data (default = keep the one in the file) + use_ctf_head - Use the CTF/4D head coordinate system instead of the + Neuromag one if available + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_read_evoked.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_read_raw` + +```{text} + Example of reading raw data + + [ data, times ] = mne_ex_read_raw(fname,from,to,in_samples,dest_comp); + + data - The data read, compensated and projected, channel by + channel + times - The time points of the samples, in seconds + + + fname - The name of the input file + from - Starting time or sample + to - Ending time or sample + in_samples - Are from and to given in samples rather than in seconds + (optional) + dest_comp - Desired (CTF) compensation in the output data (optional) + + NOTE: The purpose of this function is to demonstrate the raw data reading + routines. In real world, you probably make multiple calls to + fiff_read_raw_segment_times or fiff_read_raw_segment + between open and close + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_read_raw.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_read_write_raw` + +```{text} + function mne_ex_read_write_raw(infile,outfile); + + Read and write raw data in 60-sec blocks + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_read_write_raw.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_ex_rt` + +```{text} + An example of a mne_rt_server real-time connection + + function mne_ex_rt(mne_rt_server_ip, mne_rt_server_commandPort ,mne_rt_server_fiffDataPort) + + mne_rt_server_ip - IP of the running mne_rt_server + mne_rt_server_commandPort - Command port of the mne_rt_server + mne_rt_server_fiffDataPort - Fiff data port of the mne_rt_server + + Returns the measurement info + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_ex_rt.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_file_name` + +```{text} + [name] = mne_file_name(dir,name) + + Compose a file name under MNE_ROOT + + dir - Name of the directory containing the file name + name - Name of the file under that directory + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_file_name.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_find_channel` + +```{text} + [which] = mne_find_channel(info,name) + + Find a channel by name employing the info structure + output by mne_raw2mat or mne_epochs2mat + + epoch - The data structure containing the channel information + name - name of the channel to look for + + Returns index of the channel in the data + If the channel is not found, returns -1 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_find_channel.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_find_events` + +```{text} + [eventlist] = mne_find_events(fname, stim_channel, consecutive, output) + + Find event from raw file + + fname - string; .fiff raw data file name + stim_channel - int; the channel that record event + consecutive - bool | 'increasing' + If True, consider instances where the value of the events + channel changes without first returning to zero as multiple + events. If False, report only instances where the value of the + events channel changes from/to zero. If 'increasing', report + adjacent events only when the second event code is greater than + the first. + output - 'onset' | 'offset' | 'step' + Whether to report when events start, when events end, or both. + + eventlist - size = (n_events, 3) + The first column contains the event time in samples and the third + column contains the event id. If output = 'onset' or 'step', the + second column contains the value of the stim channel immediately + before the event/step. For output = 'offset', the second column + contains the value of the stim channel after the event offset. + + Authors: Fu-Te Wong (zuxfoucault@gmail.com), + Chien-Chung Chen / Visual Neuroscience Lab, National Taiwan University + Version 1.0 2017/9/17 + License: BSD (3-clause) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_find_events.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_find_source_space_hemi` + +```{text} + function mne_find_source_space_hemi(src) + + Return the hemisphere id for a source space + + src - The source space to investigate + hemi - Deduced hemisphere id + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_find_source_space_hemi.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_fread3` + +```{text} + [retval] = mne_fread3(fid) + read a 3 byte integer out of a file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_fread3.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_fwrite3` + +```{text} + mne_fwrite(fid, val) + write a 3 byte integer to a file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_fwrite3.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_get_current_comp` + +```{text} + [comp] = mne_get_current_comp(info) + + Get the current compensation in effect in the data + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_get_current_comp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_label_time_courses` + +```{text} + function [ values, times ] = mne_label_time_courses(labelfile,stcfile) + + Extract the time courses corresponding to a label file from an stc file + + labelfile - The name of the label file + stcfile - The name of the stc file (must be on the same subject and + hemisphere as the stc file + + values - The time courses + times - The time points + vertices - The vertices corresponding to the time points + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_label_time_courses.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_license` + +```{text} + MNE_LICENSE prints the license only once upon the first call to + this function. If the user does a "clear all", the license will + again be shown. This function should be included in every openmeeg + function to ensure that the license is displayed at least once. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_license.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_load_coil_def` + +```{text} + [CoilDef,Header] = mne_load_coil_def(fname); + CoilDef = mne_load_coil_def(fname); + + If file name is not specified, the standard coil definition file + $MNE_ROOT/setup/mne/coil_def.dat or $MNE_ROOT/share/mne/coil_def.dat is read + + The content of the coil definition file is described in + section 5.6 of the MNE manual + + This routine is modified from the original BrainStorm routine + created by John C. Mosher + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_load_coil_def.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_make_combined_event_file` + +```{text} + mne_make_combined_event_file(rawname,eventname,include,all,threshold) + + rawname Name of the raw data file to scan + eventname Name of the text format event file to output + include Stimulus channel names to combine + + This defaults to STI 001...STI 006 + + all If true, include all trigger line transitions in the file + instead of the leading edges only + threshold Threshold for detection of transition between inactive and active states + + Create both a fif and eve format event file combining STI 001...STI 006 + This function facilitates processing of Neuromag 122 data which do not + contain a composite trigger channel + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_make_combined_event_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_make_compensator` + +```{text} + [comp] = mne_make_compensator(info,from,to,exclude_comp_chs) + + info - measurement info as returned by the fif reading routines + from - compensation in the input data + to - desired compensation in the output + exclude_comp_chs - exclude compensation channels from the output (optional) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_make_compensator.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_make_projector` + +```{text} + [proj,nproj,U] = mne_make_projector(projs,ch_names,bads) + + proj - The projection operator to apply to the data + nproj - How many items in the projector + U - The orthogonal basis of the projection vectors (optional) + + Make an SSP operator + + projs - A set of projection vectors + ch_names - A cell array of channel names + bads - Bad channels to exclude + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_make_projector.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_make_projector_info` + +```{text} + [proj,nproj] = mne_make_projector_info(info) + + Make an SSP operator using the meas info + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_make_projector_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_mesh_edges` + +```{text} + MESH_EDGES Returns sparse matrix with edges number + + SYNTAX + [EDGES] = MESH_EDGES(FACES) + + faces : matrix of size [n_trianges, 3] + edges : sparse matrix of size [n_vertices, n_vertices] + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_mesh_edges.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_morph_data` + +```{text} + MNE_MORPH_DATA Returns data morphed to a new subject. + + SYNTAX + [STCS] = MNE_MORPH_DATA(FROM, TO, STCS, GRADE) + + from : name of origin subject + to : name of destination subject + stcs : stc data to morph + grade : (optional) resolution of the icosahedral mesh (typically 5) + + Note : The functions requires to set MNE_ROOT and SUBJECTS_DIR variables. + + Example: + from = 'sample'; + to = 'fsaverage'; + stcs_morph = mne_morph_data(from,to,stcs,5); + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_morph_data.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_omit_first_line` + +```{text} + [rest] = mne_omit_first_line(str) + + Omit the first line in a multi-line string (useful for handling + error messages) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_omit_first_line.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_patch_info` + +```{text} + [pinfo] = mne_patch_info(nearest) + + Generate the patch information from the 'nearest' vector in a source space + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_patch_info.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_pick_channels_cov` + +```{text} + [cov] = mne_pick_channels_cov(orig,include,exclude) + + Pick desired channels from a covariance matrix + + orig - The original covariance matrix + include - Channels to include (if empty, include all available) + exclude - Channels to exclude (if empty, do not exclude any) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_pick_channels_cov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_pick_channels_forward` + +```{text} + [fwd] = mne_pick_channels_forward(orig,include,exclude) + + Pick desired channels from a forward solution + + orig - The original forward solution + include - Channels to include (if empty, include all available) + exclude - Channels to exclude (if empty, do not exclude any) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_pick_channels_forward.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_prepare_inverse_operator` + +```{text} + [inv] = mne_prepare_inverse_operator(orig,nave,lambda2,dSPM,sLORETA) + + Prepare for actually computing the inverse + + orig - The inverse operator structure read from a file + nave - Number of averages (scales the noise covariance) + lambda2 - The regularization factor + dSPM - Compute the noise-normalization factors for dSPM? + sLORETA - Compute the noise-normalization factors for sLORETA? + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_prepare_inverse_operator.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_bem_surfaces` + +```{text} + [surf] = mne_read_bem_surfaces(source,add_geom,tree) + + Reads source spaces from a fif file + + source - The name of the file or an open file id + add_geom - Add geometry information to the surfaces + tree - Required if source is an open file id, search for the + BEM surfaces here + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_bem_surfaces.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_cov` + +```{text} + [cov] = mne_read_cov(fid,node,kind) + + Reads a covariance matrix from a fiff file + + fid - an open file descriptor + node - look for the matrix in here + cov_kind - what kind of a covariance matrix do we want? + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_cov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_curvature` + +```{text} + [curf] = mne_read_surface(fname) + + Reads a FreeSurfer curvature file + + fname - The file to read + curv - The curvature values + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_curvature.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_epoch` + +```{text} + [data,fid] = mne_read_epoch(epoch_info,which,prev_fid) + + Reads an epoch from a binary file produced by mne_epochs2mat + + epoch_info - The data structure read from the epoch data description file + which - Which epoch to read + prev_fid - Open file id from previous call + if prev_fid < 0 or missing, the file will be opened + The the current file id will be returned in the + output argument fid, if present. If this argument is + missing, file will be close upon exit from this function. + + The data will contain nchan x ntimes calibrated values + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_epoch.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_events` + +```{text} + [eventlist] = mne_read_events(filename) + + Read an event list from a fif file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_events.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_forward_solution` + +```{text} + [fwd] = mne_read_forward_solution(fname,force_fixed,surf_ori,include,exclude) + + A forward solution from a fif file + + fname - The name of the file + force_fixed - Force fixed source orientation mode? (optional) + surf_ori - Use surface based source coordinate system? (optional) + include - Include these channels (optional) + exclude - Exclude these channels (optional) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_forward_solution.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_inverse_operator` + +```{text} + [inv] = mne_read_inverse_operator(fname) + + Reads the inverse operator decomposition from a fif file + + fname - The name of the file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_inverse_operator.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_label_file` + +```{text} + [label] = mne_read_label_file(filename) + + Reads a label file. The returned structure has the following fields + + comment comment from the first line of the label file + vertices vertex indices (0 based, column 1) + pos locations in meters (columns 2 - 4 divided by 1000) + values values at the vertices (column 5) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_label_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_morph_map` + +```{text} + [leftmap,rightmap] = mne_read_morph_map(from,to,subjects_dir) + + Read the morphing map from subject 'from' to subject 'to'. + If subjects_dir is not specified, the SUBJECTS_DIR environment + variable is used + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_morph_map.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_noise_cov` + +```{text} + [cov] = mne_read_noise_cov(fname) + + Reads a noise-covariance matrix from a fiff file + + fname - The name of the file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_noise_cov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_source_spaces` + +```{text} + [src] = mne_read_source_spaces(source,add_geom,tree) + + Reads source spaces from a fif file + + source - The name of the file or an open file id + add_geom - Add geometry information to the source spaces + tree - Required if source is an open file id, search for the + source spaces here + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_source_spaces.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_stc_file` + +```{text} + [stc] = mne_read_stc_file(filename) + + Reads an stc file. The returned structure has the following fields + + tmin The first time point of the data in seconds + tstep Time between frames in seconds + vertices vertex indices (0 based) + data The data matrix (nvert * ntime) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_stc_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_stc_file1` + +```{text} + [stc] = mne_read_stc_file1(filename) + + Reads an stc file. The returned structure has the following fields + + tmin The first time point of the data in seconds + tstep Time between frames in seconds + vertices vertex indices (1 based) + data The data matrix (nvert * ntime) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_stc_file1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_surface` + +```{text} + [verts, faces] = mne_read_surface(fname) + + Reads a FreeSurfer surface file + + fname - The file to read + verts - Vertex coordinates in meters + faces - The triangle descriptions + NOTE: The quad file faces are split by this routine to + create triangular meshes for all files + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_surface.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_surfaces` + +```{text} + [surfs] = mne_read_surfaces(surfname,read_curv,read_left,read_right,subject,subjects_dir,add_info) + + Reads FreeSurfer surface files for both hemispheres + as well as curvatures if requested. + + Adds the derived geometry information to the surfaces + + surfname - The name of the surface to read, e.g., 'pial' + read_curv - read the curvatures as well + read_left - read the left hemisphere (default true) + read_right - read the right hemisphere (default true) + subject - The name of the subject (defaults to SUBJECT environment + variable) + subjects_dir - The name of the MRI data directory (defaults to + SUBJECTS_DIR environment variable) + add_info - Add auxilliary information to the surfaces + (vertex normals, triangle centroids, triangle normals, triangle + areas) (default true) + + surfs - Output structure containing the surfaces + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_surfaces.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_w_file` + +```{text} + [w] = mne_read_w_file(filename) + + Reads a binary w file into the structure w with the following fields + + vertices - vector of vertex indices (0-based) + data - vector of data values + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_w_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_read_w_file1` + +```{text} + [w] = mne_read_w_file(filename) + + Reads a binary w file into the structure w with the following fields + + vertices - vector of vertex indices (1-based) + data - vector of data values + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_read_w_file1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_reduce_surface` + +```{text} + [verts, faces] = mne_reduce_surface(surfin,desired_ntri,surfout) + + verts - Vertex coordinates in meters + faces - The triangulation information + + surfin - Name of a surface file to read + desired_nri - Desired number of triangles after reduction + surfout - Name of a surface file to hold the reduce surface (optional) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_reduce_surface.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_rt_define_commands` + +```{text} + [ FIFF ] = mne_rt_define_commands() + + Defines structure containing the MNE_RT constants + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_rt_define_commands.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_set_current_comp` + +```{text} + mne_set_current_comp(chs,value) + + Set the current compensation value in the channel info structures + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_set_current_comp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_source_spectral_analysis` + +```{text} + [res] = mne_source_spectral_analysis(fname_rawdata, fname_output, cfg) + + Estimate frequency spectra in the source space and optionally write out + stc files which have frequencies along the "time" axis. + + fname_data - Name of the data file + + MNE inversion + cfg.inv - Inverse operator structure or file name + cfg.lambda2 - The regularization factor + cfg.dSPM - enable dSPM: 0 or 1 + + Spectral estimation + cfg.mode - output quantity; 'amplitude', 'power', 'phase' + cfg.window - window type: 'hanning', 'hamming' or any other window + function available on Matlab + cfg.fft_length - FFT length in samples (half-overlapping windows used) + cfg.foi - Frequencies of interest as [f_min f_max] + + Output + cfg.outfile - The stem of the output STC file name holding the spectra + + (C)opyright Lauri Parkkonen, 2012 + + $Log$ + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_source_spectral_analysis.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_transform_coordinates` + +```{text} + [trans_pos] = mne_transform_coordinates(filename,pos,from,to) + + Transform locations between various MRI-related coordinate frames + + filename - Name of a fif file containing the coordinate transformations + This file can be conveniently created with mne_collect_transforms + pos - N x 3 array of locations to transform (in meters) + from - Coordinate frame of the above locations + Allowed choices are: FIFFV_COORD_MRI (surface RAS coordinates) + and FIFFV_COORD_HEAD (MEG head coordinates) + to - Coordinate frame of the result + Allowed choices are: FIFFV_COORD_MRI, FIFFV_COORD_HEAD, + FIFFV_MNE_COORD_MNI_TAL (MNI Talairach), and + FIFFV_MNE_COORD_FS_TAL (FreeSurfer Talairach) + + All of the above constants are define in fiff_define_constants + + trans_pos - The transformed locations + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_transform_coordinates.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_transform_source_space_to` + +```{text} + [res] = mne_transform_source_space_to(src,dest,trans) + + Transform source space data to the desired coordinate system + + src - The source space to transform + dest - The id of the destination coordinate system (FIFFV_COORD_...) + trans - The coordinate transformation structure to use + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_transform_source_space_to.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_transpose_named_matrix` + +```{text} + [res] = mne_transpose_named_matrix(mat) + + Transpose a named matrix + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_transpose_named_matrix.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_cov` + +```{text} + mne_write_cov(fid,cov) + + Write a covariance matrix to an open file + + fid - an open file id + cov - the covariance matrix to write + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_cov.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_cov_file` + +```{text} + function mne_write_cov_file(name,cov) + + Write a complete fif file containing a covariance matrix + + fname filename + cov the covariance matrix to write + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_cov_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_events` + +```{text} + mne_write_events(filename,eventlist) + + Write an event list into a fif file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_events.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_inverse_sol_stc` + +```{text} + function mne_write_inverse_sol_stc(stem,inv,sol,tmin,tstep) + + Save dynamic inverse solution data into stc files + + stem - Stem for the stc files + inv - The inverse operator structure (can be the forward operator as well) + sol - A solution matrix (locations x time) + tmin - Time of the first data point in seconds + tstep - Time between data points in seconds + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_inverse_sol_stc.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_inverse_sol_w` + +```{text} + function mne_write_inverse_sol_w(stem,inv,sol) + + Save static inverse solution data into stc files + + stem - Stem for the w files + inv - The inverse operator structure (can be the forward operator as well) + sol - The solution matrix (number of locations) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_inverse_sol_w.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_label_file` + +```{text} + write_read_label_file(filename,label) + + Writes label file. The returned structure has the following fields + + filename output file + label a stucture containing the stc data with fields: + + comment comment for the first line of the label file + vertices vertex indices (0 based, column 1) + pos locations in meters (columns 2 - 4 divided by 1000) + values values at the vertices (column 5) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_label_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_stc_file` + +```{text} + mne_write_stc_file(filename,stc) + + writes an stc file + + filename output file + stc a stucture containing the stc data with fields: + + tmin The time of the first frame in seconds + tstep Time between frames in seconds + vertices Vertex indices (0 based) + data The data matrix nvert * ntime + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_stc_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_stc_file1` + +```{text} + mne_write_stc_file1(filename,stc) + + writes an stc file + + filename output file + stc a stucture containing the stc data with fields: + + tmin The time of the first frame in seconds + tstep Time between frames in seconds + vertices Vertex indices (1 based) + data The data matrix nvert * ntime + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_stc_file1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_surface` + +```{text} + mne_write_surface(fname,verts,faces) + + Writes a FreeSurfer surface file + + fname - The file to write + verts - Vertex coordinates in meters + faces - The triangle descriptions + comment - Optional comment to include + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_surface.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_w_file` + +```{text} + mne_write_w_file(filename, w) + + writes a binary 'w' file + + filename - name of file to write to + w - a structure with the following fields: + + vertices - vector of vertex indices (0-based) + data - vector of data values + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_w_file.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mne_write_w_file1` + +```{text} + mne_write_w_file1(filename, w) + + writes a binary 'w' file + + filename - name of file to write to + w - a structure with the following fields: + + vertices - vector of vertex indices (1-based) + data - vector of data values + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/mne/mne_write_w_file1.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mtimes2x2` + +```{text} + MTIMES2X2 compute x*y where the dimensionatity is 2x2xN or 2x2xNxM + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/mtimes2x2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mtimes3x3` + +```{text} + MTIMES3X3 compute x*y where the dimensionatity is 3x3xN or 3x3xNxM + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/mtimes3x3.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mvnrnd` + +```{text} + MVNRND Random vectors from the multivariate normal distribution. This is an + open source version that emulates a subpart of the behavior of the same + name function from the MATLAB stats-toolbox. + It emulates the 3 input, 1 output argument MATLAB-version, + where the 3 input argument is the number of samples. If + more than three input arguments are provided, an error is thrown. Also, + the input argument SIGMA cannot be 3D. + + R = MVNRND(MU,SIGMA) returns an N-by-D matrix R of random vectors + chosen from the multivariate normal distribution with mean vector MU, + and covariance matrix SIGMA. MU is an N-by-D matrix, and MVNRND + generates each row of R using the corresponding row of MU. SIGMA is a + D-by-D symmetric positive semi-definite matrix. + If the covariance matrix is diagonal, containing + variances along the diagonal and zero covariances off the diagonal, + SIGMA may also be specified as a 1-by-D matrix, + containing just the diagonal. If MU is a 1-by-D vector, MVNRND + replicates it to match the trailing dimension of SIGMA. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/stats/mvnrnd.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mxDeserialize` + +```{text} + MXDESERIALIZE reconstructs a MATLAB object from a uint8 array suitable + for passing down a comms channel to be reconstructed at the other end. + + See also MXSERIALIZE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/mxDeserialize.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `mxSerialize` + +```{text} + MXSERIALIZE converts any MATLAB object into a uint8 array suitable + for passing down a comms channel to be reconstructed at the other end. + + See also MXDESERIALIZE + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/mxSerialize.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `nanvar` + +```{text} + FORMAT: Y = NANVAR(X,FLAG,DIM) + + This file is intended as a drop-in replacement for Matlab's nanvar. It + originally forms part of the NaN suite: + http://www.mathworks.com/matlabcentral/fileexchange/6837-nan-suite/ + and was modified to be compatible. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/stats/nanvar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ndstest` + +```{text} + Performs numerous tests of ndSparse math operations, + + ndstest(TOL) + + TOL is a tolerance value on the percent error. Execution will pause in debug + mode for inspection if any one of the tests exhibits an error greater than + TOL. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DEM/ndstest.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `nearest` + +```{text} + NEAREST return the index of an array nearest to a scalar + + Use as + [indx] = nearest(array, val, insideflag, toleranceflag) + + The second input val can be a scalar, or a [minval maxval] vector for + limits selection. + + If not specified or if left empty, the insideflag and the toleranceflag + will default to false. + + The boolean insideflag can be used to specify whether the value should be + within the array or not. For example nearest(1:10, -inf) will return 1, + but nearest(1:10, -inf, true) will return an error because -inf is not + within the array. + + The boolean toleranceflag is used when insideflag is true. It can be used + to specify whether some tolerance should be allowed for values that are + just outside the array. For example nearest(1:10, 0.99, true, false) will + return an error, but nearest(1:10, 0.99, true, true) will return 1. The + tolerance that is allowed is half the distance between the subsequent + values in the array. + + See also FIND + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/nearest.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `nutmeg2fieldtrip` + +```{text} + NUTMEG2FIELDTRIP converts from NUTMEG either a sensor data structure + ('nuts') to a valid FieldTrip 'raw' structure (plus 'sourcemodel' and + 'mri' if available), OR a source structure ('beam') to a valid FieldTrip + source structure. + + Use as + [data, mri, sourcemodel] = nutmeg2fieldtrip(cfg, fileorstruct) + + Input: + cfg + .keepmri (required for either input): =1 calls ft_read_mri for 'mri' output; =0 not save out 'mri' + .out (required for source input): 's' (pos_freq_time) or 'trial' (pos_rpt) + fileorstruct: may be one of following: + 1) *.mat file containing nuts sensor structure + 2) nuts sensor structure + 3) s*.mat file containing beam source structure + 4) beam source structure (output from Nutmeg (beamforming_gui, tfbf, or tfZ) + (only scalar not vector results supported at the moment) + + Output: depending on input, one of options + 1) If nuts sensor structure input, then 'data' will be 'raw' and + optionally 'sourcemodel' if Lp present, or 'mri' if individual MRI present + 2) If beam source structure input, then 'data' will be 'source' + (May be an array of source structures (source{1} etc)) + 'sourcemodel' and 'mri' may be output as well if present in beam structure + + See alo FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, LORETA2FIELDTRIP, SPASS2FIELDTRIP, + FIELDTRIP2SPSS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/nutmeg2fieldtrip.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `optimN` + +```{text} + Full multigrid matrix solver stuff (circulant boundaries) + __________________________________________________________________________ + + FORMAT v = optimN('fmg',A, b, param) + v - the solution n1*n2*n3*n4 + A - parameterisation of 2nd derivatives + n1*n2*n3*(n4*(n4+1)/2) + The first n4 volumes are the diagonal elements, which are + followed by the off-diagonals (note that 2nd derivs are% + symmetric). e.g. if n4=3, then the ordering would be + (1,1),(2,2),(3,3),(1,2),(1,3),(2,3) + b - parameterisation of first derivatives n1*n2*n3*n4 + param - 6 parameters (settings) + - [1] Regularisation type, can take values of + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Voxel sizes + - [5][6][7] Regularisation parameters + - For membrane and bending energy, the parameters + are lambda, unused and id. + - [8] Number of Full Multigrid cycles + - [9] Number of relaxation iterations per cycle + + Note that more cycles and iterations may be needed + for bending energy than for membrane energy. + + Solve equations using a Full Multigrid method. See Press et al for more + information. + v = inv(A+H)*b + A, b and v are all single precision floating point. + H is a large sparse matrix encoded by param(1:7). + The tensor field encoded by A MUST be positive-definite. If it is not, + then anything could happen (see references about Fisher scoring for help + on ensuring that second derivatives are positive definite). + + __________________________________________________________________________ + + FORMAT m = optimN('vel2mom', v, param) + v - velocity (flow) field n1*n2*n3*n4. + param - 4 parameters (settings) + - [1] Regularisation type, can take values of + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Voxel sizes + - [5][6][7] Regularisation parameters + - For membrane and bending energy, the parameters + are lambda, unusaed and id. + m - `momentum' field n1*n2*n3*n4. + + Convert a flow field to a momentum field by m = H*v, where H is the large + sparse matrix encoding some form of regularisation. v and m are single + precision floating point. This function has uses beyond only image + registration. + + __________________________________________________________________________ + + Note that the boundary conditions are circulant throughout. For Neumann + boundary conditions (zero gradients at the boundaries) use optimNn. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DARTEL/optimN.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `optimNn` + +```{text} + Full multigrid matrix solver stuff (zero gradient at boundaries) + __________________________________________________________________________ + + FORMAT v = optimNn('fmg',A, b, param) + v - the solution n1*n2*n3*n4 + A - parameterisation of 2nd derivatives + n1*n2*n3*(n4*(n4+1)/2) + The first n4 volumes are the diagonal elements, which are + followed by the off-diagonals (note that 2nd derivs are% + symmetric). e.g. if n4=3, then the ordering would be + (1,1),(2,2),(3,3),(1,2),(1,3),(2,3) + b - parameterisation of first derivatives n1*n2*n3*n4 + param - 6 parameters (settings) + - [1] Regularisation type, can take values of + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Voxel sizes + - [5][6][7] Regularisation parameters + - For membrane and bending energy, the parameters + are lambda, unused and id. + - [8] Number of Full Multigrid cycles + - [9] Number of relaxation iterations per cycle + + Note that more cycles and iterations may be needed + for bending energy than for membrane energy. + + Solve equations using a Full Multigrid method. See Press et al for more + information. + v = inv(A+H)*b + A, b and v are all single precision floating point. + H is a large sparse matrix encoded by param(1:7). + The tensor field encoded by A MUST be positive-definite. If it is not, + then anything could happen (see references about Fisher scoring for + help on ensuring that second derivatives are positive definite). + + __________________________________________________________________________ + + FORMAT m = optimNn('vel2mom', v, param) + v - velocity (flow) field n1*n2*n3*n4. + param - 4 parameters (settings) + - [1] Regularisation type, can take values of + - 1 Membrane energy + - 2 Bending energy + - [2][3][4] Voxel sizes + - [5][6][7] Regularisation parameters + - For membrane and bending energy, the parameters + are lambda, unusaed and id. + m - `momentum' field n1*n2*n3*n4. + + Convert a flow field to a momentum field by m = H*v, where + H is the large sparse matrix encoding some form of regularisation. + v and m are single precision floating point. This function has uses + beyond only image registration. + + __________________________________________________________________________ + + Note that the boundary conditions are Neumann (zero gradients at the + boundaries) throughout. For circulant boundary conditions, use optimN. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DARTEL/optimNn.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `optim_compat` + +```{text} + Compatibility function for optimN and optimNn + FORMAT varargout = optim_compat(bc,varargin) + bc - boundary condition (0=circulant, 1-Neumann) + + Call the new spm_field function via the old API of the optimN and + optimNn functions. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/DARTEL/optim_compat.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `plgndr` + +```{text} + PLGNDR associated Legendre function + + y = plgndr(n,k,x) computes the values of the associated Legendre functions + of degree N and order K + + implemented as MEX file + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/plgndr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `plinproj` + +```{text} + PLINPROJ projects a point onto a line or linepiece + + Use as + [proj, dist] = plinproj(l1, l2, r, flag) + where l1 and l2 are the begin and endpoint of the linepiece, and r is + the point that is projected onto the line + + the optional flag can be: + 0 (default) project the point anywhere on the complete line + 1 project the point within or on the edge of the linepiece + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/plinproj.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_angvar` + +```{text} + Estimates the (voxelwise) variance of the angle + estimated from the complex map cmap. + FORMAT: angvar = pm_angvar(cmap) + + Input: + cmap : Complex-valued MR intensity image. When used to + estimate the variance of a delta_phi map estimated + from two measurements with different echo-time this + should be the image with the longer echo-time. + + Output: + angvar : Map with an estimate of the variance of a phasemap + estimated using cmap as one of its constituents. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_angvar.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_brain_mask` + +```{text} + Calculate a brain mask + FORMAT bmask = pm_brain_mask(P,flags) + + P - is a single pointer to a single image + + flags - structure containing various options + fwhm - fwhm of smoothing kernel for generating mask + nerode - number of erosions + thresh - threshold for smoothed mask + ndilate - number of dilations + + __________________________________________________________________________ + + Inputs + A single *.img conforming to SPM data format (see 'Data Format'). + + Outputs + Brain mask in a matrix + __________________________________________________________________________ + + The brain mask is generated by segmenting the image into GM, WM and CSF, + adding these components together then thresholding above zero. + A morphological opening is performed to get rid of stuff left outside of + the brain. Any leftover holes are filled. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_brain_mask.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_create_connectogram` + +```{text} + Create vectors corresponding to a connectogram based on label-map. + FORMAT [ii,jj,nn,pp] = pm_create_connectogram(rima,pm) + or + FORMAT [N,P] = pm_create_connectogram(rima,pm) + + Input: + rima : Label map consisting of connected regions indentified + by unique labels. + pm : Phasemap. + + Output: + EITHER + ii : Array of row indicies. + jj : Array of column indicies. + nn : Array of no. of voxels in borders between regions. + So e.g. if ii[10]=5, jj[10]=9 and nn[10]=123 it + means that regions 5 and 9 have a common border + (are connected) and that this border has 123 voxels. + pp : Array of sum of phase differences between regions. + So e.g. if ii[10]=5, jj[10]=9 and pp[10]=770.2 it + means that regions 5 and 9 have a common border + (are connected) and that for paired voxels across + this border the sum of phase differenes is 770.2. + N.B. the subtraction is phi(ii(i))-phi(jj(i)), + which in the example above means that the phase is + smaller in region 9 than in region 5. + + OR + + N : Sparse matrix where N(i,j) for ipi range. We will then simply divide + the observed range into nstep steps. + + Output: + irima : Image with connected regions of phase-values + within each range. + cn : Total number of conncted regions. + + This routine is used to make the initial division into + a set of regions, which within each it is very unlikely that + a phase-wrap has occurred, that is the preamble for Mark + J's method. A higher value for nstep makes it less likely + that a wrap is included within a region, but will also + lead to more regions->longer execution time. + + N.B. The interval > phi <= is based on the observation that + angle(-1) returns pi (rather than -pi). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_initial_regions.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_invert_phasemap` + +```{text} + Inverting phasemaps (trickier than it sounds). + FORMAT ipm = invert_phasemap(pm) + or + FORMAT ipm = invert_phasemap(pm,idim) + or + FORMAT ipm = invert_phasemap(P) + or + FORMAT ipm = invert_phasemap(P,idim) + or + FORMAT invert_phasemap(P,fname) + or + FORMAT invert_phasemap(P,fname,idim) + + Input: + pm 1, 2 or 3D array representing a displacement field that + is to be inverted along one direction. + idim The dimension along which field is to be inverted. + P File-struct or -name containing displacement field. + fname Name of output file. + + Output: + ipm Displacement-field inverted along requested direction. + + This is a gateway function to invert_phasemap_dtj (do the job) + which is a mex-file. The job of this routine is to handle some of + the basic book-keeping regarding format and file creation. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_invert_phasemap.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_make_fieldmap` + +```{text} + This function creates an unwrapped fieldmap (in Hz) from either + a single or double echo complex image volume. In the case of a + "single-echo" image, that will have been created by the vendor + sequence out of two acquisitions with different echo times. + The complex image volume(s) may consist of either real and + imaginary OR phase and magnitude components + + FORMAT fm = pm_make_fieldmap(P,flags); + + Input: + P : A matrix of 2 or 4 filenames, or + a struct array of 2 or 4 memory mapped image volumes. + flags : Struct containing parameters guiding the unwrapping. + .iformat : 'RI' or 'PM' + 'RI' - input images are Real and Imaginary. (default) + 'PM' - input images are Phase and Magnitude + .method : 'Huttonish', 'Mark3D' or 'Mark2D' + 'Huttonish': Flood-fill based unwrapping progressing + from low to high uncertainty areas. + 'Mark3D': Region-merging based method merging 3D + regions starting with the big ones. (default) + 'Mark2D': Region-merging based method merging + slicewise 2D regions until all connected regions + within slices have been merged before moving on + to merging the slices. + .fwhm : FWHM (mm) of Gaussian filter used to implement + a weighted (with the reciprocal of the angular + uncertainty) smoothing of the unwrapped maps. + (default: 10mm) + .pad : Size (in-plane voxels) of padding kernel. This + is an option to replace non-unwrapped voxels + (i.e. those that have been considered to noisy) + with an average of neighbouring unwrapped voxels. + The size defines the size of the neighbourhood. + (default = 0); + .etd : Echo time difference (ms).(default = 10) + .ws : Weighted or unweighted smoothing (default = 1) + .bmask : Brain mask + + Output: + fm : Structure containing fieldmap information + The elements of the fm structure are: + fm.upm : unwrapped fieldmap in Hz + fm.mask : binary image used to mask fieldmap + fm.opm : phase map in radians + fm.jac : Jacobian of the fieldmap + _______________________________________________________________________ + + .iformat = 'RI' (this the default mode if not specified) + + P(1) : real part of complex fieldmap image + P(2) : imaginary part of complex fieldmap image + OR + P(1) : real part of short echo time image + P(2) : imaginary part of short echo time image + P(3) : real part of long echo time image + P(4) : imaginary part of long echo time image + + Mode = 'PM' + + P(1) : phase image + P(2) : magnitude image + OR + P(1) : phase of short echo time image + P(2) : magnitude of short echo time image + P(3) : real part of long echo time image + P(4) : imaginary part of long echo time image + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_make_fieldmap.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_mask` + +```{text} + Create a mask that will determine how far to proceed with phase unwrapping + FORMAT mask = pm_mask(angvar,mthrea,ndil) + + Input: + angvar : Map of variance of angle estimate. + mthres : Threshold for variance beyond which + phase unwrapping is considered too + uncertain. Default value (pi^2)/6 + is half the variance of a U[-pi,pi] + distribution. + ndil : We can optionally specify a no. of + erodes-dilates to apply to the mask + in order to exclude areas connected + only by thin bridges to the rest of + the brain. + + Output: + mask : Well... + + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_mask.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_merge_regions` + +```{text} + Merges regions as defined in connectogram to minimise + total costfunction (sum of phase-differences across + region borders). + FORMAT: pm = pm_merge_regions(pm,rima,ii,jj,nn,pp,rs) + + Input: + pm : Phase-map + rima : Label map consisting of connected regions indentified + by unique labels. Use pm_initial_regions to get rima. + ii : Array of row indicies. + jj : Array of column indicies. + nn : Array of no. of voxels in borders between regions. + So e.g. if ii[10]=5, jj[10]=9 and nn[10]=123 it + means that regions 5 and 9 have a common border + (are connected) and that this border has 123 voxels. + pp : Array of sum of phase differences between regions. + So e.g. if ii[10]=5, jj[10]=9 and pp[10]=770.2 it + means that regions 5 and 9 have a common border + (are connected) and that for paired voxels across + this border the sum of phase differenes is 770.2. + N.B. the subtraction is phi(ii(i))-phi(jj(i)), + which in the example above means that the phase is + smaller in region 9 than in region 5. + rs : List of region sizes, so that e.g. if rs[13]=143 it + means that the regions with label 13 consists + of 143 voxels. + + Output: + pm : Phase-map after merging of all regions in rima that + are connected. + + This routine is based on the MRM paper by Mark J. Very briefly it will + use the summary statistic in the matrices N and P, where each entry in + N signifies the number of voxels along the common border of the regions + whose labels correspond to row and column of the matrix. E.g. N(i,j) (for ihigh varinace areas in region-growing + approches. + + The first goal is easily reached by noting that (P(i,j)/N(i,j))/2pi + is a good guess for the number of wraps that differ between regions + i and j. + + The second goal is reached by merging the pairs of regions that have + the largest border (i.e. the largest N(i,j)) first (it is a little + more elaborate, but basically like that). + + The rest is really just about being really careful when updating the + stats regarding all the connections between a newly merged regions + and all the regions that bordered to one or both of the regions + constituting the new region. + + Jenkinson M. 2003. Fast, automated, N-dimensional phase-unwrapping + algorithm. MRM 49:193-197. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_merge_regions.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_merge_regions_m` + +```{text} + Merges regions as defined in connectogram to minimise + total costfunction (sum of phase-differences across + region borders). + FORMAT: pm = pm_merge_regions_m(pm,N,P,rima) + or + FORMAT: [pm,rima] = pm_merge_regions_m(pm,N,P,rima); + + Input: + pm : Phase-map + N : Sparse matrix where N(i,j) for ihigh varinace areas in region-growing + approches. + + The first goal is easily reached by noting that (P(i,j)/N(i,j))/2pi + is a good guess for the number of wraps that differ between regions + i and j. + + The second goal is reached by merging the pairs of regions that have + the largest border (i.e. the largest N(i,j)) first (it is a little + more elaborate, but basically like that). + + The rest is really just about being really careful when updating the + stats regarding all the connections between a newly merged regions + and all the regions that bordered to one or both of the regions + constituting the new region. + + Jenkinson M. 2003. Fast, automated, N-dimensional phase-unwrapping + algorithm. MRM 49:193-197. + + This is a .m version of pm_merge_regions.c. It is a fare bit slower + and produces identical results. Due to its relative simplicity and + its graphical output capabilities it might however be useful for + understanding the process per se and for understanding what happens + if/when unwrapping fails in a certain data set. + + If one wants to use the .m versions one should change in pm_unwrap.m + so that + + [ii,jj,nn,pp] = pm_create_connectogram(rima,pm); + rs = histc(rima(:),[0:max(rima(:))]+0.5); + rs = rs(1:end-1); + upm = pm_merge_regions(pm,rima,ii,jj,nn,pp,rs); + + changes to + + [N,P] = pm_create_connectogram(rima,pm); + upm = pm_merge_regions_m(pm,N,P,rima); + _________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_merge_regions_m.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_pad` + +```{text} + Pads a (partially) unwrapped phasemap such that the phase + at a non-unwrapped location is a weighted average of unwrapped + neighbouring phase-values. + FORMAT [pm,wmap] = pm_pad(pm,wmap,kernel) + + Input: + pm : 2 or 3D phasemap where some voxels have been unwrapped + and some not. + wmap : Wrap-map, where a non-zero value indicates corresponding + phase-value in pm has been unwrapped. + kernel : kernel used to generate a weighted average of surrounding + voxels. + + Output: + pm : Same as pm in, but where some previously unwrapped + phase-values have now been replaced. + wmap : Same as wmap in, but where values that was replaced + by weighted average in pm have now been set. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_pad.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_restore_ramp` + +```{text} + Restores linear phase-ramps in the x-, y- and z-direction + that has previously been removed from pm by pm_estimate_ramp. + FORMAT: pm = pm_estimate_ramp(pm,mask,ramps) + + Input: + pm : 2 or 3D phasemap that has been unwrapped and + that has had its ramps removed by pm_remove_ramp + mask : Mask that indicates which voxels are worth + bothering with and which are not. + ramps : 3x1 vector signifying the slope of the ramps in + the x-, y- and z-directions. This SHOULD be the + values returned by a previous call to pm_estimate_ramp. + + Output: + pm : Same as pm in, but with linear ramps restored. + + This routine was written on the suggestion of Mark J, and will + potentially improve performance of subsequent phase-unwrapping. + I haven't actually found it particularly helpful, and it may + simply have been a sneaky fMRIB attempt to delay the SPM + phasemap toolbox. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_restore_ramp.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_seed` + +```{text} + Find a suitable (hopefully) seed point from which + to start watershed-based unwrapping. + FORMAT: seed = pm_seed(angvar,mask,pxs) + + Input: + angvar : Map of variance of (voxelwise) estimates + of phase angle. + mask : Tells us which part of angvar to consider. + pxs : Array of voxel sizes, used to ensure + isotropic smoothing. + + Output: + seed : Coordinates of suitable seed point. + + In order to find a seed point we first threshold the + variance map at a quarter of the variance of a U(-pi,pi) + distribution. This gives us a binary image with ones only + for low variance regions. This is then smoothed with a + very wide gaussian kernel (50mm). The maximum of + the smoothed map is then pretty much a centre-of-mass + of the "low-variance volume". It could however in + principle be a relatively high variance voxel + surrounded by low-variance voxels. Therefore we pick + a percentage of the highest voxels in the smooth map + (i.e. we pick a neighbourhood) and then pick the location + of those that has the lowest variance in the original + variance map. + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_seed.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_segment` + +```{text} + Segment an MR image into Gray, White & CSF. + + FORMAT VO = pm_segment(PF,PG,flags) + PF - name(s) of image(s) to segment (must have same dimensions). + PG - name(s) of template image(s) for realignment. + - or a 4x4 transformation matrix which maps from the image to + the set of templates. + flags - a structure normally based on defaults.segment + VO - optional output volume + M - affine transformation between template and image to segment + + The algorithm is four step: + + 1) Determine the affine transform which best matches the image with a + template image. If the name of more than one image is passed, then + the first image is used in this step. This step is not performed if + no template images are specified. + + 2) Perform Cluster Analysis with a modified Mixture Model and a-priori + information about the likelihoods of each voxel being one of a + number of different tissue types. If more than one image is passed, + then they they are all assumed to be in register, and the voxel + values are fitted to multi-normal distributions. + + 3) Perform morphometric operations on the grey and white partitions + in order to more accurately identify brain tissue. This is then used + to clean up the grey and white matter segments. + + 4) If no or 2 output arguments is/are specified, then the segmented + images are written to disk. The names of these images have "c1", + "c2" & "c3" appended to the name of the first image passed. The + 'brainmask' is also created with "BrMsk_" as an appendix. + + _______________________________________________________________________ + Refs: + + Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and + Partitioning - a Unified Framework. NeuroImage 6:209-217 + + _______________________________________________________________________ + + The template image, and a-priori likelihood images are modified + versions of those kindly supplied by Alan Evans, MNI, Canada + (ICBM, NIH P-20 project, Principal Investigator John Mazziotta). + _______________________________________________________________________ + + This is a renamed version of the original spm_segment which has been + removed from the main spm distribution, but copied into the FieldMap + toolbox where it is still used. + _______________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_segment.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_smooth_phasemap` + +```{text} + Performs a weighted (by 1/angvar) gaussian smoothing of a phasemap + FORMAT pm = pm_smooth_phasemap(pm,angvar,vxs,fwhm) + + Input: + pm : Phase-map + angvar : Map of uncertainty of the angular estimate. + vxs : Voxel sizes (mm) in the three directions. + fwhm : FWHM (mm) of gaussian kernel for the three + directions (or scalar for isotropic kernel). + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_smooth_phasemap.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pm_unwrap` + +```{text} + Unwrapping of phasemap + When measuring phase one cannot easily distinguish between e.g. a phase + of 182 degrees, and one of -178 degrees. One tries to distinguish these + cases by using neighbourhood information. So in the example above, if we + find that a neighbouring voxel has a phase of 150 degres it seems much + more likely that the "true" phase is 182 degrees than -178 degrees. It's + trickier than it sounds. + FORMAT: [upm,(angvar),(mask),(opm)] = pm_unwrap(ci,pxs,method) + or + FORMAT: [upm,(angvar),(mask),(opm)] = pm_unwrap(ci,pxs) + or + FORMAT: [upm,(angvar),(mask),(opm)] = pm_unwrap(P,method) + or + FORMAT: [upm,(angvar),(mask),(opm)] = pm_unwrap(P) + + Input: + ci : Complex image volume corresponding + to abs(te2).*exp(i*angle(te2))./exp(i*angle(te1)); + where te1 and te2 corresponds to the complex + images obtained with the short and the long + echo-time respectively, and i denotes sqrt(-1). + pxs : 3x1 (or 2x1) array with pixel sizes. + + or + + P : File structure (from) spm_vol, containing complex + image volume as per above. + + method : Determines which method should be used + for phase-unwrapping. The options are + 'Huttonish', 'Mark2D', 'Mark3D' and 'hybrid'. + 'Huttonish' : Loosely (hence -ish) based on method described + in Hutton et al. Gets an estimate of the + uncertainty of the phase angle at each point + and unwraps in a "watershed" fashion from + a high certainty seed towards more uncertain + areas. + 'Mark2D' : Method suggested for high-res data in + Jenkinssons MRM paper. + 'Mark3D' : Method suggested for low-res data in + Jenkinssons MRM paper. + + Output: + upm : Phasemap (corresponding to angle(ci)) + after unwrapping of phase jumps. + angvar : Map of the variance of the phase-angle + estimates. This is used internally to + guide the unwrapping procedure, and + can also be used if one whishes to + do a weighted fitting of some smooth + basis set to the unwrapped phasemap. + mask : Binary mask indicating what voxels + have been unwrapped. + opm : angle(ci) + + Light reading: + + Examples of water-shed/flood-fill based unwrapping + algorithms: + + Hutton C, Bork A, Josephs O, Deichmann R, Ashburner J, + Turner R. 2002. Image distortion correction in fMRI: A + quantitative evaluation. NeuroImage 16:217-240. + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/FieldMap/pm_unwrap.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pp_settings` + +```{text} + Settings for push/pull + FORMAT sett = pp_settings(deg,bnd,ext) + deg - interpolation degree in each dimension (3 elements) + 0 - nearest neighbour + 1 - trilinear + 2 - cubic B-spline + 3 - 3rd degree B-spline + 4 - 4th degree B-spline + bnd - boundary conditions in each dimension (3 elements) + 0 - circulant + 1 - reflected + 2 - reflected negative + ext - extrapolation flag 0/1 + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Spatial/pp_settings.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `printstruct` + +```{text} + PRINTSTRUCT converts a MATLAB structure into a multiple-line string that, when + evaluated by MATLAB, results in the original structure. It also works for most + other standard MATLAB classes, such as numbers, vectors, matrices, and cell-arrays. + + Use as + str = printstruct(val) + or + str = printstruct(name, val) + where "val" is any MATLAB variable, e.g. a scalar, vector, matrix, structure, or + cell-array. If you pass the name of the variable, the output is a piece of MATLAB code + that you can execute, i.e. an ASCII serialized representation of the variable. + + Example + a.field1 = 1; + a.field2 = 2; + s = printstruct(a) + + b = rand(3); + s = printstruct(b) + + s = printstruct('c', randn(10)>0.5) + + See also DISP, NUM2STR, INT2STR, MAT2STR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/printstruct.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `ptriproj` + +```{text} + PTRIPROJ projects a point onto the plane going through a triangle + + Use as + [proj, dist] = ptriproj(v1, v2, v3, r, flag) + where v1, v2 and v3 are three vertices of the triangle, and r is + the point that is projected onto the plane spanned by the vertices + + the optional flag can be: + 0 (default) project the point anywhere on the complete plane + 1 project the point within or on the edge of the triangle + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/ptriproj.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pull` + +```{text} + GPU single precision pull + FORMAT f1 = pull(f0, phi, sett) + f0 - 3D float array + phi - 4D float array (dim(4)=3) + sett - Settings + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Spatial/pull.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `pullg` + +```{text} + GPU single precision pullg + FORMAT g1 = pullg(f0, phi, sett) + f0 - 3D float array + phi - 4D float array (dim(4)=3) + sett - Settings + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Spatial/pullg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `push` + +```{text} + GPU single precision push + FORMAT f0 = push(f1, phi, dm0, sett) + f1 - 3D float array + phi - 4D float array (dim(4)=3) + dm0 - Output dimensions + sett - Settings + __________________________________________________________________________ + + + [Matlab code]( https://github.com/spm/spm/blob/main/toolbox/Spatial/push.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `range_` + +```{text} + RANGE computes the range (i.e. difference between min and max) for a vector + or an N-dimensional array. + + Use as + r = range(x) + or you can also specify the dimension along which to look by + r = range(x, dim) + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/stats/range.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `readCPersist` + +```{text} + Version 1.2 24 April 2007 Modified to close the CPersist file if a really huge + taglength is encountered. Recently discovered .acq files with the string 'ssss' added + at the end of the file after the final 'EndofParameters' string. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/ctf/readCPersist.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `readCTFMRI` + +```{text} + Version 1.2: 25 April 2007 Module readCPersist changed and removed from this listing. + Version 1.1: 19 April 2007 No changes since v1.0 + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/ctf/readCTFMRI.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `readCTFds` + +```{text} + ************************************************************************ + + This program is provided to users of CTF MEG systems as a courtesy only. + It's operation has not been verified for clinical use. + Please do not redistribute it without permission from CTF Systems Inc. + + ************************************************************************ + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/ctf/readCTFds.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `readCTFhdm` + +```{text} + Version 1.1 19 April 2007 - Test date. + 21 March 2007. Modified to read v6.0 .hdm files that have additional + fields in MultiSphere_Data + Reads a head model file and returns the contents as a structure. The purpose is + to make localSpheres head models available in the MATLAB environment. + Head Model File format is a "Config Reader" file. It is defined in document + "CTF MEG FIle Formats', PN900-0088. + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/ctf/readCTFhdm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_16bit` + +```{text} + READ_16BIT read a stream of 16 bit values and converts them to doubles + This function is designed for EDF files and is implemented as mex + file for efficiency. + + Use as + [dat] = read_16bit(filename, offset, numwords); + + See also READ_24BIT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/read_16bit.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_24bit` + +```{text} + READ_24BIT read a stream of 24 bit values and converts them to doubles + This function is designed for Biosemi BDF files and is implemented as mex + file for efficiency. + + Use as + [dat] = read_24bit(filename, offset, numwords); + + See also READ_16BIT + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/read_24bit.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_ctf_shm` + +```{text} + READ_CTF_SHM reads metainformation or selected blocks of data from + shared memory. This function can be used for real-time processing of + data while it is being acquired. + + Use as + [msgType msgId sampleNumber numSamples numChannels] = read_ctf_shm; + or + [data] = read_ctf_shm(msgNumber); + [data] = read_ctf_shm(msgNumber, numValues); + + See also WRITE_CTF_SHM + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/read_ctf_shm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_eep_avr` + +```{text} + READ_EEP_AVR reads averaged EEG data from an EEProbe *.avr file + and returns a structure containing the header and data information. + + eeg = read_eep_avr(filename) + + eeg.label ... array of labels (1 x nchan) + eeg.rate ... sample rate (Hz) + eeg.npnt ... number of data points + eeg.nchan ... number of channels + eeg.nsweeps ... number of trials averaged + eeg.xmin ... + eeg.xmax ... + eeg.time ... array of time (1 x npnt) + eeg.data ... data array (nchan x npnt) + eeg.variance ... variance (nchan x npnt) + eeg.condlab ... string with condition label + eeg.condcol ... string with color code for condition + eeg.psi ... pre-stimulus interval + eeg.trialc ... total number of trial in original data + eeg.rejtrialc ... number of rejected trials + + Use plot(eeg.time,eeg.data) to plot the traces at all channels + + Author: Robert Oostenveld, Aalborg University, Denmark, 11 March 2003 + + See also READ_EEP_CNT, READ_EEP_TRG, READ_EEP_REJ + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/eeprobe/read_eep_avr.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_eep_cnt` + +```{text} + READ_EEP_CNT reads continuous EEG data from an EEProbe *.cnt file + and returns a structure containing the header and data information. + + eeg = read_eep_cnt(filename, sample1, sample2) + + where sample1 and sample2 are the begin and end sample of the data + to be read. + + eeg.label ... labels of EEG channels + eeg.rate ... sampling rate + eeg.npnt ... number of sample in data segment + eeg.nchan ... number of channels + eeg.nsample + eeg.time ... array [1 x npnt] of time points (ms) + eeg.data ... array [nchan x npnt] containing eeg data (uV) + eeg.trigger ... array [n, 4] containing trigger information + + Author: Robert Oostenveld, Aalborg University, Denmark, 11 March 2003 + + See also READ_EEP_TRG, READ_EEP_REJ, READ_EEP_AVR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/eeprobe/read_eep_cnt.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_eep_rej` + +```{text} + READ_EEP_REJ reads rejection marks from an EEProbe *.rej file + + This function returns a Nx2 matrix with the begin and end latency + of N rejection marks. The latency is in miliseconds. + + rej = read_eep_rej(filename) + + An EEProbe rejection file is formatted like + 0.0000-0.3640 + 2.4373-3.5471 + ... + where rejection begin and end are given in seconds. This function + converts the latency in miliseconds. + + Author: Robert Oostenveld, Aalborg University, Denmark, 11 March 2003 + + See also READ_EEP_CNT, READ_EEP_TRG, READ_EEP_AVR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/eeprobe/read_eep_rej.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_eep_trg` + +```{text} + READ_EEP_TRG reads triggers from an EEProbe *.trg file + + This function returns an Nx1 array with the N triggers + + [trg] = read_eep_trg(filename) + + trg(i).time ... trigger latency in ms + trg(i).offset ... byte offset + trg(i).code ... trigger code (string) + trg(i).type ... numeric value of trg.code + + where i as number between 1 and N (the number of triggers found) + + An EEProbe trigger file is formatted like + 0.00195312 256 + 0.000 10350 __ + 17.033 2242926 1 + 20.535 2701934 5 + 21.096 2775406 13 + 21.098 2775662 8 + ... + where the first column is the trigger latency in seconds, the second + column is the byte offset in the file and the third column is the triggercode. + The triggercode can be numeric or a string. The first line of the file contains the + sample duration. + + Author: Robert Oostenveld, Aalborg University, Denmark, 11 March 2003 + + See also READ_EEP_CNT, READ_EEP_REJ, READ_EEP_AVR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/eeprobe/read_eep_trg.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `read_eep_trial` + +```{text} + READ_EEP_TRIAL reads a data from an EEProbe *.cnt file + + [eeg,t] = read_eep_trial(filename, triggernumber, interval); + + interval = [ -2, 5] reads a window of -2 to 5 seconds around + the given trigger number + + Script returns eeg data structure: it contains the data, labels etc + for the given interval + + t is the time in milliseconds of the trial (at the trigger, i.e., stimulus-time) + + Author: Michiel van Burik, ANT Software, Enschede, The Netherlands, 8 October 2003 + + See also READ_EEP_TRG, READ_EEP_REJ, READ_EEP_AVR + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/eeprobe/read_eep_trial.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `removefields` + +```{text} + REMOVEFIELDS makes a selection of the fields in a structure + + Use as + s = removefields(s, fields); + + See also KEEPFIELDS, COPYFIELDS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/removefields.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `renamefields` + +```{text} + RENAMEFIELDS renames a selection of the fields in a structure + + Use as + b = renamefields(a, old, new) + which renames the fields with the old name to the new name. Fields that + are specified but not present will be silently ignored. + + See also COPYFIELDS, KEEPFIELDS, REMOVEFIELDS + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/renamefields.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `rfbevent` + +```{text} + RFBEVENT sends a keyboard or mouse event to a VNC server + + RFB ("remote frame buffer") is a simple protocol for remote access to + graphical user interfaces. Because it works at the framebuffer level it + is applicable to all windowing systems and applications, including X11, + Windows and Macintosh. RFB is the protocol used in VNC (Virtual Network + Computing). + + The remote endpoint where the user sits (i.e. the display plus keyboard + and/or pointer) is called the RFB client or viewer. The endpoint where + changes to the framebuffer originate (i.e. the windowing system and + applications) is known as the RFB server. + + Use as + rfbevent(display, passwd, eventtype, eventvalue, ...) + + Some examples + rfbevent('vncserver:5901', 'yourpasswd', 'Text', 'xclock') % type multiple characters + rfbevent('vncserver:5901', 'yourpasswd', 'Button', 'Return') % single key event, press and release + rfbevent('vncserver:5901', 'yourpasswd', 'Button', 'Return', 0) % single key event, press and release + rfbevent('vncserver:5901', 'yourpasswd', 'Button', 'Return', 1) % single key event, press only + rfbevent('vncserver:5901', 'yourpasswd', 'Button', 'Return', -1) % single key event, release only + rfbevent('vncserver:5901', 'yourpasswd', 'Pointer', [20 100]) % only mouse position + rfbevent('vncserver:5901', 'yourpasswd', 'Pointer', [20 100 1]) % mouse position and button 1, press and release + rfbevent('vncserver:5901', 'yourpasswd', 'Pointer', [20 100 1], 0) % mouse position and button 1, press and release + rfbevent('vncserver:5901', 'yourpasswd', 'Pointer', [20 100 1], 1) % mouse position and button 1, press only + rfbevent('vncserver:5901', 'yourpasswd', 'Pointer', [20 100 1], -1) % mouse position and button 1, release only + + Note that the password has to be represented as plain text in the matlab + script/function that is using RFBEVENT, which poses a potential security + problem. The password is sent over the network to the VNC server after + being encrypted. + + This implements the KeyEvent and PointerEvent messages according to + "The RFB Protocol" by Tristan Richardson (RealVNC Ltd, formerly of + Olivetti Research Ltd / AT&T Labs Cambridge) Version 3.8 (Last updated 8 + June 2007), http://www.realvnc.com/docs/rfbproto.pdf + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/rfbevent.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `rgb2hsv` + +```{text} + RGB2HSV converts red-green-blue colors to hue-saturation-value. + + this code is based on the comments in + http://stackoverflow.com/questions/3018313/algorithm-to-convert-rgb-to-hsv-and-hsv-to-rgb-in-range-0-255-for-both + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/external/images/rgb2hsv.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `rmsubfield` + +```{text} + RMSUBFIELD removes the contents of the specified field from a structure + just like the standard Matlab RMFIELD function, except that you can also + specify nested fields using a '.' in the fieldname. The nesting can be + arbitrary deep. + + Use as + s = rmsubfield(s, 'fieldname') + or as + s = rmsubfield(s, 'fieldname.subfieldname') + + See also SETFIELD, GETSUBFIELD, ISSUBFIELD + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/utilities/rmsubfield.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `routlm` + +```{text} + ROUTLM computes the projection of a point from its la/mu parameters + these equal the "Barycentric" coordinates + + Use as + [proj] = routlm(v1, v2, v3, la, mu) + where v1, v2 and v3 are three vertices of the triangle + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/routlm.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `sandwich2x2` + +```{text} + SANDWICH2X2 compute x*y*x' provided y is Hermitian and dimensionality is 2x2xN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/sandwich2x2.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `sandwich3x3` + +```{text} + SANDWICH3X3 compute x*y*x' provided y is Hermitian and dimensionality is 3x3xN + + + [Matlab code]( https://github.com/spm/spm/blob/main/external/fieldtrip/src/sandwich3x3.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `savexml` + +```{text} + SAVEXML Save workspace variables to disk in XML. + SAVEXML FILENAME saves all workspace variables to the XML-file + named FILENAME.xml. The data may be retrieved with LOADXML. if + FILENAME has no extension, .xml is assumed. + + SAVE, by itself, creates the XML-file named 'matlab.xml'. It is + an error if 'matlab.xml' is not writable. + + SAVE FILENAME X saves only X. + SAVE FILENAME X Y Z saves X, Y, and Z. The wildcard '*' can be + used to save only those variables that match a pattern. + + SAVE ... -APPEND adds the variables to an existing file. + + Use the functional form of SAVE, such as SAVE(filename','var1','var2'), + when the filename or variable names are stored in strings. + + See also SAVE, MAT2XML, XMLTREE. + + + [Matlab code]( https://github.com/spm/spm/blob/main/compat/savexml.m ) + + Copyright (C) 1995-2025 Functional Imaging Laboratory, Department of Imaging Neuroscience, UCL +``` + +### `setCTFDataBalance` + +```{text} + Version 1.1 13 April 2007 Mod to chanList: If chanList is omitted and + size(data,2)