Last modified on 22 November 2014, at 17:15

MATLAB Programming

MATLAB is a programming language developed by MathWorks. It started out as a matrix programming language where linear algebra programming was simple. It can be run both under interactive sessions and as a batch job.

Most MATLAB scripts and functions can be run in the open source program Octave. This program is freely available for most computing platforms.

GNU Octave and LabVIEW MathScript are systems for numerical computations with an m-file script language that is mostly compatible with MATLAB. Both alternatives can replace MATLAB in many circumstances. While a good deal of the content of this book will also apply to both Octave and LabVIEW MathScript, it is not guaranteed to work in exactly the same manner. Differences and comparison between MATLAB and Octave are presented in Comparing Octave and MATLAB.

A Tutorial IntroductionEdit

All programming languages are introduced by the most famous computer program on the planet, "Hello world", so let's begin with that for the time being. Open MATLAB on your computer. You will be greeted by a desktop environment of its own. In the center you can see a window labelled as "Command Window". The cursor should be already flickering there; all you now have to do is to write this...

   disp('Hello world')

and press the return key. The output will be shown just below the command as

   Hello world

So there you have it, a more simple program than in C or C++ we have to call only one function called


and pass the argument string in single quotes (not double), but why so? Because we might need to use double quotes inside the string and that would be interpreted as the end of the string argument. Having said this, it is assured that double quotes work inside the string, however escape sequences may have to be used to get the string right.


MATLAB has a programming environment in its own and needs an area to store the variables and other program data that is stored while using the tool. MATLAB has a command window as shown, and a base workspace which is the default workspace. Functions in MATLAB also have their own workspace, and the visibility of a variable is dependent on the workspace that it resides in. If the variable is in the base workspace then it is visible to all of the scripts and functions in MATLAB, while a function's local variables are visible to that function only and are not usable outside that function.

Type this on the MATLAB Command Window

   My_Var = 10

You will see

   My_Var =

as a response, also note that there would also be an addition to the Base workspace.

My_Var in Base workspace

To check out what all variables are stored in the MATLAB workspace, we can use the following command.


This would list out all the variables currently present in the MATLAB workspace, but would not give much idea about the data types and the size of the variables, to have those in the result use this command instead


By this time, i think there would be much clutter on your command window.

To clear out all the output on the command window, use this command.


This WOULD NOT clear out the variables and the history. so that you would have a new clean and fresh command window.

The output of whos on my screen showed something like this Output of "whos" command in Matlab

Now, if you notice the Size is marked as 1X1, but why? The reason for this is that in MATLAB all the data is realized as double precision arrays (well, its the way MATLAB is designed to work as it is a scientific computing tool). And so scalars like these are realized as a 1X1 array. Simple!

After all this if you think your work is done and you do not need all those variables in the MATLAB workspace now, you can relieve yourself of your Programmers baggage by using this command.


This clears out any and all variables in the workspace. But if your miseries are not yet to finish and would like to remove a variable or two.

   clear <var1> <var2>....

where var1, var2, var3,.... are the variables that you want to clear, do not put the three dots in the end, that's just for description.


Variables are just a container of your data. You can give any name to your variable as long as it is under 63 characters, starts with an alphabet and is without any punctuation in between. The reason for not allowing any punctuation is that the punctuation marks like . , : , ; etc have a special meaning in MATLAB and can alter the flow of execution


is a perfectly valid variable name. There may be some variables names that are not allowed even if they are perfectly valid variable names, because they are reserved keywords and are used to notify some code execution logic. However their number is limited and meaningful names for variables can be created outside this pool of names. To find if any word is a reserved keyword, run this check on the command line.


The result would be

   ans =

All values of variables are referred by their current instance in the workspace. The variables can be overwritten during the execution of MATLAB scripts and the values vary accordingly. All operations use the current value in the workspace.

Let's try something good. We all know that the value of pi is 3.1416, lets ask MATLAB the same, type this on the command window


The result is

   ans =

Lets try overwriting it...

   pi = 0

...and see it once again.

   ans =

Calculate the area of a circle now.

   Area = pi * 10 * 10

Basic MATLAB ConceptsEdit

Saving and loading a MAT-file50%.svgEdit

clc; clear all; close all;

[filename, pathname] = uigetfile( {'*.jpg';'*.bmp'}); aa=imread([pathname,filename]); I=aa; bb=imresize(aa,[256 256]); imshow(bb);title('input image');

%%...............%%% RGB2Lab color conversion %%%.........

rgbimage=makecform('srgb2lab'); labimage=applycform(bb,rgbimage); figure, imshow(labimage);title('color conversion image');

%%..............%%% seperate L* a* b* color space %%%.........

L=im2double(labimage(:,:,1)); a=im2double(labimage(:,:,2)); b=im2double(labimage(:,:,3)); figure,imshow(L);title('L* image'); [h,w,o]=size(L);

