KEMBAR78
What Is Matlab | PDF | Trigonometric Functions | Matrix (Mathematics)
0% found this document useful (0 votes)
103 views42 pages

What Is Matlab

MATLAB INTRODUCTION

Uploaded by

Foru Raju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views42 pages

What Is Matlab

MATLAB INTRODUCTION

Uploaded by

Foru Raju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 42

A introduction to Matlab ANS Solutions

WHAT IS MATLAB ?

MATLAB® is a high-performance language for technical computing. It


integrates computation, visualization, and programming in an easy-to-use environment
where problems and solutions are expressed in familiar mathematical notation.
Typical uses include
 Math and computation Algorithm development
 Data acquisition
 Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including graphical user interface building

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

Figure1: Basic view of Matlab.

The MATLAB System 


The MATLAB system consists of five main parts:
Development Environment. 
Development Environment Include the set of tools and facilities that help us use
MATLAB functions and files. Many of these tools are graphical user interfaces.
Matlab by itself can be used as a calculator, where all the calculations are done at
the command prompt. Matlab is an interactive system whose basic data element is an
array that does not require dimensioning. This allows you to solve many technical
computing problems, especially those with matrix and vector formulations, in a fraction
of the time it would take to write a program in a scalar non interactive language such as C
or FORTRAN. The name MATLAB stands for matrix laboratory.
Matlab is a copyright of MathWorks Incorporation. The MathWorks is committed
to making MATLAB as fast as 3GL programming languages, like C and FORTRAN.
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.

Shows the status


of Matlab.
When Matlab is
processing the
status is
‘BUSY’

Figure2: The Matlab Desktop

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

Figure3: The Command Window

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

Display of the variable after


execution, since ‘;’ is not used
to stop the display.

Variables declared using ‘;’ at the end


and hence there is no display of the
variable and value unlike the variable
‘myvar’

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

>> a=115 is far different from the command


>> A=115 these two commands creates two variables, ‘a’ and assigns 115 and ‘A’ and
assigns the value 115.
The next window in the above listed sequence is The Command History. By its
name we can say that it is nothing but the history of the commands typed at the command
prompt. See figure5 for the Command History.
Statements you enter in the Command Window are logged in the Command
History. All the statements we can see in the command history are the commands typed at
the command prompt. There is a time stamp at the beginning of the window, which
denotes the start of each session of Matlab.

Timestamp marks
the start of each
session

All the commands typed


at the command prompt
on the given date and at
given time

Figure5: The Command History

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.

These are all the


variables created

Figure6: Workspace Browser


Matlab default variable:
In the Matlab browser we can find a variable ‘ans’. This is the default Matlab
variable. Any value declared in Matlab with out a base variable will get stored in the
default variable ‘ans’. E.g. at the command prompt if you say a=5, then the variable a is
stored in the memory with value 5. Now, at the command prompt if you just say 5,
>> 5
then this 5 should be stored in the memory in the name of a variable. Since you have not
provided any variable name, Matlab will take its default variable ‘ans’ and store it in the
workspace.
Saving the Current Workspace:
The workspace is not maintained across MATLAB sessions. When you quit
MATLAB, the workspace is cleared. You can save any or all of the variables in the
current workspace to a MAT-file, which is a MATLAB specific binary file. You can then
A introduction to Matlab ANS Solutions

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

To clear a variable using the Workspace browser:


In the Workspace browser, select the variable, or Shift+click or Ctrl+click to
select multiple variables. To select all variables, choose Select All from the Edit or
context menus. Press the Delete key or click the delete button on the toolbar.
A confirmation dialog box may appear. If it does, click yes to clear the variables.
To delete all variables at once, select Clear Workspace from the Edit menu in the
Workspace browser.
Using the clear function clears all the variables from the workspace.
>>clear
this command clears all the variables from the workspace.
>>clear a ------------clears the variable ‘a’ from the workspace.
>>clear x y z -------clears the variables ‘x’, ‘y’, ‘z’ from the workspace.
We can double-click (See figure7) on any variable to view its contents of the
variable in a new window called the array editor. We can use the Array Editor to view
and edit a visual representation of one- or two-dimensional numeric arrays, strings, and
cell arrays of strings that are in the workspace.
>>openvar(‘v’)
this command directly opens the array editor window of the variable ‘v’
We can also view the contents of the workspace from the command prompt by using
different commands.
>> who
this command displays all the variables that are present in the workspace, as shown
below.
Your variables are:
a ans b c myvar var1
>>whos
this command displays all the variables along with their details that are present in the
workspace, as shown below.
Name Size Bytes Class
a 1x1 8 double array
ans 1x1 8 double array
A introduction to Matlab ANS Solutions

b 1x1 8 double array


c 1x1 8 double array
myvar 1x1 8 double array
var1 1x1 8 double array
Grand total is 6 elements using 48 bytes

