# Matlab Syntax

## Introduction

Matlab is a powerful, flexible programming language for scientific computing. It is a high-level interpreted language, meaning reading and writing Matlab is easy.

### Variables

One of the most basic concepts in computer programming is the variable. A variable is a word/identifier that hangs onto a single value. For example, let’s say you needed the number 5 for your program, but you’re not going to use it immediately. You can set a variable, say my_variable, to grab the value 5 and hang onto it for later use, like this:

``````my_variable = 5;
``````

A few more examples:

``````participants = 10;
hearing_threshold = 25;
``````

Declaring variables in Matlab is easy; you just write out a name/identifier, like my_variable, and use = to assign it a value. (The semicolon tells Matlab that you don’t want the result printed in the command window. If you just assign a value, you probably don’t need Matlab to repeat the value.) We can now summon the value 5 by calling out the name my_variable whenever we need it.

MATLAB stands for MATrix LABoratory and makes it easy to work with large arrays of numbers, such as vectors or matrices, at the same time. You can easily assign more than one number to a variable – just put them between square brackets:

``````results = [1,2,20,4,12,9,5];
``````

MATLAB has a special notation for generating sequences of numbers. Just put a colon (:) between the starting number and the ending number. For instance 1:10 will be expanded into 1,2,3,4,5,6,7,8,9,10. Other examples:

``````sequence = [1:100];
included_participants = [3:12];
``````

These values are all in a row, but we can have several rows, or in fact any number of dimensions:

``````matrix = [1,2,3; 4,5,6]
matrix =
1     2     3
4     5     6
``````

### What’s a statement?

You can think of a Matlab statement as being similar to a sentence in English: it’s the smallest unit of the language that makes sense by itself. Variables and data are some of the building blocks that form statements. To continue the sentence analogy, it’s clear that we also need a kind of punctuation to make it obvious where one statement ends and another begins. In Matlab many statements are terminated with a semicolon or the word ‘end’, like so (don’t worry about understanding the keywords, we’ll get to those soon):

``````if hearing_threshold > 10  % elevated thresholds may signal hearing problems
second_test = 'yes';   % better do a second test
end
``````

Matlab comes with a handy integrated development environment (IDE), which means you have several tools at your fingertips that make programming easier, such as a console window, a script editor, and a debugger. The IDE takes the code you write, checks it for syntax errors, and executes the statements line by line.

You may have noticed the instructions in the editor that begin with a `%` (percent) symbol. These lines of code are called comments, and they aren’t read by the interpreter—they don’t affect the code at all. They’re plain English (or French, etc.) comments written by the programmer to provide instructions or explain how a particular part of the program works.

Comments improve the readability of your code tremendously and will help you debug programs more quickly, since you’ll be able to tell at a glance what each part of the program is supposed to do. Always keep in mind that someone else may have to work with your code, or you might come back to it after a few months. Well-commented code is easy to maintain and re-understand. I encourage you to comment on your code whenever its purpose isn’t immediately obvious.

### Arithmetic Operators

Matlab can perform a range of arithmatic computations. Here are some examples:

• Subtraction (-)
• Multiplication (*)
• Division (/)
• Exponentiation (^)
• Trigonometry (sin,cos,tan,…)
• logarithms (log,log10,log2)

At its simplest, we can use MATLAB as a calculator:

``````3+2

ans =

5
``````

If yo have access to MATLAB, try at least 10 simple computations on the command prompt using most of the functions listed above. Use variables, like so:

``````tax = 8; % percent
tip = 15; % percent
meal = 25; % dollar
total = meal + (meal * tax/100) + (meal * tip/100)
``````

You can see a complete list of in-built elementary arithmatic functions by typing: `help elfun`

### Getting help

MATLAB has two inbuilt commands to print the documentation for any function, `help` and `doc`. Help prints the documentation in the command window, while doc opens a window, but otherwise shows the same information. Try this:

``````help sin

SIN    Sine of argument in radians.
SIN(X) is the sine of the elements of X.

Reference page in Help browser
doc sin
``````

If you do not know the name of the function, yo can use the ‘lookfor’ command to search all the documentation and print a list of functions that contain the keyword you searched for:

``````lookfor filter
dfilt                          - Digital Filter Implementation.
fdesign                        - Digital Filter Design.
filtstates                     - Filter States object.
filter                         - One-dimensional digital filter.
filter2                        - Two-dimensional digital filter.
``````

That said, searching the internet with a specific MATLAB question usually gives you some pointers or ready-to-use programs. MATLAB has a very large user base and most problems that you come across as a beginner (and even advanced user) have been soved many times over.

### Strings

