Goals: This lecture aims at providing an introduction to MATLAB programming for beginners, how to install it, different components of the Graphical Unit Interface of MATLAB, as well as how to perform simple arithmetic operations in MATLAB.

Lecture Videos

This video is created solely as reference for the attendants of ICP2017F course at UT Austin. If you did not attend this class, then you may not find this video useful.


MATLAB: a brief history

MATLAB was developed in the mid 1980’, by the collaborative works of Cleve Moler, a PhD graduate of Stanford University, and John Little, a graudate of MIT. Together they co-founded a private company named MathWorks.

The name of the language and software they developed, MATLAB is an attribution to the original purpose of the software, that is, to serve as a matrix laboratory. Cleve Moler was among the developers of the popular Fortran libraries EISPACK and LINPACK. He wanted to provide his students with a higher-level environment, so that they could use these high-performance Fortran libraries without the need to learn Fortran.

Since MATLAB was developed by a scientist for scientists, its structure and syntax has more resemblance to the popular programming language of scientists, Fortran, than to any other language. You will soon notice this similarity when we get to learn modern Fortran later on in this course.

An informative historical review of MATLAB by its own inventor is available to watch on MathWork website. A lower quality of the same video can be accessed on youtube, which I embed here for you:

MATLAB: Why do you need to learn it?

For the following reasons:

  • It targets engineers as well as natural and medical scientists as its main audience, just like Fortran.
  • It has excellent native array/matrix representation and manipulation tools, just like Fortran.
  • It has extensive sets of high-level commands for numerical computing, like Fortran.
  • It is an interpreted language that makes it really easy to use anytime, unlike C, C++, Fortran which are compiled languages.
  • It has excellent set of graphical tools for 2D and 3D plotting (in fact other languages like Python have tried to copy from and reverse-engineer the graphical tools and commands available in MATLAB).
  • It has one of the largest user-base (over 2,000,000 users) in all scientific communities.
  • There is an extensive list of numerical libraries written in MATLAB over the past decades by all those science/engineering -oriented users.
  • It has excellent manual, and user guide, with extensive illustrative examples. Basically, you might not even need to take a MATLAB class, if you could closely and carefully follow MATLAB’s user guide.

MATLAB caveats

Here is a personal list of MATLAB caveats that I can think of, at the moment:

  • It is not free.
  • It is slow compared to compiled programming languages. See for example, the following performance comparisons and tests in NASA modeling guru web page. As you can see there, the performance of MATLAB script can be significantly lower than compiled languages such as Fortran and C.
  • If you have already coded in a fully object-oriented programming (OOP) language, in particular Python, you will find some oddities in MATLAB’s OOP implementation. You may feel this when, for example, you are working with cell arrays in MATLAB. We will see later on, what cell arrays are.

MATLAB features

MATLAB has the following features and attributes.

  • MATLAB is a fourth-generation, high-level programming language. Remember from our second lecture, that a high-level programming language provides a high level of programming abstraction from details of computer and machine code. For comparison, Fortran, C++, and C are considered high, medium, and low -level programming languages respectively.

  • MATLAB is an array-based programming language, meaning that it is designed to be with the goal of facilitating array manipulation for scientists and engineers.

  • MATLAB is a multi-paradigm programming language. MATLAB allows the programmer to use the following major programming paradigms in their codes:

   Later on, we will get to each of these programming paradigms in MATLAB.

  • MATLAB is an interpreted language. A programming language implementation is a system for executing computer programs. There are two general approaches to programming language implementation:

    • Interpretation: An interpreter takes as input a program in some language, and performs the actions written in that language on some machine.

    • Compilation: A compiler takes as input a program in some language, and translates that program into some other language, which may serve as input to another interpreter or another compiler.

      MATLAB is an interpreted language, meaning that, as soon as you type a MATLAB command on the MATLAB’s command-line and press enter, the MATLAB interpreter executes the statement. MATLAB programs can also be compiled using MATLAB Compiler, to create standalone applications to be executed later when desired.

  • The extension for human-readable MATLAB source code file is .m.

Some useful resources for MATLAB

MATLAB installation

Depending on your operating system, you can download and install a specific version of MATLAB for your personal computer. MATLAB is available to all students enrolled at UT Austin for free. It can be downloaded from here.

Alternative replicas of MATLAB

Since MATLAB is not free, the GNU organization has started a project called GNU Octave which is a reverse-engineering of MATLAB language and environment, hence mostly compatible with it, but at no cost!. You can download it from here. GNU Octave is a free open source software (FOSS) package which is mostly compatible with MATLAB. It provides a very similar command line interpreter interface, and implements most of the functionality as the commercial MATLAB product. Nevertheless, there are subtle differences which anyone attempting to switch to GNU Octave or to write MATLAB/GNU Octave-compatible scripts must appreciate. Octave was conceived in 1988 and has been under development since 1992, and over the years has made a great deal of progress, especially in the area of graphics and plotting.

MATLAB script editors

I highly recommend you to use MATLAB’s own IDE for MATLAB scripting since it has fantastic features such as automatic debugging, indentation and syntax highlight. However, once you become proficient in MATLAB scripting, you may realize that the text-editing capabilities of MATLAB IDE are not that great compared to highly popular general-purpose text editors. In that case, I recommend you to use,

  • Sublime (available Windows, OS X, Linux)
    Sublime is a sophisticated text editor for codes in many different languages, including MATLAB, C, C++, Fortran, etc. It has many advanced tools for code editing and syntax highlighting.

  • Notepad++ (available only on Windows)
    Notepad++ is a highly versatile text and source code editor for use with Microsoft Windows. It is likely – and in my opinion, arguably – the most powerful general-purpose text editor that is currently available on the web. Notepad++ automatically identifies the type of code the file contains based on the file extension and highlights the code syntax accordingly. However, you should keep in mind that it is not specifically designed for MATLAB. If you are professional multi-language programmer, you will soon find the hidden gems in Notepad++, that are not available in any other editor, including MATLAB’s own editor.