%%..........%%% applying filter in L* color space %%%..........

for s=1:3

   for i=1:h
       for j=1:w
          if p<=0
          if q>256
          if r<=0
          if t>256


contrast_L=azx(:,:,1)+azx(:,:,2)+azx(:,:,3); figure,imshow(contrast_L),title('contrast map L* image');

%%..............%%% find inverse of a* %%%............

figure,imshow(a);title('a* image'); d=max(max(a)); yy=d-a; yy=(yy*5); figure,imshow(yy);title('inv a* image'); [h,w,o]=size(yy);

%%.............%%% applying filter in a* color space %%%........

for s=1:3

   for i=1:h
       for j=1:w
          if p<=0
          if q>256
          if r<=0
          if t>256


contrast_a=aza(:,:,1)+aza(:,:,2)+aza(:,:,3); figure,imshow(contrast_a),title('contrast map a* image');

%%.............%%% find final scaling contrast map %%%.......

Scaling_contrast=imadd(contrast_L,contrast_a); figure,imshow(Scaling_contrast),title('Scaling contrast map');

%%...........%%% gabor filter outputs %%%.......................


%%..........%%% removing erythema & dark pixels %%%..........

ts=0.4;  %% set threshold value R=Scaling_contrast; for i=1:h

   for j=1:w
       if Scaling_contrast(i,j)>=ts


figure,imshow(R);title('Removing erythema');

The MATLAB Command Prompt50%.svgEdit

  • Calculator

Data Storage and ManipulationEdit

Data Types and Operators on Point ValuesEdit

Arrays and MatricesEdit



Handle Graphics25%.svgEdit

What is a handle?
Figure handles
Axis handles
Other types of handles

Annotating Plots25%.svgEdit

M-file ProgrammingEdit


Control Flow75%.svgEdit

Error Messages75%.svgEdit

Debugging M Files50%.svgEdit

Numerical ManipulationEdit

Linear AlgebraEdit

It is the Matrix laboratory after all.

  • Operations
  • Transpose
  • Systems of linear equations
  • Row reduced echelon form
  • Inverse
  • Coffactor, minor
  • Jacobian

Differential EquationsEdit

More advanced I/OEdit

Different versions of MATLAB handle this differently. We will focus on versions 6.5 and 7.x, primarily on MATLAB 7.x since it is the latest. A note will appear when the procedure is different for ver. 6.

Reading and writing from filesEdit

Writing and Reading to A Serial PortEdit

Writing to a USB portEdit



  • Moving Average
  • Alpha Beta
  • Kalman
  • PSD estimation
  • Entropy
  • Markov Processes
  • Queuing Theory


Phase vocoderEdit

See "Phase vocoder and encoder in MATLAB" for an example phase vocoder and the corresponding sound sample encoder in MATLAB.

Object Oriented ProgrammingEdit

MATLAB as well as Octave have object oriented capabilities. Yet, technically it is not fully an object oriented language.

An Object Oriented Language(OOL) has three components: 1. Polymorphism 2. Inheritance 3. Encapsulation

Octave can be extended by adding new objects. Those objects can overload the operators like e.g. assignment, slicing, comparison.

While in MATLAB, this can be done with m-script, in Octave new objects are implemented as C++ classes. A simple example of how objects can be added to Octave can be found here.

Struct arrays25%.svgEdit

MATLAB classes00%.svgEdit

An alternative to MATLAB: OctaveEdit

What is Octave ?Edit

A short presentation of Octave and its history.

Differences between Octave and MATLABEdit

The most important differences between Octave and MATLAB that anyone willing to use Octave instead of MATLAB should be aware of.

Toolboxes and ExtensionsEdit

The toolboxes are pretty good if you can afford them. In version 7 there are a lot of toolboxes.

Symbolic Toolbox75%.svgEdit

Image Processing Toolbox00%.svgEdit

MATLAB Compiler00%.svgEdit

Legacy ToolboxesEdit

  • GUIDE00%.svg allows the creation of interactive user interfaces.
  • Simulink00%.svg is for modeling, simulating and analysing systems.
  • Psychtoolbox00%.svg is a set of tools that aid in vision research.
  • Distributed computing- The distributed computing toolbox is a set of tools that aid in distributing models over a cluster.
  • Optimization- The optimization toolbox includes various algorithms for minimization.

MATLAB in medicineEdit

„Image Processing in Optical Coherence Tomography using Matlab” is a book which will introduce you to subtleties related to the implementation of selected fragments of algorithms, the notation of some of them in the MATLAB environment has been given. The presented source code is shown only in the form of example of implementable selected algorithm. The book is addressed to ophthalmologists , IT specialists and students involved in the development of applications designed for automation of measurements for the needs of medicine.


External linksEdit

Other WikibooksEdit

A number of other wikibooks use MATLAB to teach their subjects. The following wikibooks make use of MATLAB: