Sanjay's MATLAB library functions

See also separate page on Eye Movement analysis.
The whole library can be downloaded (0.15 MB) as a zip, or is available on GitHub / OSF. Unzip this and add 'matlib' to your MATLAB path. The individual functions are specified below.

2-dimensional data visualisation

Useful for looking at data consisting of paired measurements.

conditionalPlot Download

This is designed to do a between-subjects comparison of one variable conditioned on another -- when two variables are measured per trial. For example, if you supply the RT and accuracy for each trial, it will generate a conditional accuracy plot. Can handle multiple conditions and multiple subjects.

plotBins Download

This plots the mean Y value in each quantile bin of X. The error bar is the standard deviation of the Y values in each bin.

plotBinsQuantiled Download

Use this to plot the quantile levels of a Y variable, when datapoints are binned according to the quantile of another X variable.

plotBinsQuantiledGrid Download

Plot a mesh of quantile levels of two variables, X and Y, when both variables are binned according to quantiles. The deviation of the lines from a rectangular grid thus indicates deviations from independence.

scatterRegress Download

Shortcut function that works like scatter, then also does a linear regression and plots the fit line.

heatmap Download

This functions like scatter, but plots a heatmap of the density of points.

Basic matrix functions

Some of these functions really ought to be included in Matlab! My implementations are not fast, but they are terser than writing loops etc.

nancat Download

This allows you to concatenate any arrays - even if they are of different sizes. The syntax is the same as the normal "cat". Any items that are smaller are padded with nans on all the relevant dimensions

pivot Download

Does what a pivot-table does in excel. Converts data in "long form" to an n-dimensional table. The last column is treated as values, the earlier columns as categories.

dePivot Download

Undoes what "pivot" did. Converts an n-dimensional table into long-form, with a "condition" column for each dimension of the input.

anovanTable Download

Performs an N-dimensional anova, given an N-dimensional matrix. Simply supply the matrix, where there is one measurement per cell. All the other parameters are the same as for anovan - so to perform repeated measures, use "random" on one of your matrix dimensions.

groupMeans Download

Group an n-dimensional array according to conditions specified in a identical-sized array. The conditions are categorical, and are used to divide the data into groups. Then the mean is taken for each group, along the specified dimension.

alignRight Download

Takes a matrix that has nan-padding, and "right-aligns" the values by removing trailing nans from each row. For example, if subjects (rows) have different numbers of trials (columns), you might have "nan"s in the last columns for some subjects. This function would allow you to look at the last trial, penultimate trial etc.

nanassign Download

Performs assignments like MATRIX(4,:)=VECTOR, but it avoids "dimensional agreement". Like "nancat", it pads missing regions with "nan". For example, if you are creating a matrix of subject x trial, you can use this to assign data from each subject.

removeIdenticals Download

Remove sequential repeated values in a vector.

findregions Download

Segments a vector by giving the starts and stops of sequences of repeated values.

matrixRowIndices Download

Allows you to index into a matrix, using a different column from each row. The vector of indices has the same size as the columnheight of the matrix, and each element corresponds to a row. The number indicates which column to extract.

smoothn Download

Smoothing that works along one dimension of an n-dim array. It is similar to using conv2 with a 1-dimensional filter

first Download

retrieves the first element of an array. Equivalent to X(1). Useful when chaining commands - allows you to extract the first value without storing the whole array anywhere. Was very useful before the find function allowed a count parameter.

flat Download

Flattens a matrix into a vector. Equivalent to X(:), but usefult when chaining commands.

nanzscore Download

Z-score that leaves nan as nan, ignoring those values when calculating the mean and standard deviation. this is useful for imputation, allowing "nan" to be replaced by "0" in some cases.

linspace Download

Wrapped the original "linspace" to allow vector endpoints, and thus generate linearly spaced vector outputs.

nan2zero Download

Converts nans to zeros, as though you had done "X(isnan(X))=0;". This is useful for removing nans within chained functions.

bool2nan Download

Converts 1s to nans, leaves 0s as 0s, as though you had done "X(X>0)=nan;". Useful for masking out unwanted values in a large matrix, e.g. RT+bool2nan(RT<0) removes negative RTs.

inversePermutation Download

Works out what permutation order you need, to get from one sequence to another. For example, the inverse permutation to get [1 2 3 4 5] from [1 5 2 3 4] is [1 3 4 5 2].

Structure operations

workspace2struct Download

Returns a structure containing all the variables and values from the current workspace - just as though you had performed "save;X=load".

struct2workspace Download

Dumps fields from the given structure into the current workspace.

transpIndex Download

Takes an array of structures, and puts the index of the structure inside onto the individual fields. In other words, it is like using catStruct to concatenate all the structures in the array, so that the fields have extra dimensions. Only works when the fields are numerical arrays.

removeIndexFromAllFields Download

In a structure whose fields are all arrays of the same length, (corresponding to trials for instance,) this allows a single element (trial) to be removed from each field.

catStruct Download

Allows concatenation of structures which have the same fields, by individually concatenating each of their individual fields. Only works when the fields are arrays.

ensureStructsAssignable Download