Double clicking on the variable


displays the contents of the variable

Figure7: Array Editor.


Here Name is nothing but the name of the variable.
Size is the size of the variable. In Matlab all the variables are considered in the
form of a matrix.
The Matlab language works with only a single object type:
The Matlab array. All Matlab variables, including scalars, vectors, matrices,
strings, cell arrays, structures, and objects are stored as Matlab arrays. In C, the
MATLAB array is declared to be of type m X Array. The m X Array structure contains,
among other things:
 Its type
 Its dimensions
 The data associated with this array
 If numeric, whether the variable is real or complex
 If sparse, its indices and nonzero maximum elements
 If a structure or object, the number of fields and field names
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.

1st row 2nd col


Variable Name

Rows
Columns

1st row 1st th


col 5 row 2nd
col

Variable format

Figure8: Two dimensional variables.


A introduction to Matlab ANS Solutions

>>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

Logical char NUMERIC cell structure


Function Handle

Java classes

User classes

int8,uint8, single double


int16,uint16,
int32,uint32,
int64,uint64
A introduction to Matlab ANS Solutions

Figure9: Data Types.

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

Figure10: Cell array


Structures
A 1-by-1 structure is stored in the same manner as a 1-by-n cell array where n is
the number of fields in the structure. Members of the data vector are called fields. Each
field is associated with a name stored in the m X Array. The members of the structure are
accessed using the dot ‘.’ operator.
Multidimensional Arrays
Matlab arrays of any type can be multidimensional. A vector of integers is stored
where each element is the size of the corresponding dimension. The storage of the data is
the same as matrices.
Empty Arrays
Matlab arrays of any type can be empty. An empty m X Array is one with at least
one dimension equal to zero. For example, a double-precision m X Array of type double,
where m and n equal 0 and pr is NULL, is an empty array.
A introduction to Matlab ANS Solutions

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

Double-click on the file to open


in an appropriate tool

Figure12: Current Directory

The next is The Launch Pad.


The start button at the bottom left corner of the Matlab desktop also provides the
same feature as the launch pad. The Matlab Start button provides easy access to tools,
demos, and documentation. Just click the button to see the options.
A introduction to Matlab ANS Solutions

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

Figure13a: Launch pad and its expanded format.

Figure13b: Matlab start button


A introduction to Matlab ANS Solutions

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.

The MATLAB Application Program Interface (API)


