Day 07

Day 7: Data structures

Version: 6.10.2014

Command reference: Matlab syntax

pdf version of the script: [Tag07.pdf]

Word version of the script: [Tag07.docx]

Downloads:

T7A1) [katzen.mat]

T7B1) [celldemo.m]

T7B2) [experiment1.mat]

T7C1) [randomsquares.m]

T7C2) [random_squares_memory.m] [random_squares_load.m]

T7H1) [structuredemo.m], [make_exampledata.m]

Topics:

A) DATA STRUCTURES

If you want to manage complicated amounts of data, you quickly run into the problem that the situation becomes confusing when using variables of the types introduced in the course so far. Especially if you have to relate variables of different types to each other (e.g. names of test animals with their weight, their sex, information on whether they have ever given birth, the test condition used and the result obtained), you have to work very carefully to ensure that all vectors remain the same length, etc. If you also need all this information in several functions, you have to work very carefully. If you also need all this information in several functions, you have to pass all the variables in each case and must not mix up the order.

There is therefore a more practical way of solving such tasks: the data structure:

  • In a structure, you can combine several related variables into a single one, even if they have different types.
  • The variables within the structure are also referred to as"fields".
  • The structure can be easily passed between functions, where the relevant fields can be used and possibly changed.
  • A structure is obtained by specifying its fields with the syntax

structurname.fieldname=assignment

An example: You can imagine a structure like a rucksack: instead of carrying all your books, pens, handkerchiefs, wallet, USB stick etc. to university one by one and constantly checking that you still have everything with you, you stuff everything into the rucksack and take it with you. When you're sitting in a maths course, you use the USB stick, pens and paper from your rucksack, while you need your wallet in the canteen.

  • What could this structure look like?


The advantage of structures is that you can put together very meaningful combinations by choosing your own names (which you can usually still understand years later if you look at your old programme again).

The disadvantage is that you cannot simply search them linearly - e.g. the find command does not work for searching all fields of a structure and you cannot simply search all fields with a loop.

Tasks:


T7A1) In the example of the cats in the animal shelter, we saw that for some questions you have to relate different types of data to each other. We used several vectors or matrices there and combined them using the same indices. This approach works, but is not without danger:

Load the data on the cats again [katzen.mat] and sort the cats by age. What else is necessary so that you can query the other data about the cats?

T7A2) To keep all the data together, you introduce a structure in Matlab. A structure consists of several fields that can have different data types. For example, you could use the following structure to manage a mouse farm. The first mouse is created with:

mouse.earmark='M7777';
mouse.cage=5;
mouse.female=true;
mouse.litter-size=[5 8 7]
;

  • Display what is stored under mouse, mouse.cage and maus.wurfgroessen(2);
  • To add another mouse, you must give it an index:

maus(2).ohrmarke='M7735';
maus(2).kaefig=9;
maus(2).weiblich=true;
maus(2).wurfgroessen=[13 4 10 9];

  • Think of a few more mice and output
    • mouse
    • The cage numbers of mice 1 to 4
    • The size of the first litter of each of the first 3 female mice.


T7A3) No mouse lives forever. Write a function that deletes the correct entry in the structure maus when the ear tag is specified.

B) CELL ARRAYS

Closely related to structures are the so-called cell arrays. These can be used to manage lists of variables of different types, whereby the individual entries are not labelled with names (as with structures), but with indices. Cell arrays are therefore matrices, so to speak, in which different data types can be mixed.

You can imagine them as a kind of storage room in which the shelves are numbered consecutively and can contain very different things, which can be found quickly thanks to the numbering.

One advantage of cell arrays is that (unlike structures) they can be easily searched linearly by simply counting through their cells.

Their disadvantage is that they do not have descriptive names, but use numbers (just like matrices) to address certain data.

In addition to a typical example of the use of a cell variable, we want to deal with the special case of how to programme functions with a variable number of input or output parameters in Matlab. This requires the keywords varargin and varargout instead of explicitly marking the parameter names in the function header. varargin and varargout are then the names of a cell array of input and output parameters in the programme code. The number of arguments passed when calling the function can always be queried in every function (even if varargin and varargout are not used) in the programme text with the variables nargin (number of input arguments) and nargout (number of output arguments) automatically assigned by Matlab.