Another useful data type in MATLAB is the string. Strings are, well, strings of characters, which is a more formal way of saying they’re really just regular language phrases. They can include numbers, letters, and various symbols, like so: ‘MATLAB is easy’. A string is created by just writing it down between single quotation marks. Go ahead and try it: `my_string = 'Hello world!'`

Some symbols can’t be used in a string (for instance the quotation mark itself, because it is marks the begining and end of a string), and some results can only be achieved by special characters. To include these characters in a string they must be “escaped”", or marked as unique. The backslash character (`\`) does this work for us! We just put it directly before the character we want to escape. For instance `\'` is equivalent to a quotation mark in a string; `\t` is a tab; `\n` (for new line) put the subsequent characters on a new line.

``````my_string = 'The world\'s end';
two_lines = 'First. \nSecond.';
``````

### Displaying text

At some point in your program you will probably want to display a result or some other text. This is easy to do in MATLAB. The ‘disp’ command is convenient for simple text printing: `disp('Calculating cortical surface…')`. The disp command takes a string or a variable containg numbers as input and prints it on the command line.

``````grey_matter_density = [25,30,21,19,32];
disp('The measured density of cortical gray matter for each sample is:');
disp(grey_matter_density);

The measured density of cortical gray matter for each sample is:
25    30    21    19    32
``````

Another, more flexible, command to print text is `fprintf`. Have a look at it’s help info and see how it differs from `disp`.

### Matrix Slicing

You can access some of the values stored in a variable directly. For instance, in the example above, if you are interested in the third entry in `grey_matter_density`, you can type:

``````grey_matter_density(3)
ans =
21

% This will show the third and the fourth entry:
grey_matter_density([3,4])
ans =
21  19

% The third and fouth entry in reverse order:
grey_matter_density([4,3])
ans =
19  21

% You can use the colon operator to generate a sequence of
% indices. Here are all values from the second to the fifth:
grey_matter_density([2:5])
ans =
30    21    19    32
``````

A practical example is extracting date and time values from the output of MATLAB’s `clock` function:

``````a = clock
a =
1.0e+03 *
2.0130    0.0120    0.0090    0.0190    0.0350    0.0402

year = a(1)
year =
2013

month = a(2)
month =
12

day = a(3)
day =
9

hour = a(4)
hour =
19

minutes = a(5)
minutes =
35

disp([num2str(day),'.',num2str(month),'.',num2str(year)])
9.12.2013
``````

The last line is a nicely formatted version of the date when I wrote this portion of the tutorial. Don’t worry about `num2str` at the moment (you can always look it up in the help).

## Flow Control

### Conditionals

Program manipulate data and often take decision based on conditions. The easiest way to take a decision in MATLAB is using the `if` command. Here’s an example of if statement syntax in MATLAB:

``````if 8 < 9
disp('Eight is less than nine!');
end
``````

If is always followed by an expression that can be true or false. The code between `if` and `end` is executed if the expression evaluates to True. If the expression is false, then the interpreter just skips the code and continues with the next line after `end`.

For more control you can add `elseif` and `else`. The full syntax would look something like this:

