Back to Main Page

Introduction to Matlab Practical

Dr Lincoln Colling

Recap of Lecture

In lecture 1 we covered: - The basics of the Matlab interface - Variables - Basics of scripts

Aims of Practical

In the practicals we're going to get some hands on experience using Matlab

Practical One

Getting familiar with the Matlab interface, typing commands in the command window, basic mathematical operations, running functions, and drawing plots

Practical Two

Programming up a complete experiment in PsychToolBox and collecting some real experimental data.

Practical two will happen after you've had all the lectures, so you're encouraged to explore Matlab on your own between the end of the lectures and the second practical

The Matlab interface

Using Matlab as a calculator

Any commands you type into the Command Window are run immediately.

Try this out by typing some simple calculations into the Command Window at the command prompt (>>)

When you don't specify an output variable then Matlab automatically saves it to a variable called ans
>> 5 + 6

    ans = 

But you can also specify where to save it. Here we're saving it to a variable called x
>> x = 5  + 6

    x = 

Notice that the output is automatically printed at the command window. You can suppress this output by adding ; to the end of the command
>> x = 5 + 6;

This works whether the command is typed in directly, is part of a script, or is part of a function.

You can enter multiple statements on one line by using ; or , between the commands

>> x = 1; y = 2;
>> y = 1, y = 2

y =


y =



Mathematical operations in Matlab

Symbol Operation Example
+ Addition 2 + 2
- Subtraction 2 - 2
* Multiplication 2 * 2
/ Division 2 / 2
^ Exponent 2^2
sqrt() Square root sqrt(2)

Order of operations
  • Matlab executes operations in the same order you learned in high school: Exponents, Multiplication, Division, Addition, and Subtraction.

  • You can change the order by using brackets/parentheses ()

>> 1 + 2 * 3

ans =


>> (1 + 2) * 3

ans =



Working with variables

You can create Matlab variables using the assignment operator, which is just an equals sign (=).

>> y = 'string';
>> y 

y =

Once you have assigned a variable you can overwrite just by reassigning it.

>> x = 1;
>> x 

x = 
>> x = 'one';
>> x

x =

Keeping track of variables

>> x = 1; y = 2;
>> whos
  Name      Size            Bytes  Class    Attributes

  x         1x1                 8  double              
  y         1x1                 8  double              
>> who

Your variables are:

x  y 
>> clear
>> who

clc clears the Command Window but leaves the Workspace untouched

Error messages

If you do something wrong then Matlab will let you know!

>> x = 1;
>> 4x
Error: Unexpected MATLAB expression.
Did you mean:
>> 4*x

If you've typed the command incorrectly, you can just hit the up arrow (↑) and the last command you've typed will show at the command prompt.

Running scripts

  • You can run scripts just by typing the name of the .m file at the command window.
  • If we had a script called SayHello.m then we can run it by typing it's name without the .m
>> SayHello

Using functions

  • Functions are run the same way as scripts, but often we'll need to specify inputs and outputs
  • You can specify the inputs directly, or by passing variables to the function.
  • Multiple outputs are put inside [/]
>> MyFunction(100);
>> x = 100;
>> MyFunction(x);
>> [Output1 Output2] = MyFunction(x);

Generating random data

  • We want to explore some plotting functions so we'll need to generate some fake data!
  • To do this, we'll use:
    • The standard way for generating vectors: [start_number : step : end_number]
    • The randn() function. This takes two inputs: [1] the length of the output [2] the width of the output.

First we'll generate a sequence of numbers and then we'll add some noise.
plasticInTheSea = [10 : .1 : 21.9] + randn(1,120);
Second we'll generate two correlated sequences of numbers.
condition1 = randn(60,1); % generate a 60 x 1 matrix
condition2 = condition1 + (randn(length(condition1),1)); 

Drawing plots

  • Matlab can generate many types of plots.
  • Use figure to open a new window for plots
  • Plotting commands typed at the command prompt (>>) will show up in the window
  • Each new plot you generate by defaults overwrites the previous plot, but there is a special command to prevent this behaviour

Line plots
  • The first plot we'll draw is a line graph using the plot() function