Matlab:

  • A single element of a cell array is accessed by indexing with curly brackets.
  • A{1}=[1 2 3]; % a cell array is created
  • A{2}='A B C D E';% and supplemented by more entries.
  • A{3}=logical(0)
  • A{2,2}=9 Cell arrays can also have several dimensions, so the one-dimensional cell array becomes a two-dimensional one and all entries missing from the complete matrix are set as an empty set [ ].
  • a=A{3,1}(2) % If vectors or matrices are stored in a cell array, individual elements can also be extracted from them. This is the second element of a cell array stored in A{3,1} stored in A{3,1}

Tasks:

T7B1) Complete the following example programme for using cell arrays from the Matlab course for doctoral candidates: [celldemo.m]

T7B2) An EEG measurement (EEG = electroencephalogram, measurement of brain waves) was carried out in a practical course. After the analysis (which we will ignore for now), the data was saved in Matlab in the file [experiment1.mat]. If you load this file, you will notice that it contains only one variable of the type cell (with 2 elements). This variable contains all the information relating to the experiment.

a) Load the file and take a look at the content of the cell variable:

  • The first element is a structure that contains the information about the experiment, such as the name of the original file and number of measurement points.
  • The second element contains the measured data.

b) Plot the data of each subject in a separate plot.

  • In each plot, the name of the respective subject should also appear as a caption (command: title). This can be found in the structure (1st element of the cell variable) in the Names entry.
  • Tip: Use a for-loop whose count variable can be used as an index for the data and for the name.

*c) The data represent the EEG signal in µV and were recorded at 500 Hz. Extend your programme by adjusting and labelling the axes of your plots accordingly.
*d) Create a new cell variable with the same structure as the previous one, but which only contains the data of the unique student subjects.

T7B3) Secondly, let's look at a special case of using cell arrays. Take a look at the following programme:

function [varargout]=testvar(varargin)

%Loop over all input arguments
for i=1:length(varargin)

%The input arguments are written to a vector :
x(i)=varargin{i};

end

%Loop over the output arguments, nargout is their number,
this variable is automatically set by Matlab with every function call and can be used in the programme code :

for i=1:nargout
varargout{i}=2*x(i);
end

  • Use this function with [a b c]=testvar(1, 2, 3,4).
  • Try other combinations of input and output arguments.
  • This example is actually quite a bad one, as it only works for variables of type double. Extend it so that all variables of all other data types are output unchanged.

C) APPLICATION EXAMPLE: STIMULATION IN A PSYCHOPHYSICAL EXPERIMENT

Various aspects of what you have learnt in this course will now be summarised in a task - controlling the stimulation of a psychophysical experiment.

T7C1) An example of visual stimulation in a simple psychophysical experiment is shown in the demo [zufallsquadrate.m].
Take a look at this programme and try it out. Make the following changes to the program step by step:

a) Determine a random colour for each "jump" that is assigned to the new square.

b) Let the user specify the duration of the pause as an additional argument.

c) Take the user specification of the pause as the maximum value and determine each individual pause randomly between 0s and this maximum value.

d) Make the user input of the pause optional. If the user enters a pause value, this will be used, otherwise 2sec will be used as the default value.

e) Change the probability of the position from a uniform distribution to a normal distribution around the centre of the figure.

T7C2) Often you want to know the exact parameters used in a stimulation, either to reproduce an experiment or to be able to analyse it exactly. This is particularly important for randomised stimulation.
A good way of storing the various parameters in a clearly organised way is to introduce a structure that contains all the important information. While the programme is running, this structure is filled and saved after the programme has finished. A corresponding version of the stimulation with random squares can be found in [zufallsquadrate_speicher.m]. This data is loaded and reproduced with [zufallsquadrate_laden.m]. Take a look at both programmes and try to understand how the structure is handled.

a) At the moment, the parameters are always saved under the name'zufallsquadparameter.mat' . This means that this file is overwritten if it is called up several times.
Change the function random_squares_save so that the user can specify a file name of their choice as an argument.

b) Extend the function so that the user can specify a file name (which is then also used for saving) or not.
If no file name is specified, the function saves the parameters in the file 'standard.mat'

c) As in the last task, assign a random colour to the square, which is also saved in each case.

d) Extend your function with an additional argument that allows you to choose whether

  • you want to have random colours,
  • or only red, blue and green squares.
  • If the option with only three colours is selected, make sure that they appear in random order, but that each of the colours is shown the same number of times (or that a colour appears once more or less frequently if the number of repetitions is not divisible by 3).

e) Customise the function random_squares_load to the changes in random_squares_store function.

MAIN TASK:

Command reference: Matlab syntax

*T7H1) For the advanced Matlab course, I have written demo programmes to illustrate the use of structures. Please follow the functionality:

T7H2)[CellRespMat.mat] contains responses from 20 nerve cells in the retina whose activity was recorded in an experiment and stored in this 3D matrix. The first dimension of the 3D matrix corresponds to the 20 cells, the second to time (500 time steps of 1 ms each) and the third dimension to the stimulus presentation (192 presentations of the same stimulus). E.g.: r=CellRespMat(5,100,45) is the 100th time step of the response of cell 5 at the 45th stimulus presentation. For each time step, each cell responds with 0 (no spike) or 1 (spike). The cells respond to 192 light stimuli (patterns on the screen) that moved to the left or right with equal probability. The direction of the respective movement stimulus is stored in a vector:[sigma.mat](-1 means left, 1 means right).

  • Look at the data in the Array Editor or as a graphic. To do this, you must reduce the data to 2D matrices. The squeeze command turns a "slice" of a 3D matrix into a real 2D matrix, e.g. M=squeeze(CellRespMat(5,:,:)); contains all time points of all presentations of cell 5.
  • Consider a suitable way of storing the measurement data together with the associated stimulation by using cell arrays or structures to make it easier to handle the data.
  • Hints:
    • The way you organise data is always a matter of taste - there is not just one right or best solution).
    • sparse() only works for 2D matrices!

*T7H3) (corresponds approximately to T4H5, can be modified by your own solution)

A circle (which is actually a 360-angle) is created with Matlab as follows:
degrad = pi/180;
w=0:1:360;
si=sin(w*degrad);
co=cos(w*degrad);
plot(co,si)

If you try this out, this circle looks pretty much like an egg. axis equal makes the axes square, so it's nicer to look at.
A closed line like this circle can be filled with a colour using the fill(x,y,farbdef) command. Colours are defined either with the abbreviation also used for the plot command (e.g. y for yellow etc) or with the help of RGB coding.

  • Create a structure that contains all relevant information for the various circles (or other n-corners).
  • Draw a square, a 3-corner, a 7-corner and a 25-corner in the same way.
  • Try out how to change the size and direction of these figures.
  • *) You only have to change the programme slightly to draw a five-pointed star in one go. How?

**T7H4) Starry sky (corresponds approximately to T4H6): You want to draw a pretty colourful filled starry sky with different sized, colourful filled stars (or optionally other N-corners) with different numbers of corners against a dark blue background.

  • a) Think of a structure in which you can store all the relevant information about your stars.
  • b) Draw the starry sky with several stars of different colours.
  • c) Embellish your starry sky so that it fills the entire screen. (Use the help to find out how to do this).
  • d) Draw your stars in random places in the sky.
  • e) You can use the starry sky as a kind of screensaver.
    • At first the stars are coloured as described above.
    • Then, after a short pause, the stars turn yellow in random order.
    • When all the stars are yellow, they return to their original colour in random order.
    • This colour change is repeated until the user cancels the program.
    • f) Save the sequence of your celestial phenomena in a file using a meaningful structure. Write a programme that repeats the sky show in the same way.
    • ***g) Make sure that the different stars do not overlap.

To the 8th day of the course

(Changed: 24 Jun 2026)  Kurz-URL:Shortlink: https://uol.de/p36847en
Zum Seitananfang scrollen Scroll to the top of the page

This page contains automatically translated content.