Which MATLAB version should I use?

Always try to use the latest version if possible, since new features are added to MATLAB every year.

Using MATLAB online, in your web browser

Since as a UT student, you have a campus-wide MATLAB licence, you can login to your account to use MATLAB in your browser, on a remote server. For instructions on how to use MATLAB on-line, click here.

MATLAB environment

As soon as you open MATLAB, you will likely encounter a environment like the following figure.

A snapshot of MATLAB environment.

The main compartments in MATLAB environment are:

  • command window: where you can type single or multiple line commands.
  • script editor: which is where you can create new or open/edit existing MATLAB files.
  • address bar: indicating the current working directory.
  • folder tree window: showing all files in the current working directory.
  • workspace window: which shows all the global variables currently defined in MATLAB.

Useful MATLAB commands

The following are some useful MATLAB commands that allow you to get help on the command-line:

  • demo will load MATLAB examples in the Help Browser, illustrating some features of MATLAB.

  • help <keyword> will explain any function. For example,
    >> help sin
    sin    Sine of argument in radians.
     sin(X) is the sine of the elements of X.
    
     See also asin, sind.
    
     Reference page for sin
     Other functions named sin
    


  • help help will explain how MATLAB help works.

  • lookfor <keyword> searches through MATLAB help for a specific word or phrase. For example,
    >> lookfor gaussian
    hwv                            - Create a Hull-White/Vasicek mean-reverting Gaussian diffusion model
    xreggpr                        - xreggpm Gaussian Process model constructor
    gmdistribution                 - Gaussian mixture distribution class.
    awgn                           - Add white Gaussian noise to a signal.
    bigaussianir                   - Bi-Gaussian Doppler filter impulse response.
    gaussianir                     - Gaussian Doppler filter impulse response.
    intfiltgaussian_intfactor      - Support function used by @channel package for
    wgn                            - Generate white Gaussian noise.
    commblkgaussfilt               - Gaussian filter block helper function.
    commblkgaussiansrc2            - Mask function for Gaussian Noise Generator block
    


  • doc <keyword> will bring up a documentation page in the Help Browser for the given keyword.

  • dir <path> lists the contents of the given path.
    >> dir
    .                lcdata.xml       m3iregistry      mcc.bat          mexext.bat       mw_mpiexec.bat   win64            
    ..               lcdata.xsd       matlab.exe       mex.bat          mexsetup.pm      registry         worker.bat       
    deploytool.bat   lcdata_utf8.xml  mbuild.bat       mex.pl           mexutils.pm      util             
    


  • pwd outputs the current working directory.
    >> pwd
    ans =
    C:\Program Files\MATLAB\R2016a\bin
    


  • quit quits MATLAB by closing the application.

  • diary('filename') (or diary filename) saves all subsequent keyboard interactions with MATLAB Command Window to the file filename. diary off suspends the diary. diary on resumes diary mode using the current filename, or the default filename diary if none has yet been specified.

Comments in MATLAB scripts

Comment lines in MATLAB begin with percent character %. Anything after % is ignored by MATLAB interpreter. The % character itself only tells the interpreter to ignore the remainder of the same line. In the MATLAB Editor, commented areas are printed in green by default. There are two useful keyboard shortcuts for adding and removing chunks of comments. Select the code you wish to comment or uncomment, and then press Ctrl-R to place one % symbol at the beginning of each line and `Ctrl-T to do the opposite.

MATLAB also supports multi-line comments, akin to /* ... */ in languages like C or C++, via the %{ %} delimiters. But there is a small and important difference. In MATLAB, the lines containing %{ or %} should not contain any other text (except white spaces). Otherwise the multi-line comment would not work as you wish. For example,

%{ x = 1;
y=2;%}


You notice that in the above, y=2; is not commented. The correct syntax is,

%{
x = 1;
y=2;
%}


Comments are useful for explaining what function a certain piece of code performs especially if the code relies on implicit or subtle assumptions or otherwise perform subtle actions. Doing this is a good idea both for yourself and for others who try to read your code. It is highly recommended to include a block of comments at the beginning of your codes explaining what the your MATLAB script or function does does and how to use it. MATLAB will output the leading comments that appear at the beginning of an .m file, when you type,

>> help <my function name>


All of MATLAB’s built-in functions written in MATLAB are documented this way.

MATLAB’s search path

MATLAB has a search path and strategy that is used to find variables, and MATLAB scripts. MATLAB’s current working directory is always displayed in the MATLAB address bar. When you enter a name in MATLAB’s command prompt, the MATLAB interpreter attemps to find an entity with that name in the following order:

  1. First, it looks for a variable of the same name in MATLAB’s workspace and if it exists, MATLAB displays the value of the variable.
  2. If not, then MATLAB, looks for a M-file (a MATLAB script) in the working directory of MATLAB.
  3. If not, then MATLAB looks for an M-file in MATLAB’s list of directories (the search path) to find the file. If no entity exists with the given name, then MATLAB gives an error.



Comments