What Is Matlab
What Is Matlab
The name MATLAB stands for MATrix LABoratory. MATLAB is a high-performance language for technical
computing. It integrates computation, visualization, and programming environment. Furthermore, MATLAB is a
modern programming language environment: it has sophisticated data structures, contains built-in editing and
debugging tools, and supports object-oriented programming. It also has easy to use graphics commands that make
the visualization of results immediately available. These factors make MATLAB an excellent tool for teaching and
research.
Getting started
1. Starting MATLAB
When you start MATLAB, a special window called the MATLAB desktop appears. The desktop is a window that
contains other windows. The major tools within or accessible from the desktop are:
The Workspace
Example 4
>> sin(pi/4)
ans =
0.7071
>> exp(10)
ans =
2.2026e+004
Matrix generation
MATLAB is an efficient computer programming language if objects in your programs are matrices and vectors. It
stores numerical objects as matrices and it allows users to create and manipulate matrices in a wide variety of ways.
It even treats a scalar as a 1 by 1 matrix. If your programming involves matrices you will find MATLAB to be easily
programmable and very helpful for your computations. Therefore, we need to become familiar with matrix
generation and manipulation.
1. Entering a matrix
A matrix is an array of numbers. To type a matrix into MATLAB you must
2. Matrix functions
MATLAB provides many matrix functions for various matrix / vector manipulations. Let’s consider a matrix A.
Calculating the inverse of A manually is probably not a pleasant work. In MATLAB, however, it becomes as simple
as the following commands:
>> A = [1 2 3; 4 5 6; 7 8 0];
>> inv(A)
ans =
-1.7778 0.8889 -0.1111
1.5556 -0.7778 0.2222
-0.1111 0.2222 -0.1111
In linear algebra, to calculate A -1 B, we need to use the matrix inverse, “inv”
>> inv(A)*B
The second way to solve this is to use the backslash(\) operator.
>> A\B
Note: the usage of slash (/) operator, A/B, is to calculate: A B -1.
The determinant of A is
>> det(A)
ans =
27
See the table below for more of these functions. Use the help documentation of MATLAB to find how to use these
functions.
det Determinant
Basic plotting
1. Overview
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of computation is possible
with very few commands. Being able to plot mathematical functions and data freely is the most important step, and
this section is written to assist you to do just that.
2. Plotting elementary functions
The basic MATLAB graphing procedure, for example in 2D, is to take a vector of x-coordinates and a vector of y-
coordinates, locate the pairs of points and then join them by straight lines. You need to prepare “x” and “y” in an
identical array form; namely, ”x” and “y” are both row arrays or column arrays of the same length.
For example, to plot the function “y = sin(x)” on the interval “[0,2pi]”, we first create a vector
of “x” values ranging from 0 to 2pi, then compute the sine of these values, and finally plot the result.
We do this by sampling the function at a sufficiently large number of points and then joining up the points (
x,y) by straight lines. Suppose we take steps (or increments) of pi/100 over the distance [0,2pi]:
>> x = 0:pi/100:2*pi;
The corresponding y values are computed by:
>> y = sin(x);
And finally, we can plot the points with:
>> plot(x,y)
3. Adding titles, axis labels
MATLAB enables you to add axis labels and titles. For example, to include a title and label the axes on the graph
from the previous example, we use:
>> xlabel (`x = 0:2\pi');
>> ylabel (`Sine of x');
>> title (`Plot of the Sine function')
The strings enclosed in single quotes, can be anything of our choosing. The character “\pi” creates the symbol
for pi.
The color of a single curve is, by default, blue, but other colors are possible. The desired color is indicated by a third
argument. For example, red is selected by “plot(x,y,’r’)”.
4. Multiple data sets in one plot
Several graphs may be drawn on the same figure. For example, these statements plot three related function of x: y 1=
2*cos(x), y 2 = cos(x), and y 3 = 0.5*cos(x), in the interval [0 2pi].
>> x = 0:pi/100:2*pi;
>> y1 = 2*cos(x);
>> y2 = cos(x);
>> y3 = 0.5*cos(x);
>> plot(x,y1,'--',x,y2,'-',x,y3,':')
>> xlabel('0 \leq x \leq 2\pi')
>> ylabel('Cosine functions')
>> legend('2*cos(x)','cos(x)','0.5*cos(x)')
>> title('Typical example of multiple plots')
5. Subplot
MATLAB allows the graphic window to be split into an m by n array of small windows into which we may plot one
or more graphs. The windows are counted 1 to mn row-wise, starting from the top left. For example, these
statements subplot four related function of x: y 1 = sin(3pi*x), y 2= cos(3pi*x), y 3 = sin(6pi*x), and y 4 = cos(6pi*x)
in the interval [0 1].
>> x = 0:1/100:1;
>> y1 = sin(3*pi*x);
>> y2 = cos(3*pi*x);
>> y3 = sin(6*pi*x);
>> y4 = cos(6*pi*x);
>> title('Typical example of subplots')
>> subplot(2,2,1), plot(x,y1)
>> xlabel('0 \leq x \leq 1'), ylabel('sin(3 \pi x)')
>> subplot(2,2,2), plot(x,y2)
>> xlabel('0 \leq x \leq 1'), ylabel('cos(3 \pi x)')
>> subplot(2,2,3), plot(x,y3)
>> xlabel('0 \leq x \leq 1'), ylabel('sin(6 \pi x)')
>> subplot(2,2,4), plot(x,y4)
>> xlabel('0 \leq x \leq 1'), ylabel('cos(6 \pi x)')
“subplot(2,2,1)” specifies that the window should be split into a 2 by 2 array and we select the first
subwindow.
Introduction to programming in MATLAB
1. Introduction
So far, all the commands were executed in the Command Window. The problem is that the commands entered in the
Command Window cannot be saved and executed again several times. In order to repeat any calculation and/or
make any adjustments, it is most convenient to create a file with a list of commands. The files that are used for this
purpose are called script files or scripts for short.
This section covers the following topics:
M-File Scripts
M-File Functions
2. M-File scripts
An M-File script is an external file that contains a sequence of MATLAB statements. Script files have a filename
extension “.m” and are often called M-Files. M-Files can be scripts that simply execute a series of MATLAB
statements, or they can be functions that can accept arguments and can produce one or more outputs.
Note: the first character of the filename must be a letter.
Examples
Here are some simple scripts.
Example 1
Let’s put the commands for calculating the roots of a quadratic equation into a file called “quat.m”.
Use the MATLAB editor to create a file: “File –> New –> M-file“.
Decide on a name for the function, making sure that it does not conflict a name that is already used by MATLAB.
Document the function. That is, describe briefly the purpose of the function and how it can be used. Each comment line
should be preceded by a “%” which signifies that the line should be ignored when the function is evaluated.
The first command line of the file must have the format:
function
= functionname(list of inputs)
......
......
Save the function as a M-file
Examples
Here are some simple examples.
Example 1
Using our previous M-File example (solving the quadratic equation), if it is being used by many other M-files, it will
be convenient to have a separate file (i.e. a function file) which calculates the roots of a quadratic equation. Let’s
write a function file “quatsol.m”:
% ----------------------------------------------------
------
% quatsolv.m is to compute the roots of
% quadratic equation ax^2 + bx + c =0
% ----------------------------------------------------
------
function [x1, x2] = quatsolv(a, b, c)
x1=(-b+sqrt(b^2-4*a*c))/(2*a);
x2=(-b-sqrt(b^2-4*a*c))/(2*a);
The first line of a function M-File starts with the keyword “function”. (Notice above that Matlab ignores the
comment lines so the first executable statement is the “function” statement.) It gives the function name and
order of arguments. In this example, there are up to two output arguments and three input arguments.
To evaluate this function, a main program is needed. This main program provides input arguments (a, b, and c).
These inputs are then sent to the function file (“quatsolv.m”) to calculate the roots and then return the results
back to the main program. In this example, the main function is to be called “main.m”, which looks like:
% ----------------------------------------------------
---
% main.m is to solve quadratic equation ax^2 + bx + c
=0
% it calls the external function quatsolv.m
% ----------------------------------------------------
---
a = input(`Enter a: ');
b = input(`Enter b: ');
c = input(`Enter c: ');
[x1, x2] = quatsolv(a, b, c);
x1
x2
When “main.m” is invoked, it will function as the previous version of “quat.m”.
Example 2
Besides solving the quadratic equation on roots of a quadratic equation, one can also plot it for a graphical
presentation. Let’s create another main file ( “main2.m” ) and a new function file ( “quatsolv2.m” )
which look like the following:
% ----------------------------------------------------
---
% main2.m is to plot quadratic equation ax^2 + bx + c
for
% some range.
% it calls the external function quatsolv2.m
% ----------------------------------------------------
---
global a b c
a = 1;
b = 0;
c = -2;
fplot(`quatsolv2',[-4, 4])
The global statement means that a, b, and c can be used outside of main2.m. In the “fplot”statement, the single
quotes around “quatsolv2” are necessary to prevent MATLAB from evaluating ”quatsolv2” until
inside “fplot”. The second argument of “fplot”, “[-4,4]”, is a vector which defines the beginning
and the end of the range of x-values over the plot. The function file “quatsolv2.m” is defined as the
following:
% ----------------------------------------------------
------
% quatsolv2.m is to compute the values of
% quadratic equation ax^2 + bx + c
% ----------------------------------------------------
------
function y = quatsolv2(x)
global a b c
y = a*x^2 + b*x + c;
In this example, there are up to one output argument and one input argument. If you run “main2.m”, a graph
will show as below:
Figure 1.