Matlab provides interfaces to external routines written in other programming
languages, data that needs to be shared with external routines, clients or servers
communicating via Component Object Model (COM) or Dynamic Data Exchange
(DDE), and peripheral devices that communicate directly with MATLAB. Much of this
interface capability was formerly referred to as the Matlab Application Program Interface,
or API.
Matlab API is a library that allows us to write C and Fortran programs that
interact with Matlab. It includes facilities for calling routines from MATLAB (dynamic
A introduction to Matlab ANS Solutions

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.

* indicates file not saved

Position of the cursor


inside the edit window

Figure14: Edit window Indicates that this file


is a script 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

Figure15: Running a file which is not in the current directory


First Program:
The figure16 shown below shows the edit window with a program written to fine
the factorial of a number. ‘%’ is used to write the comments with in the window.

Commented
statements are
displayed in green
color

Figure16: First program


A introduction to Matlab ANS Solutions

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.

All the key words


will be displayed in
blue

Every function must be saved in


the name of its function

Figure17: Creating a function


If the above file is run, then it returns the following error,
??? Input argument 'fact' is undefined.
Error in ==> D:\MATLAB6p5\work\fact23.m
On line 8 ==> for i=1:fact
That means variable fact is not initialized but used. But observe that the above file is a
function and the variable fact is an input argument. He following statement executes the
file
>>fact123(5)
i.e. name of the function with the value as the argument.
A introduction to Matlab ANS Solutions

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

Figure18: Break point Figure19: Execution stops at breakpoint


A introduction to Matlab ANS Solutions

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

Operator Precedence Level


Highest
() Precedence
~ (negation)
.' .^ ' ^ + (unary plus) - (unary minus)
.* ./ .\ * / \
+ (addition) - (subtraction)
: < <= > >= == ~=

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

sin - Sine. sinh - Hyperbolic sine.


asin - Inverse sine. asinh - Inverse hyperbolic sine.
cos - Cosine. cosh - Hyperbolic cosine.
acos - Inverse cosine. acosh - Inverse hyperbolic cosine.
tan - Tangent. tanh - Hyperbolic tangent.
atan - Inverse tangent. atan2 -Fourquadrant inverse tangent.
atanh - Inverse hyperbolic tangent. sec - Secant.
sech - Hyperbolic secant. asec - Inverse secant.
asech - Inverse hyperbolic secant. csc - Cosecant.
csch - Hyperbolic cosecant. acsc - Inverse cosecant.
acsch - Inverse hyperbolic cosecant. cot - Cotangent.
coth - Hyperbolic cotangent. acot - Inverse cotangent.
acoth - Inverse hyperbolic cotangent.
Exponential. Complex.
exp - Exponential. abs - Absolute value.
log - Natural logarithm angle - Phase angle.
log10 - Common (base 10) logarithm. conj - Complex conjugate.
log2 - Base 2 logarithm and imag - Complex imaginary part
dissect floating point number. sqrt - Square root.
real - Complex real part. complex - Construct complex data
from real and imaginary parts.
Rounding and remainder.
fix - Round towards zero. floor - Round towards minus infinity.
ceil - Round towards plus infinity. round - Round towards nearest integer.
rem - Remainder after division. sign - Signum function
mod - Modulus (signed remainder after division).
Precision Format Functions:
Matlab performs all computations in double precision. We can use the format
function to control the output format of the numeric values displayed in the Command
Window. The format function affects only how numbers are displayed, not how Matlab
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.

The table below describes the allowable values for type


Value For Result Example
Type
+ +, -, blank +
bank Fixed dollars and cents 3.14
compact Suppresses excess line feeds to show more output in theta = pi/2
a single screen. Contrast with loose. theta=1.5708

hex Hexadecimal (hexadecimal representation of a binary 400921fb54442d18


double-precision number)
long 15-digit scaled fixed point 3.14159265358979
long e 15-digit floating point 3.141592653589793e+00
long g Best of 15-digit fixed or floating point 3.14159265358979
loose Adds linefeeds to make output more readable. theta=pi/2 theta=1.5708
Contrast with compact
rat Ratio of small integers 355/113
short 5-digit scaled fixed point 3.1416
short e 5-digit floating point 3.1416e+00
short g Best of 5-digit fixed or floating point 3.1416
To change the format from the command prompt, use the following commands,
>>format type
>>format('type')
Arrays:
The following are some of the basic finctions which can create arrays
automatically.
zeros - Zeros array.
ones - Ones array.
eye - Identity matrix.
repmat - Replicate and tile array.
rand - Uniformly distributed random numbers.
randn - Normally distributed random numbers.
A introduction to Matlab ANS Solutions

magic - Magic square.


pascal - Pascal matrix.
linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
: - Regularly spaced vector and index into matrix.
Basic array information:
size - Size of array.
length - Length of vector.
ndims - Number of dimensions.
disp - Display matrix or text.
Accessing Arrays:
>>a=[1 2 3]; creates a 1x3 matrix
>>b=[1,2,3]; creates a matrix same as ‘a’. ‘,’ is used for horizontal concatenation
>>c=[1
2
3]; creates a 3x1 matrix
>>d=[1;2;3]; creates a matrix same as ‘c’. ‘;’ is used for vertical concatenation
>> p=ones(3)
p=
1 1 1
1 1 1
1 1 1
>> q=zeros(4)
q=
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
>> r=rand(2)
r=
0.9501 0.6068
0.2311 0.4860

>> 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

more - Control paged output in command window.


format - Set output format.
beep - Produce beep sound.
Operating system commands
cd - Change current working directory.
delete - Delete file.
dir - List directory.
mkdir - Make directory.
rmdir - Remove directory.
Flow Control:
Programming language constructs.
if - Conditionally execute statements.
else - IF statement condition.
elseif - IF statement condition.
end - Terminate scope of FOR, WHILE, SWITCH, TRY and IF statements.
for - Repeat statements a specific number of times.
while - Repeat statements an indefinite number of times.
break - Terminate execution of WHILE or FOR loop.
continue - Pass control to the next iteration of FOR or WHILE loop.
switch - Switch among several cases based on expression.
case - SWITCH statement case.
otherwise - Default SWITCH statement case.
try - Begin TRY block.
catch - Begin CATCH block.
return - Return to invoking function.
error - Display error message and abort function.
Graphics
MATLAB has extensive facilities for displaying vectors and matrices as graphs,
as well as annotating and printing these graphs. It includes high-level functions for two-
dimensional and three-dimensional data visualization, image processing, animation, and
presentation graphics. It also includes low-level functions that allow you to fully
A introduction to Matlab ANS Solutions

customize the appearance of graphics as well as to build complete graphical user


interfaces on our MATLAB applications.
When you use a plotting command, MATLAB creates the graph using various
graphics objects, such as lines, text, and surfaces (see Graphics Objects for a complete
list). All graphics objects have properties that control the appearance and behavior of the
object. Matlab enables us to query the value of each property and set the value of most
properties. These graphics are created in one more window called the figure window.
Whenever MATLAB creates a graphics object, it assigns an identifier (called a
handle) to the object. You can use this handle to access the object's properties. Handle
Graphics is useful if you want to Modify the appearance of graphs.
Basic Plotting:
Matlab has extensive facilities for displaying vectors and matrices as graphs, as
well as annotating and printing these graphs. These are the few of the most important
graphics functions
2D graphs:
Elementary X-Y graphs.
plot - Linear plot.
loglog - Log-log scale plot.
semilogx - Semi-log scale plot.
semilogy - Semi-log scale plot.
polar - Polar coordinate plot.
plotyy - Graphs with y tick labels on the left and right.
Axis control.
zoom - Zoom in and out on a 2-D plot.
grid - Grid lines.
axes - Create axes in arbitrary positions.
subplot - Create axes in tiled positions.
Graph annotation.
legend - Graph legend.
title - Graph title.
xlabel - X-axis label.
A introduction to Matlab ANS Solutions

ylabel - Y-axis label.


text - Text annotation.
Example plots:
Write the following program to get the output, a sign plot
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
Now label the axes and add a title. The characters pi creates the symbol .
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)

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

