Till KTH:s startsida Till KTH:s startsida

Introduction to Matlab

Short introduction to MATLAB

MATLAB is a system that was originally developed for processing of matrices using a compact notation. Since images can be represented as matrices Matlab can in this respect be used for image processing.

However, MATLAB is suitable for operations that can easily be expressed in terms of matrices. As you will notice, this has affected the design of the labs for this course.

Dokumentation

MATLABs embedded help functionality works as follows. If you write

helpyou will get a list of a large number of topics, under which all embedded commands (and a short description of some key concepts) have been collected. This list is hierarchically organised. If you then writehelp topicwhere topic is among the headlines of this comprehensive list, you get a list of all the commands associated to this topic. Finally, if you writehelp commandyou get specific information regarding a particular command. Some of the commands/topics that will be most relevant to this course are arith, axis, clear, close, colon,color, colormap, diary, figure, for, function, help, if, image, input, keyboard, linspace, load, ones, paren, pause, plot, print, punct, relop, save, script,showgrey, size, slash, title, while, and zeros. 
Test it yourself!

Storage in files

Variables in MATLAB can be stored as files using

save filename x y zwhich results with a binary representation of the variables x, y och z being written to the file filename.mat. These can be used in a new MATLAB-session byload filenameNote that the variables stored previously with the same name will be overridden. To check which variables are defined dowhoIf you want to know the size of the variables, writewhos

Displaying images

Images may be displayed with image or showgrey (for grey level images). The images that are to be displayed, as well as histograms and other graphical contents, will be drawn in so called figure windows. The first such window is created as soon as it is needed. Additional windows, to display multiple images simultaneously, can be opened with

figureAll graphical contents will be drawn in the currentfigure window. This is usually the last opened figure window, or the window that was activated last, e.g. by clicking onto it, making it the window in the foreground. If you like a particular window, say window number id, to become the current window, just writefigure(id)Commandcloseterminates the current window whileclose(id)terimates window with number id. With the command subplot, a few different illustrations can be displayed in a single figurehelp subplotCommandtitle(sprintf('Titel: (arg1, arg2) = (%d, %f)', intarg, floatval))can be used to give an informative title for your figure, including the parameter setting used to generate it.

Printing out

What is shown in a figure window can be printed out onto a laser printer named skrivarnamn using

print -PprinternameYou can also store store files in the POSTSCRIPTformat to a file filename usingprint -deps filenameBefore you print out the image you might want to complement it with a title or change the coordinate axes. The commandtitle textsträngassigns the title string to the current figure. Coordinate axes can be drawn usingaxis onand removed withaxis off

Keeping a diary

In some cases it might be appreciated to keep all input commands and results in a diary file, such that the Matlab-session can later be recreated. This is done by writing

diary filnamnwhich makes Matlab copy all inputs and outputs (visible in the command window) to the file filnamn. Once a diary is opened it may be closed or reopened with diary off anddiary on.

Scripts

A {\sc Matlab}-script is a file containing a series of Matlab commands. A script-file must have a name similar to scriptname.m. When you type

scriptnamein the Matlab command window (or in another script or function) the series of commands in the script-file will be executed in the same way as if you wrote the same commands directly in the command window (at the prompt). Thus the script may affect the Matlab variables stored in memory.

To speed of the presentation of your labs you ought to create a script such that the most important steps of the labs can easily be reproduced . For the purpose of presentation you might want to interrupt the script at strategical points of execution, such as the partial results can be more closely inspected. This can be done using the commandskeyboard, pause and input. In many cases the first command is preferable, since it allows Matlab's command window to be accessed.