>> help plot
 plot   Linear plot. 
    plot(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
    then the vector is plotted versus the rows or columns of the matrix,
    whichever line up.  If X is a scalar and Y is a vector, disconnected
    line objects are created and plotted as discrete points vertically at
    plot(Y) plots the columns of Y versus their index.
    If Y is complex, plot(Y) is equivalent to plot(real(Y),imag(Y)).
    In all other uses of plot, the imaginary part is ignored.
    Various line types, plot symbols and colors may be obtained with
    plot(X,Y,S) where S is a character string made from one element
    from any or all the following 3 columns:

Try it out!

>> figure;
>> plot(plasticInTheSea);

Now we'll try make it look nicer

ylabel('Amount of plastic in oceans (Megatonnes)'); % rename the y
set(gca,'XTick',0 : 12 : 120); % remove some of the xticks 
% if you're using Matlab 2017 then you can use
% xticks(0:12:120) instead

set(gca,'XTickLabel',1999 : 2009); % re-style x-axis
% if you're using Matlab 2017 then you can use
% xticklabels(1999:2009)

ylim([0 30]); % change the axis limits

% add a title.
% Notice what we do to handle ' in a  string
title('Increasing levels of plastic in the world''s oceans (1999-2000)');

% add a title.
% Notice what we do to handle ' in a  string
title('Increasing levels of plastic in the world''s oceans (1999-2000)');

And save it to an image

% tell matlab to [g]et [c]urrent [f]igure and save it to disk
saveas(gcf,'ocean-plastic.png') % save it to an image

Scatter plots
  • Next we'll draw is a scatter plot using the scatter() function
>> help scatter
 scatter Scatter/bubble plot.
    scatter(X,Y,S,C) displays colored circles at the locations specified
    by the vectors X and Y (which must be the same size).  
    S determines the area of each marker (in points^2). S can be a
    vector the same length a X and Y or a scalar. If S is a scalar, 
    MATLAB draws all the markers the same size. If S is empty, the
    default size is used.
    C determines the colors of the markers. When C is a vector the
    same length as X and Y, the values in C are linearly mapped
    to the colors in the current colormap. When C is a 
    length(X)-by-3 matrix, it directly specifies the colors of the  
    markers as RGB values. C can also be a color string. See ColorSpec.

Try it out!

>> figure;
>> scatter(condition1,condition2)

Or try add a little styling (make the dots red and filled)

>> scatter(condition1,condition2,'r','filled')
Now we'll try make it look nicer. You can use the same commands you used previously. E.g:
  • xlim([min max]) and ylim([min max])
  • xlabel(string) and ylabel(sting)
  • set(gca,'XTick',..) and set(gca,'YTick',..)
  • set(gca,'XTickLabel',..) and set(gca,'YTickLabel',..)

Bar plots
  • Now we'll draw bar plots with the bar() function
>> help bar
 bar Bar graph.
    bar(X,Y) draws the columns of the M-by-N matrix Y as M groups of N
    vertical bars.  The vector X must not have duplicate values.
    bar(Y) uses the default value of X=1:M.  For vector inputs, bar(X,Y)
    or bar(Y) draws LENGTH(Y) bars.  The colors are set by the colormap.
    bar(X,Y,WIDTH) or bar(Y,WIDTH) specifies the width of the bars. Values
    of WIDTH > 1, produce overlapped bars.  The default value is WIDTH=0.8
    bar(...,'grouped') produces the default vertical grouped bar chart.
    bar(...,'stacked') produces a vertical stacked bar chart.
    bar(...,COLOR) uses the line color specified.  Specify the color as one of
    these values: 'r', 'g', 'b', 'y', 'm', 'c', 'k', or 'w'.

Let's try it out. We'll plot the first bar first...
bar(1,mean(condition1)); % plot the average of condition 1
... and then we'll plot the second bar. But first we use hold on so we don't overwrite our first bar
hold on;
bar(2,mean(condition2)); % plot the average of condition 2
set(gca,'XTick',[1 2])
set(gca,'XTickLabel',{'Condition 1','Condition 2'})
ylabel('Amount of variable (units)')

bar(1,mean(condition1)); % plot the average of condition 1
hold on;
bar(2,mean(condition2)); % plot the average of condition 2
xticks([1 2]) % matlab 2017
set(gca,'xtick',[1 2]) % matlab 2016
set(gca,'XTickLabel',{'Condition 1','Condition 2'});
ylabel('Amount of variable (units)')

Error bar plots

  • Bar plots are common, but they're not very useful
  • One better way to visualise the data is with a dot plot with error bars
  • To do this, we'll mix the errorbar() plot and the scatter() plot

Building an error bar plot

First we'll need to write a function to calculate a confidence interval.

We'll use the formula: CI=1.96×σn CI = 1.96 \times \frac{\sigma}{\sqrt{n}}

  • remember, we can count the length of vector using length()
  • we calculate n\sqrt{n} using sqrt()
  • and we can calculate the standard deviation (σ\sigma) using std()
function ci = MyCiFun(input)

    n = length(input);
    sd = std(input);
    ci = 1.96 * sd/sqrt(n);

Now we can incorporate the output from MyCiFun.m into the errorbar() function

scatter(1,mean(condition1),'b'); hold on;
set(gca,'XTick',[1 2])
%xticks([1 2])
set(gca,'XTickLabel',{'Condition 1','Condition 2'});
%xticklabels({'Condition 1','Condition 2'})
ylabel('Amount of variable (units)')
xlim([0 3]);
errorbar(1, mean(condition1),   MyCiFun(condition1), 'b')
errorbar(2, mean(condition2),   MyCiFun(condition2), 'r')