``````IQ = 110;
if IQ > 120
disp('You're a genius!');
elseif IQ > 100
disp('Pretty smart for a carbon-based life form!');
else
disp('Are you sure you want to take this course?');
end
``````

Practise if statements a bit until you are comfortable with the way they work. For instance, print a warning message if a value is larger or smaller than a certain threshold.
There is a second, similar control structure in MATLAB, which starts with the command `switch`. Use the help function to find out how it works and come up with an example where it would make more sense to use `switch` than `if`.

### Loops

#### While

The while loop is similar to an if statement: it executes the code inside of it if some condition is true. The difference is that the while loop will continue to execute as long as the condition is true. In other words, instead of executing if something is true, it executes while that thing is true.

`while count < 5` decides when the loop will be executed. So, “as long as count is less than 5,” the loop will continue to execute. `count = count + 1;` increases count by 1. This happens over and over until count equals 5.

``````count = 0

if count < 5
disp('Hello, I am an if statement and count is');
disp(count);
end

while count < 5
disp('Hello, I am a while and count is');
disp(count);
count = count + 1;
end
``````

At this point it’s useful to know that you can stop the MATLAB interpreter by holding down the the CONTROL utton and the C button at the same time. For instance, if you were to remove the `count = count + 1;` line from the previous script, then the wile loop would never terminate (count would not increase and thus never become greater than 5). The loop would run until the end of time (or at least until you close MATLAB).

A common application of a while loop is to check user input to see if it is valid. For example, if you ask the user to enter y or n and they instead enter 7, then you should re-prompt them for input. A slightly different example. See if you can figure out how to which response will allow you to get out of the loop:

``````choice = input('Enjoying the course? (y/n)','s');
while choice ~= 'y'
choice = input('Wrong answer! Try again (y/n): ','s');
end
``````

The `input` command prints a question and records text entered at the command line into a variable (see it’s help for more information). The `~=` operator stands for “”not equal to”.

#### For

An alternative way to loop is the for loop. The syntax is as shown; this example means “for each number i in the range 1 to 10, display i”:

``````for i = 1:10
disp(i);
end
``````

This kind of loop is useful when you want to do something a certain number of times. An example are the trials in a psychphysical experiment, where each trial consists of a stimulus presentation and a response measurement. For instance (greatly simplified):

``````num_trial = 25; % we present 25 trials
responses = zeros(1,num_trials); % this array will be filled with the responses

for trial = 1:num_trials
% present the stimulus
beep;
# get the response for the current trial
responses(trial) = input('Did you hear the sound? ','s');
end

disp('The responses were:');
disp(responses);
``````

## Functions

You have already seen some functions above, such as `sin` and `log`. MATLAB has a very large number of built-in functions than can do all sorts of things, not just arithmetic. The general anatomy of a MATLAB function is `output = function_name(input);`. For instance, the function `len` returns the length of a variable:

``````a = [1,3,10,5,98,45,8];
% this will print the lenght in the command window:
len(a)
% We can also assign the length of a to a new variable:
length = len(a);
``````

Some functions require no input. Try `why` (someone at MathWorks had a good time). You can get help on what a function does and what its inputs and outputs are by `help`:

``````help len
% help itself is also a function, so you can ask it about itself:
help help
``````

You can look at the code for a function, use the `type` command. For instance, let’s take a closer look at the function that calculates the mean of two or more numbers:

``````%This will print the mean of 23 and 45:
mean(23,45)
% We can also calculate the mean of a matrix:
a = [23,45,76,19,51];
mean(a)
% MEAN can do many other things. Lets look at its help:
help mean
MEAN   Average or mean value.
For vectors, MEAN(X) is the mean value of the elements in X. For
matrices, MEAN(X) is a row vector containing the mean value of
each column.  For N-D arrays, MEAN(X) is the mean value of the
elements along the first non-singleton dimension of X.

MEAN(X,DIM) takes the mean along the dimension DIM of X.

Example: If X = [1 2 3; 3 3 6; 4 6 8; 4 7 7];

then mean(X,1) is [3.0000 4.5000 6.0000] and
mean(X,2) is [2.0000 4.0000 6.0000 6.0000].'

% The see the code for the MEAN function:
type mean
function y = mean(x,dim)
%MEAN   Average or mean value.
%   For vectors, MEAN(X) is the mean value of the elements in X. For
%   matrices, MEAN(X) is a row vector containing the mean value of
%   each column.  For N-D arrays, MEAN(X) is the mean value of the
%   elements along the first non-singleton dimension of X.
%
%   MEAN(X,DIM) takes the mean along the dimension DIM of X.
%
%   Example: If X = [1 2 3; 3 3 6; 4 6 8; 4 7 7];
%
%   then mean(X,1) is [3.0000 4.5000 6.0000] and
%   mean(X,2) is [2.0000 4.0000 6.0000 6.0000].'
%

if nargin==1,
% Determine which dimension SUM will use
dim = min(find(size(x)~=1));
if isempty(dim), dim = 1; end

y = sum(x)/size(x,dim);
else
y = sum(x,dim)/size(x,dim);
end
``````

The `type` command prints the code of the function in the command window. Most MATLAB functions are just text files with MATLAB code in them. This means that you can write your own functions and use them like you would use any of the built-in ones. This is easy to do. You begin with a function declaration in the first line, like so: `function outputs = function_name(inputs)`. Then come a few lines of comments (starting with `%`) which contain help text. The `help` function actually only prints those first commented lines in the command window! So if you start with a comment, the help function will automatically work on your your function! After the comments comes the main code that processes the inputs and generates the outputs. Here are a few examples:

``````function addtwo(x,y)
%               print the result = x + y
x+y

function s = area(a,b,alpha)
% AREA calculates triangle’s area given 2 sides & angle between them
% AREA reads in two sides of the triangle and the angle between them
% (in radians) and returns the area of the triangle.

if a < 0 | b < 0
error(‘a and b can not be negative.’)
end
s = a * b * sin(alpha) / 2;
``````

MATLAB cannot execute a function unless it knows where to find its m-file. The text file for the function has to be in the MATLAB path or in the current directory (there are buttons for both in the menu ribbon).

## Closing remarks

I encourage you to pracise these concepts a bit. You can find exercises and further tips and guidelines by search the web for `matlab getting started`, `matlab introduction`, `matlab exercises`, etc.

See you in the course!