In many cases, a practical way of creating a script-file is by first investigating the methods using the command window with a diary activated, manually edit the diary-file once it has been deactivated, and then successively update the script until it can be executed in its entirety. (To prevent interference with some global variables you better reset these before every execution using clear variabelnamn.

Functions

A function in Matlab very much works like a script. The difference is that a function

  • uses local variables,
  • accepts input arguments,
  • returns (one or many) output variables

A function that accepts two different input arguments and returns a single variable has a declaration similar tofunction utdata = functionname(indata1, indata2)while a declaration of a function that returns three variables, without any input arguments, will be written asfunction [utdata1, utdata2, utdata3] = functionname()In the function-file the arguments are treated like ordinary Matlab variables. Results are returned by assigning a value to the output variables (see below).

Search paths

For Matlab to find a particular requested file, such as a file containing Matlab variables, a Matlab script or function, the file has to be placed either in Matlab's current working directory or among the directories included in the search paths.

You may output Matlab's current working directory with the command pwd and change it with cd. You may also, within Matlab, see the current search paths of the system, as well as change these, using the command path . (If you need any help, just use the help-function).

If you create your own library of Matlab functions and scripts, you might want to include these to the search paths. On CSCs Unix computers this can be done by updating the environment variable $MATLABPATH in your .login-file or by creating your own module-file (see /info/bildat12/module/bildat12 for an example of how to create module-files).

Suppression of outputs

If a command (usually a line) ends with a semi-colon ;, the results are suppressed from being output. This is practical if you are working with large images, that would otherwise fill up your screen with endless rows of numbers. This is also the case for most scripts and functions.

Comments

If a command line (e.g. in a script or a function) is preceded by a percent character, the rest of the information on this line will be ignored. In fact, Matlab's embedded help -function is based on such comment lines. The command

help matlabfilewhere matlabfile.m is a script- or function-file, prints out the first unended sequence of comment lines found in this file. You may thus use the help-function also for your own functions and scripts. Just remember that the first line in the function-file needs to include the declaration of the function (see above).

Syntax and computational efficiency

The notation in Matlab was primarily developed for treatment of matrices and vectors using a compact notation. There are a number of common constructions that allows you to avoid explicit loops and thus increase the computational speed. Since Matlab is an interpreting system, you should try to use these constructions whenever it is possible. Some examples:

  • Arithmetic sequences are generated using a colon : or linspace, as for examplex = (1 : 2 : 97) 
    x = linspace(1, 97, 48)
  • Colons can also be used to extract subsets of vectors and matricesx(1 : 5 : 16)
  • Constant matrices are easily generated with zeros and ones17 * ones(3, 4)
  • Multiplications of matrices are written with * and element-wise multiplication with .*ones(2 : 3) * ones(3 : 4)
  • Matrices and vectors are concatenated using parentheses [ ]. Spaces or commas separate elements within a line, while semi-colons work as separators between lines. An {apostrophe 'denotes a transpose. An example with a matrix created using these operators is
    y = [[ones(1, 2), zeros(1, 2); linspace(1, 2, 4); 1 2 3, 4]' ...
         17*linspace(3, 81, 4)' * [0.1 0.2]]
    

As you see, like in most other languages, you may choose a notation that is more or less readable for the less experienced user. Thus, choose a programming style that is easy to read!

If you still have to write an explicit loop, you should try to avoid making your function too slow, by allocating all necessary memory outside the loop, instead of inside it. For example, compare the following two constructions

clear x;
for n = 1:10000
  x(n) = n*n;
end

for n = 1:10000
  x(n) = n*n;
end

In the first loop considerably more CPU time will be needed than in the last one, since the vector x is reallocated in every iteration in the first case, while it already is of sufficient length when the second loop is executed.

None of the above solutions are satisfactory, of course. Assignment like to those done above should in Matlab be done with the embedded functionality:

tmp = (1 : 1 : 10000); 
x = tmp .* tmp;

Coordinate systems

In image processing and computer vision there are a number of different conventions for coordinate systems. During the seminars, as well as in the book of Sonka, we use a Cartesian coordinate system with a horizontal right-sided $x$-axis and a $y$-axis vertically pointing straight up. However, the coordinate system in the book of Gonzalez \& Woods and in Matlab is rotated 90 degrees in relation to the system we use, i.e. the first coordinate axis points downwards and the second one horizontally to the right.

How matrices are defined and accessed in Matlab will be highlighted by a simple example. This example shows how the ASCII-based image format is defined as a function that returns an image matrix as output.

function pixels = matlabcoordimage()

% Test image with imax = 3, jmax = 4 and pixel values
% pixels(i, j) = 10*i + j
% where i and j are Matlab indeces as they
% are used for accessing matrix elements

pixels = [11 12 13 14; ...
          21 22 23 24; ...
          31 32 33 34];

To create a corresponding image in \sc Matlab where the values instead reflect the image points in Cartesian coordinates, you write:

function pixels = cartesiancoordimage()

% Test image with xmax = 4, ymax = 3 and pixel values
% f(x, y) = 10*x + y
% where x and y are Cartesian coordinates
% as they appear on the screen

pixels = [13 23 33 43; ...
          12 22 32 42; ...
          11 21 31 41];

Note that this increases the risk of confusion. Furthermore, in some programming environments vectors are accessed starting with the index zero, while the first value of a vector in Matlab always has the index one. This is another degree of freedom that might complicate the situation. If you happen to see a problem, take a few minutes and think again!

Memory usage

Image information requires large amounts of memory, both for external storage on disk as well as in the computer's internal memory. Thus when you need to debug your algorithms, the work is considerably simplified, if you initially use relatively small test images.

Try to avoid storing large numbers of images (Matlab-variables, POSTSCRIPT-images or images in similar formats) directly onto your account. Most graphs and images can be regenerated with relative ease and can thus be efficiently ``stored'' in terms of the {\sc Matlab}-scripts that originally generated them.

If you use a large number of images in Matlab, the Matlab-process might sooner or later be very large. To release the memory of an allocated variable x, you may type clear x. Doing this on a regular basis will considerably lower the amount of memory needed by the Matlab-process, which on some machines may significantly improve also the computational speed.