This creates an altered version of a structure to try and make it assignment-compatible with another structure - i.e. it creates fields that are missing. Both structures may need to be altered to make them compatible. This may be necessary if you want to concatenate two structures using [] or cat.

Simple graphical functions

Functions for simple data visualisation

errorBarPlot Download

The commonest task is to plot the means and standard errors of a set of data. This function takes means over dimension 1, plots dimension 2 as the x-axis, and dimension 3 as different lines. It uses either "errorbar", or else the "area" parameter can draw a shaded error region.

pairwiseComparisons Download

Takes a matrix of data, with subjects as rows (as for errorBarPlot), and performs pairwise comparisons across columns. A matrix is returned, or "plot_p" draws horizontal "comparison lines" and p-values over a previously drawn plot.

plotn Download

Calls plot, but accepts n-dimensional arrays. Can draw extra dimensions as different line colours, line-styles, or subplots, allowing 5 dimensions to be visualised. Can propagate the submatrices to any graph function, like "surf", errorBarPlot" or "imagesc"

correlateStructFields Download

Performs all pairwise correlations across fields in an structure-array

fitSigmoid Download

Fast simple fit and plot a sigmoid to data of various kinds.

histcont Download

Continuous histogram, like "hist". Uses sliding-window method to show frequency in each window, and is thus equivalent to a box-smoothed histogram. Operates on n-dimensional arrays, counting along the first dimension. Can return counts and do plot.

makeSubplotScalesEqual Download

Use with the usual subplot syntax, except an array in place of the plot number. It goes through each of those plots, and ensures the scales are equal.

makeXandYscalesEqual Download

For the current plot, make the X and Y axes the same.

colourMap Download

This generates a colour from the current gradient. If you want to have 7 colours from the spectrum, the third one is colourMap(3,7). Calling colourMap with a Nx3 matrix (or an existing colourmap) will set the current axis default colour order. Handy for colouring a sequence of lines on the same axis.

Reaction time functions

reciprobit Download

Plot a reciprocal probit plot of reaction times. Under this plot, a recinormal distribution appears as a straight line. This can separate trials by condition, and can plot the probit relative to the whole dataset, or relative to the individual conditions. Returns an intercept and slope of the fit line.

ehazard Download

Calculates an empirical hazard function. Works a bit like ecdf, but calculates the conditional probability of an event given it has not already happened.

vincentisedDelta Download

Plots a delta-plot of vincentised data. It takes the quantiles of the two reaction time distributions, and compares the values of the corresponding quantiles. It allows comparison of the shapes of two distributions.

generalRaceModel4 Download

This Monte-Carlo simulates an N-horse race between ballistic processes. It is optimised for fast sampling. It allows an arbitrary logic of start/stop/control when each process terminates, and can be used to predict multiple sequential responses and error-corrections.

generalRaceFit2 Download

This is a companion to generalRaceModel, and fits the a race model to a given dataset. Data is given as an RT matrix for each response-type, over a number of trials, and the model is run multiple times to obtain likelihoods of the parameters. Supported fitting algorithms include simulated annealing and genetic algorithm (with the appropriate matlab toolboxes). Experimental feature: can also be used to fit joint distributions of RT1 and RT2 when two responses occur in the same trial.

Eye movement analysis functions

These functions are designed for use with the Eyelink 1000 and the associated API. You will need a copy of edf2asc.exe supplied with the Eyelink to use the batch-conversion functions - ensure that the exe is 'on your path' - e.g. in the c:\windows\system folder.

readEDFASC Download

Convert the named edf file into a matlab structure. The structure will contain eye position, saccades and fixations as parsed by the Eyelink online parser, and any events sent to the eye tracker during the experiment. It uses an intermediate ASC file, and if the ASC already exists, it does not need the edf2asc program.

edf2ascAll Download

Runs the edf2asc tool on each file in a directory, creating the ASC files.

readAllEDF Download

Reads multiple EDF files from a single experiment, into a matlab structure. Designed for use with Sanjays experiment framework.

snipSaccades Download

A multi-purpose tool for epoching and analysing saccades and pupil data. Handles rotation/reflection/translation, saccade-related snipping, event-related snipping, baseline correction, blink removal +/- interpolation and more.

viewSaccadeData Download

This browses through each trial, displaying the both a screen-based plot and a time-based plot of the eye. Trial events and trial locations can be displayed from a parameter file, e.g. directly from Sanjays experiment framework.

Sanjay's Experiment Framework

These functions should provide a robust framework for developing experiments under PsychToolbox. The library does screen creation, eyelink initialisation, error handling, and runs a sequence of trials which can be automatically generated using a factorial design, with counterbalancing over the experiment.

RunExperiment Download

Actually runs the experiment.

createTrials Download

Create factorial design from the trial variables and block variables.

prepareScreen Download

Creates the screen window, loads image resources, and loads sound resources, into the experiment array.

LogEvent Download

Logs events in the experiment. Will ensure they are logged on eyelink also, if connected.

removeNonalphanumericChars Download

Does what it says.

WaitForFixation2 Download

Using eyelink, waits for the eye to remain on fixation spot for a given amount of time.

WaitForSaccade3 Download

Using eyelink, waits for a saccade to be made, of a given minimum size.
Importantly, it features