What Is Matlab
What Is Matlab
WHAT IS MATLAB ?
Introduction
MATLAB has evolved over a period of years with input from many users. In
university environments, it is the standard instructional tool for introductory and
advanced courses in mathematics, engineering, and science. In industry, MATLAB is the
tool of choice for high-productivity research, development, and analysis. The default
view of Matlab is as shown in the figure1 below.
A introduction to Matlab ANS Solutions
The basic windows that help the user use Matlab are five. These five windows are
to enable ease access and interaction with Matlab.
These windows include,
The Command Window
Command history
Workspace Browser
Current Directory
Launch Pad
Apart from these windows, the main Matlab window is called The Matlab
desktop. If all the above shown windows are closed, then what we see is the Matlab
desktop. This window is the main window and opens when Matlab starts and closes only
when Matlab exists. In other words, exiting Matlab means closing or quitting this Matlab
desktop. The figure2 below shows how this Matlab desktop looks.
This window is the main window but do not provide any access to Matlab
commands or functions. To interact with Matlab we need the first window of the above
listed windows, The Command window. Shown in figure3, is The Command window.
A introduction to Matlab ANS Solutions
In the command window, we have the command prompt (see figure3). This
command prompt is just like the dos prompt where we type all the commands so that
Matlab can understand the commands and give us the desired output. This is the point of
interaction between the user and Matlab. We type different commands at the command
prompt in the command window to execute our programs and achieve the desired tasks.
Command Prompt
Command prompt
Let us assume that we have a variable ‘a’, which has to hold the value ‘115’. So
declare this variable, as we do in any other language, we say,
>> a=115
this statement declares the variable, a and assigns it the value 115.
Now declaring some more variables,
>> b=2
>> c=10;
>> myvar=1001
>> var1=2001;
A introduction to Matlab ANS Solutions
See the figure4 below and observe the difference between declaring the variables using a
semicolon (‘;’) at the end of the declaration.
Initially declared variable ‘a’,
assigning it the value of 115
Figure4: Variables
From the figure we can observe that, for the declarations made using the ‘;’, there
is no display of the variable and the value. And for those variables declared without ‘;’,
the variable and its corresponding value is displayed immediately after the execution of
the command (Any command is executed just by pressing the return key.). To clear the
command window, we use the command,
>> clc
this command clears the command window. This is a basic command in Matlab.
Matlab is case-sensitive hence the command typed
A introduction to Matlab ANS Solutions
Timestamp marks
the start of each
session
The command history not only stores the Matlab commands but it also stores
everything what ever is typed at the command prompt. E.g.: the ‘abcdef’ in the command
history. This ‘abcdef’ is not a valid Matlab command but still is store in the command
history since it is typed at the command prompt.
A introduction to Matlab ANS Solutions
The next window is The Workspace Browser. The MATLAB workspace consists
of the set of variables (named arrays) built up during a MATLAB session and stored in
memory. You add variables to the workspace by using functions, running M-files, and
loading saved workspaces. To view the workspace and information about each variable,
use the Workspace browser.
load the MAT-file at a later time during the current or another session to reuse the
workspace variables. MAT-files use a .mat extension.
The .mat extension is also used by Microsoft Access.
To save all of the workspace variables using the Workspace browser:
From the File menu, select Save Workspace As, or click the save button in
the Workspace browser toolbar.
The Save dialog box opens. Specify the location and File name. MATLAB
automatically supplies the .mat extension.
Click Save. The workspace variables are saved under the MAT-file name
you specified.
We can also save the workspace variables from the desktop by selecting Save
Workspace As from the File menu.
To save some but not all of the current workspace variables:
Select the variable in the Workspace browser. To select multiple variables,
Shift+click or Ctrl+click.
Right-click and from the context menu, select Save Selection As.
The Save to MAT-File dialog box opens. Specify the location and File
name. MATLAB automatically supplies the .mat extension.
Click Save. The workspace variables are saved under the MAT-file name
you specified.
To save workspace variables, use the save function followed by the filename you want to
save to.
>> save('myvariables')
saves all current workspace variables to the file myvariables.mat. If you don't specify a
filename, the workspace is saved to matlab.mat in the current working directory.
To load the saved workspace variables in the same session or in a new Matlab
session, use the load command.
>> load myvariables
this command loads all the preciously save variables into the workspace.
Clearing the workspace variable:
We can clear the variables, which removes them from the workspace.
A introduction to Matlab ANS Solutions
When we say a=115, it means that ‘a’ is a variable of size 1X1. i.e. ‘a’ has 1 row and 1
column. See figure8 shown below.
>> x=[1 2 3]
this declaration declares a variable x of size 1X3. i.e. x contains 1 row and 1 column.
Rows
Columns
Variable format
>>size(p)
ans =
3 6
this command gives the size of the array ‘p’. i.e. it returns the number of rows and
columns in the array. Since this size is not taken into any variable, Matlab by default
takes it to the default variable of size 1X2.
Byte is the amount of space occupied by the variable n the memory.
Class is the data type of the variable.
Data Types:
The term data type refers to the way in which a computer represents numbers in
memory. A data type determines the amount of storage allocated to a number, the method
used to encode the number's value as a pattern of binary digits, and the operations
available for manipulating the type.
There are 15 fundamental data types in Matlab. Each of these data types is in the
form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-
dimensional array of any size. Two-dimensional versions of these arrays are called
matrices. All of the fundamental data types are shown in lowercase text in the figure9
below. Additional data types are user-defined, object-oriented user classes (a subclass of
structure), and java classes, that you can use with the Matlab interface to Java.
ARRAY
Java classes
User classes
The six fundamental data types in MATLAB are double, char, logical, uint8, cell,
and structure.
By default, MATLAB stores most data in arrays of class double. The data in these
arrays is stored as double precision (64-bit) floating-point numbers. All Matlab functions
and capabilities work with these arrays. For images stored in one of the graphics file
formats supported by Matlab, however, this data representation is not always ideal. The
number of pixels in such an image may be very large; for example, a 1000-by-1000
image has a million pixels. Since each pixel is represented by at least one array element,
this image would require about 8 megabytes of memory if it were stored as class double.
To reduce memory requirements, Matlab supports storing image data in arrays of class
uint8 and uint16. The data in these arrays is stored as 8-bit or 16-bit unsigned integers.
These arrays require one-eighth or one-fourth as much memory as data in double arrays.
Complex Double-Precision Matrices
The most common data type in Matlab is the complex double-precision. These
matrices are of type double and have dimensions m-by-n, where m is the number of rows
and n is the number of columns. The data is stored as two vectors of double-precision
numbers - one contains the real data and one contains the imaginary data. The pointers to
this data are referred to as pr (pointer to real data) and pi (pointer to imaginary data),
respectively. A real-only, double-precision matrix is one whose pi is NULL.
Numeric Matrices
Matlab also supports other types of numeric matrices. These are single-precision
floating-point and 8-, 16-, and 32-bit integers, both signed and unsigned. The data is
stored in two vectors in the same manner as double-precision matrices.
MATLAB Strings
Matlab strings are of type char and are stored the same way as unsigned 16-bit
integers except there is no imaginary data component. Unlike C, MATLAB strings are
not null terminated. All string declarations must be done under single quotations.
E.g.: s=’matlab’;
A introduction to Matlab ANS Solutions
Cell Arrays
Cell arrays are a collection of Matlab arrays where each m X Array is referred to
as a cell. This allows Matlab arrays of different types to be stored together. Cell arrays are
stored in a similar manner to numeric matrices, except the data portion contains a single
vector of pointers to m X Arrays. Members of this vector are called cells. Each cell can
be of any supported data type, even another cell array. In short, a cell array is a matrix of
matrices.
1 2 3 4 3 4 5 5 7
5 6 7 8 8 9 3 10 7
66 454 50 88 7
h e l l o h o w r u ? 3+5i 5
1003 12i
Data Storage:
All Matlab data is stored column wise, which is how Fortran stores matrices.
Matlab uses this convention because it was originally written in Fortran.
For example, given the matrix
>>a=['HOME '; 'EDIT '; 'TIME']
now the variable ‘a’ contains the strings as displayed.
a=
HOME
EDIT
TIME ----------these strings in Matlab are stored in the below shown format,
H E T O D I M I M E T E
The next window as per our listing is The Current Directory.
Matlab file operations use the current directory and the search path as reference
points. Any file you want to run must either be in the current directory or on the search
path. To search for, view, open, and make changes to Matlab related directories and files,
we use the Matlab Current Directory browser. Equivalent functions are documented for
each feature of the Current Directory browser.
To open the Current Directory browser, select Current Directory from the View
menu in the Matlab desktop, or type filebrowser at the Command Window prompt. The
Current Directory browser opens. A quick way to view or change the current directory is
by using the Current Directory field in the desktop toolbar on the Matlab desktop as
shown below.
Figure11: Current directory field in the desktop toolbar of the Matlab desktop
The default directory in Matlab is the ‘work’ directory as shown above. To
search for, view, open, and make changes to Matlab-related directories and files, use the
Matlab Current Directory browser.
Alternatively, you can use the functions
>>dir ---- to list the files in the current directory
>> cd ---- to change directory
>>delete ---- to delete files or folders
can be used. Figure12 shown below shows the current directory.
A introduction to Matlab ANS Solutions
Matlab uses a search path to find M-files and other Matlab-related files, which are
organized in directories on your file system. Any file you want to run in Matlab must
reside in the current directory or in a directory that is on the search path. By default, the
files supplied with Matlab and MathWorks toolboxes are included in the search path.
Search path is used to search for the pre defined functions files that we use in our
code. To see which directories are on the search path or to change the search path, select
Set Path from the File menu in the desktop, and use the Set Path dialog box.
Alternatively, you can use the path function to view the search path, addpath to
add directories to the path, and rmpath to remove directories from the path.
Use the pathname edit box to view Click the find button to search
directories and their contents for the content with in m file
The Matlab Start button and the Launch Pad are similar tools that provide easy
access to tools, demos, and documentation for all your MathWorks products. The Matlab
Start button has a menu interface that we can access. The Launch Pad presents
information as a tree view in a window that is always visible if you have the Launch Pad
open.
The launch pad and the Start button are as shown in the figure13 below.
Toolboxes:
A toolbox is nothing but a collection of the related functions. Toolboxes are
similar to a header files in C language. Matlab features a family of add-on application-
specific solutions called toolboxes. Very important to most users of Matlab, toolboxes
allow you to learn and apply specialized technology. Toolboxes are comprehensive
collections of Matlab functions (M-files) that extend the Matlab environment to solve
particular classes of problems. Areas in which toolboxes are available include signal
processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and
many others.
Matlab has a vast collection of computational mathematical algorithms ranging
from elementary functions like sum, sine, cosine, and complex arithmetic, to more
sophisticated functions like matrix inverse, matrix eigen values, Bessel functions, and fast
Fourier transforms. It has toolboxes on various technologies such as communications,
signal processing, fuzzy logic, control systems, neural networks, etc.
. To open it, select Launch Pad from the View menu in the MATLAB desktop.
The product categories are listed. To expand the listings for a product category or
product, click the + to the left of the product. To collapse the listings, click the - to the left
of the product. Navigate through the product categories and products to the tool you want
to open. Double-click a tool to open it. This example shows how to open the Filter
Design and Analysis tool in the Signal Processing Toolbox.
Apart from the Matlab windows discussed so far, we have here other windows.
They are,
Help
Edit Window
Figure Window
A introduction to Matlab ANS Solutions
Help, is the Matlab help which provides information regarding the toolbox
functions and their functionalities.
Matlab provides interactive help. We can just type
>> help functionname -------------- to get immediate help on the command window itself.
The other two windows will be discussed in the next session.
A introduction to Matlab ANS Solutions
DEMO-Double-click to
display the demos of the
product
Product Page-double-
click to view the latest
product information on
the Matlab web site
Programming
Matlab is a high-level matrix/array language with control flow statements,
functions, data structures, input/output, and object-oriented programming features. It
allows both "programming in the small" to rapidly create quick and dirty throw-away
programs, and "programming in the large" to create complete large and complex
application programs.
Starting Matlab session:
On Windows platforms, to start MATLAB, double-click the MATLAB shortcut
icon “ ” on the Windows desktop. After starting MATLAB, the MATLAB desktop
opens.
Ending Matlab session:
To end the current Matlab session, select Exit MATLAB from the File menu in
the desktop, or type quit in the Command Window or just click the “ ” button of the
Matlab desktop.
>>quit
>>exit
To execute specified functions each time MATLAB quits, such as saving the
workspace, you can create and run a Matlab script file finish.m.
linking), calling Matlab as a computational engine, and for reading and writing MAT-
files.
We can call our own C or FORTRAN subroutines from Matlab as if they were
built-in functions. Matlab callable C and FORTRAN programs are referred to as MEX-
files. Mex-files are dynamically linked subroutines that the Matlab interpreter can
automatically load and execute. Mex-files have several applications:
Large pre-existing C and FORTRAN programs can be called from Matlab
without having to be rewritten as M-files.
Bottleneck computations (usually for-loops) that do not run fast enough in
Matlab can be recoded in C or FORTRAN for efficiency.
Mex-files are not appropriate for all applications. Matlab is a high-productivity system
whose specialty is eliminating time-consuming, low-level programming in compiled
languages like FORTRAN or C.
Programming in Matlab
Matlab is a powerful programming language as well as an interactive
computational environment. The main aim of any language is development of
applications. This can very easily be done in Matlab through a set of Matlab functions,
code words and a proper logic.
Types of Files:
Matlab has different types of files. Matlab has three types of files. They are the
M-files, Mat-files and the Mex-files.
M-files are the standard ASCII text files, with a '.m' extension to the file name.
There are two types of M files; they are the ‘script’ files and the ‘function’ files.
Mat-files are the binary data-files, with a .mat extension to the filename. Mat-files
are created by Matlab when we save data with the save command or when we save the
workspace variables (as discussed in the previous session). The data in Mat-files is
written in special format which only Matlab can understand.
Mex-files are Matlab callable FORTRAN and C programs, with a .mex extension to the
filename (described in the Matlab API).
A introduction to Matlab ANS Solutions
To write a set of commands, we have a special window called the Edit Window
where we can write the set of commands at a single place and save the same with our
own file name. The files saved in such a way are by default saved with the extension .m.
These M-files are of two types, they are the ‘script’ files and the ‘function’ files.
Script files are those files which do not depend on any other file for input arguments or
return any output arguments. Function files are those files which accept input arguments
and return some output arguments. The input or output arguments are optional for
function files. The main difference between script files and the function files is that,
script files can run independently and function files which have input arguments can’t run
independently. They need to be called from some other file or from the command prompt
by passing the required input arguments.
Function files can be run in two different ways according to the arguments passed,
either input or out arguments. Function files which contain one or more input argumenys
have to be called from some other file by giving the value to the input arguments.
Function files with no input arguments but only output arguments can be run
independently. There may be functions which do not have both input and output
arguments. Whatever be it, the variables of the function files will be local. These
variables will be deleted from the workspace once the execution of the function is
finished. Whereas the variables of the script files will be available in the workspace even
after the script file finishes execution. These variables will reside in the workspace unless
the user clears the variables in the workspace.
Hence it is always advised to clear the variables of the workspace when a new
program is being executed.
Few differences between the script files and the function files are:
Script M-files Function M-files
do not accept input arguments or can accept input arguments and return
return output arguments. output arguments
internal variables are local to the
operate on the data in the workspace function by default.
useful for automating a series of
steps we need to perform many useful for extending the matlab
times. language for various applications.
A introduction to Matlab ANS Solutions
Creating/Opening an M-file:
To create a script or function M-file, choose ‘New’ from the file menu and select
M-file or click on the button on the toolbar. This procedure brings up a text editor
window where we enter Matlab commands.
Saving an M-file:
After making changes to an M-file, we see an asterisk (*) next to the filename
(see figure14) in the title bar of the Editor/Debugger. This indicates there are unsaved
changes to the file.
To save the changes, use one of the Save commands in the File menu:
Save--Saves the file using its existing name. If the file is newly created,
the Save file as dialog box opens, where you assign a name to the file and
save it.
Another way to save is by using the button on the toolbar. If the file has
not been changed, Save is grayed out, but you can instead use Save As to
A introduction to Matlab ANS Solutions
save to a different filename. Save As--The Save file as dialog box opens,
where we assign a name to the file and save it.
We do not need to type the .m extension because Matlab automatically
assigns the .m extension to the filename.
If you do not want an extension, type a . (period) after the filename.
Save All--Saves all named files to their existing filenames. For all newly created files, the
Save file as dialog box opens, where you assign a name to each file and save it.
AutoSave:
As you make changes to a file in the Editor, every five minutes the Editor
automatically saves a copy of the file to a file of the same name but with an .asv
extension. The auto saved copy is useful if you have system problems and lose changes
made to your file. In that event, you can open the auto saved version, filename.asv, and
then save it as filename.m to use the last good version of filename.
Use Auto save Preferences for the Editor/Debugger to turn the auto save feature
off or on, to specify the number of minutes between automatic saves, and to specify the
file extension and location for auto saved files. Auto saved files are not automatically
deleted when you delete the source file. So if, for example, you rename a file, delete
the .asv version of the original filename. If the M-file you are editing is in a read-only
directory, an auto save copy of the file is not made.
Running M-Files:
We can run a script or a function that does not require an input argument directly
from the Editor/Debugger.
Click the run button “ ”on the toolbar, or select Run from the Debug menu.
If the file is not in a directory on the search path or in the current directory, a
dialog box appears, presenting you with options that allow you to run the file. You can
either change the current directory to the directory containing the file, or you can add the
directory containing the file to the search path. See figure 15.
A introduction to Matlab ANS Solutions
Commented
statements are
displayed in green
color
In the above program, we have declared two variables, fact and a and they are
initialized to 7 and respectively. This program calculates the factorial of the number fact.
Here if we want to get the factorial of any other then we need to go to the program and
change the value of the variable fact. Instead we can accept any value from the user. This
can be if we declare the file as a function.
Creation of a function file:
To create a function file, the first word in the code should be function. See the
figure17 shown below.
When you type the above command at the command prompt, the program
executes and nothing is displayed. And we can also observe that there will be no variables
in the workspace also. It means that the variables are local to the function. Since no
display commands are used, there is no display of the output. For this reason we can pass
output arguments to the function so that these output arguments will be stored in the
workspace.
function a=fact123(fact)
a=1;
for i=1:fact
a=a*i;
end
run the above program and you will observe that the variable a will be stored in the
workspace and by typing ‘a’ at the command prompt will display the output.
Debugging:
While executing the code, it is come times required that we run the code line by
line. This may be to understand what exactly is happening in the code or what is getting
executed or what in not getting executed in a conditional loop. In such cases we can use
the debug option provided by Matlab. To enter the debug mode, we need to introduce a
break point. To introduce a break point, go to the line number where you want to
introduce the breakpoint and click before the statement. A red point appears as shown in
figure18.
Execution stopped at
Break point the break point
Break point enables us to execute the code line by line so that we can see what is
happening in each line of our code. Run the program in the normal procedure even after
introducing the break point. Execution stops at the line number where the break point is
introduced as shown in figure19. To continue execution step by step, press F10.
Global Variables:
If you want more than one function to share a single copy of a variable, simply
declare the variable as global in all the functions. The global declaration must occur
before the variable is actually used in a function.
Although it is not required, using capital letters for the names of global variables
helps distinguish them from other variables.
For example, create an M-file called falling.m.
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Then interactively enter the statements global GRAVITY
>>GRAVITY = 32;
>>y = falling(5);
The two global statements make the value assigned to GRAVITY at the command
prompt available inside the function. You can then modify GRAVITY interactively and
obtain new solutions without editing any files.
Basic functions and features:
In Matlab we can build expressions that use any combination of arithmetic,
relational, and logical operators. Precedence levels determine the order in which Matlab
evaluated an expression. With in each precedence level, operators have equal precedence
and are evaluated from left to right. The precedence rules for Matlab operators are as
shown below:
A introduction to Matlab ANS Solutions
Relational operators:
< Less Than
<= Less Than or equal to
> Greater Than
>= Greater Than or equal to
== Equal to
~= Not equal to
Logical Operators:
Matlab provides the following logical operators
& --- AND
| -----OR
~ ---NOT
Special variables:
In addition to the rules of variables, Matlab has several special variables
ans ---------- Default variable names used from results
pi ----------- Ratio of the circumference of a circle to its diameter (22/7=3.1516)
eps --------- Smallest number such that, when added to one, creates a number greater then
one on the computer
flops ------ Count the floating point operations.
Inf -------- Stands for infinity (1/0)
NaN ------ Stands for not a number (0/0).
Matlab does not have any mathematical value as not defined. If it encounters 0/0 or
inf/inf, it returns NaN.
Some elementary mathematical functions:
Trigonometric.
A introduction to Matlab ANS Solutions
computes or saves them. The specified format applies only to the current session. The
default output format is shortG.
>> m=magic(5)
m=
1stcol 2ndcol 3rdcol 4thcol 5thcol
1st row 17 24 1 8 15 3rd row, 5th
2nd row 23 5 7 14 16 column
element
A introduction to Matlab ANS Solutions
3rd row 4 6 13 20 22
4th row 10 12 19 21 3 Elements of 4th row to 5th row
5 th row
11 18 25 2 9 and 1stcol and 2ndcol
>> m(:,:) ----‘:’ all rows and all columns. Here ‘,’ is the separator between rows and cols
ans =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
Elements of 2nd row and
10 12 19 21 3
all (:) columns
11 18 25 2 9
>> m(1,:) ------------------ display elements of 1st row, all columns
ans =
17 24 1 8 15
>> m(:,3) -------------------- display elements of all rows, 3rd column
ans =
1
7
13
19
25
> m(1:2,:) -------------- display elements of 1 to 2 rows and all columns
ans =
17 24 1 8 15
23 5 7 14 16
>> m(1:end,:) -------------- display elements of 1 to end rows and all columns, same as
m(:,:)
ans =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> m(1:end,2)-------------- display elements of 1 to end rows and 2nd column
ans =
24
5
6
12
18
>> m(2:3,3:4)--------------- display elements of 2nd to 3rd rows and 3rd to 4th columns
A introduction to Matlab ANS Solutions
ans =
7 14
13 20
>> m(3,6)------------------- error, because m contains only 5 columns
??? Index exceeds matrix dimensions.
>> m(3,5)------------------- display the 3rd row and 5th column element
ans =
22
>> m(3,4:5)----------------- display elements 3rd row , 4th to 5th column
ans =
20 22
21
Some basic functions:
General purpose commands.
helpbrowser - Bring up the help browser.
help - M-file help, displayed at the command line.
helpwin - M-file help, displayed in the help browser.
lookfor - Search all M-files for keyword.
ver - MATLAB, SIMULINK, and toolbox version information.
version - MATLAB version information.
Managing the workspace.
who - List current variables.
whos - List current variables, long form.
workspace - Display Workspace Browser, a GUI for managing the workspace.
clear - Clear variables and functions from memory.
load - Load workspace variables from disk.
save - Save workspace variables to disk.
quit - Quit MATLAB session.
Managing commands and functions.
type - List M-file.
edit - Edit M-file.
open - Open files by extension.
which - Locate functions and files.
Controlling the command window.
echo - Echo commands in M-files.
A introduction to Matlab ANS Solutions
Title
Figure
window
Xlabel
Ylabel
Figure20: Figure window
3D Plotting:
Elementary 3-D plots.
plot3 - Plot lines and points in 3-D space.
mesh - 3-D mesh surface.
surf - 3-D colored surface.
A introduction to Matlab ANS Solutions
Legend
Figure22: Example2
A introduction to Matlab ANS Solutions
Figure23: myimage.bmp
To read a wave file, first copy the wave file to the current directory
Type the following commands at the command prompt to read a wav sound and display
its waveform. (Speech signals are plotted in the form of waves). Let the name of the
speech file be myspeech.wav
>>s=wavread(‘myspeech.wav’); --- the speech matrix will be read into the variable ‘s’.
>>plot(s) ---- plots the sound waveform as shown in figure24
Figure24: myspeech.wav
Type ‘Help functionname’ at the command prompt to get the detailed help about any
functions.