fill3 - Filled 3-D polygons.


Color control.
colormap - Color look-up table.
Color maps.
hot - Black-red-yellow-white color map.
gray - Linear gray-scale color map.
bone - Gray-scale with tinge of blue color map.
copper - Linear copper-tone color map.
pink - Pastel shades of pink color map.
white - All white color map.
jet - Variant of HSV.
autumn - Shades of red and yellow color map.
spring - Shades of magenta and yellow color map.
winter - Shades of blue and green color map.
summer - Shades of green and yellow color map.
Graph annotation.
title - Graph title.
xlabel - X-axis label.
ylabel - Y-axis label.
zlabel - Z-axis label.
colorbar - Display color bar (color scale).
text - Text annotation.
Specialized plots:
Specialized 2-D graphs.
bar - Bar graph.
barh - Horizontal bar graph.
compass - Compass plot.
errorbar - Error bar plot.
ezplot - Easy to use function plotter.
ezpolar - Easy to use polar coordinate plotter.
feather - Feather plot.
A introduction to Matlab ANS Solutions

fill - Filled 2-D polygons.


fplot - Plot function.
hist - Histogram.
pie - Pie chart.
Contour and 2-1/2 D graphs.
contour - Contour plot.
contourf - Filled contour plot.
contour3 - 3-D Contour plot.
ezcontour - Easy to use contour plotter.
ezcontourf - Easy to use filled contour plotter.
Specialized 3-D graphs.
bar3 - 3-D bar graph.
bar3h - Horizontal 3-D bar graph.
ezgraph3 - General purpose surface plotter.
ezmesh - Easy to use 3-D mesh plotter.
ezmeshc - Easy to use combination mesh/contour plotter.
ezplot3 - Easy to use 3-D parametric curve plotter.
ezsurf - Easy to use 3-D colored surface plotter.
ezsurfc - Easy to use combination surf/contour plotter.
meshc - Combination mesh/contour plot.
meshz - 3-D mesh with curtain.
pie3 - 3-D pie chart.
stem3 - 3-D stem plot.
The following program creates a 3D plot as shown in figure
[X,Y] = meshgrid([-2:0.1:2]);
Z = X.*exp(-X.^2-Y.^2);
plot3(X,Y,Z);grid on
A introduction to Matlab ANS Solutions

Figure21: Example 3D plot


Example2:
x = -pi:pi/20:pi;
plot(x,cos(x),'-ro',x,sin(x),'-.b')
h = legend('cos','sin',2);
the above code results in the following output

Legend

Figure22: Example2
A introduction to Matlab ANS Solutions

Images display and file I/O:


imshow - Display image.
imagesc - Scale data and display as image.
colormap - Color look-up table.
imread - Read image from graphics file.
imwrite - Write image to graphics file.
imfinfo - Information about graphics file.
Movies and animation:.
capture - Screen capture of current figure.
getframe - Get movie frame.
movie - Play recorded movie frames.
frame2im - Convert movie frame to indexed image.
im2frame - Convert index image into movie format.
Speech reading:
Speech file import and export.
wavread - Read Microsoft WAVE (".wav") sound file.
wavwrite - Write Microsoft WAVE (".wav") sound file.
Audio hardware drivers.
sound - Play vector as sound.
soundsc - Autoscale and play vector as sound.
wavplay - Play sound using Windows audio output device.
Examples of ‘imread and ‘wavread’:
To read an image, first copy the mage file to the current directory.
Let the name of the image be myimage.bmp. then type the following command at the
command prompt
>>a=imread(‘myimage.bmp’); ------- the image matrix will be read into the variable ‘a’.
>>imshow(a) ------- displays the matrix a in the figure window.
at the execution of the above commands, the following figure window appears displaying
the figure23.
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.

You might also like