You are on page 1of 66

# INTRODUCTION

TO

MATLAB

## Indian Institute of Technology Guwahati 1

OUTLINE
What is MATLAB?
Basics of MATLAB
MATLAB Windows, Input-Output, File Types, A few general commands
Number Arrays, Simple Plots, Script File, Function File, Data Handling, Anonymous
Function, Symbolic Computation

Interactive Computation
Matrices, Vectors and Array operations, Character Strings, Command Line Functions,

## Indian Institute of Technology Guwahati 2

What is MATLAB?
MATLAB is a high-performance language for technical computing. MATLAB stands
for MATrix LABoratory.
It integrates computation, visualization, and programming in an easy-to-use
environment.
Problems and solutions are expressed in familiar mathematical notation.
Applications
Maths and Computation
Algorithm Development
Modeling and Simulation
Data Analysis
Scientific and engineering graphics
Ref : http://cimss.ssec.wisc.edu/wxwise/class/aos340/spr00/whatismatlab.htm
Indian Institute of Technology Guwahati 3
Basics of MATLAB, (MATLAB Windows)
MATLAB works through three basic windows
MATLAB Desktop

Figure Window

Editor Window

## Indian Institute of Technology Guwahati 4

Basics of MATLAB, (MATLAB Windows)

## Indian Institute of Technology Guwahati 5

Basics of MATLAB, (MATLAB Windows)
MATLAB Desktop comprises of the following sub windows
Command Window

## MATLAB Command Prompt >>

All commands are run in the command prompt
Current Folder or Current Directory Pane
All files from current directory are listed here.

Workspace

Command History

## Indian Institute of Technology Guwahati 6

Basics of MATLAB, (MATLAB Windows)

## Indian Institute of Technology Guwahati 7

Basics of MATLAB, (MATLAB Windows)

FIGURE WINDOW
EDITOR WINDOW

## Indian Institute of Technology Guwahati 8

Basics of MATLAB
On-line help documentation
help, helpwin and helpdesk
MATLAB performs interactive computation
Takes input from the screen and flushes output onto the screen.
Can read input files and write output files.

## Data types in MATLAB

Fundamental data type in MATLAB is an array.
It encompasses following type of data.
Integers, Doubles, Matrices, Character Strings, Structures and Cells.
Dimensioning of data is automatic in MATLAB.
Variable declaration is case sensitive.

## Indian Institute of Technology Guwahati 9

Basics of MATLAB
File types in MATLAB
o Five main file types are there in MATLAB
M-files (.m extension)
Script and function files comes under this category.
Mat files (.mat extension)
.mat files are used to save data.
save command is used to save data.
Fig-files (.fig extension)
This are figure files.
Contains 2D or 3D plots.
Other less commonly used files are P-files and Mex-files.

## Indian Institute of Technology Guwahati 10

Basics of MATLAB
Some useful commands to be remembered
Workspace Information
Command Function
clc clears command window, cursor moves to the top
home scrolls the command window to put the curser on top
clf clears figure window
Directory Information

Command Function
pwd shows the current working directory
cd changes the current working directory
dir lists contents of the current directory
ls lists contents of the current directory, same as dir
path gets or sets MATLAB search path
editpath modifis MATLAB search path
copyfile copies a fie
Indian Institute of Technology Guwahati 11
Basics of MATLAB
Some useful commands to be remembered
Directory Information
Command Function
mkdir creates a directory

General Information
Command Function
computer tells you the computer type you are using
clock gives you wall clock time and date as a vector
date tells you the date as a string
more controls the paged output according to the screen size
ver gives the license and the MATLAB version information
bench benchmarks your computer on running MATLAB
compared to other computers

Basics of MATLAB

## Indian Institute of Technology Guwahati 13

Basics of MATLAB
Some useful commands to be remembered
Command Function
help Lists topics on which help is available
helpwin Opens the interactive help window
helpdesk opens the web browser-based help facility
help topic provides help on topic
Workspace Information
Command Function
who lists variables currently in the workspace
whos lists variables currently in the workspace with their size
what lists M- , Mat- , and Mex-fies on the disk
clear clears the workspace, all variables are removed
clear x y z clears only variables x, y, and z
clear all clears all variables and functions from workspace
Indian Institute of Technology Guwahati 14
Basics of MATLAB

## Indian Institute of Technology Guwahati

Basics of MATLAB
Some useful commands to be remembered
Directory Information
Command Function
ctrl + c local abort , kills the current command execution
quit quits MATLAB
exit same as quit

## Output format in MATLAB

format short
format short e
format long
format long e
format hex
format rat
format bank
Indian Institute of Technology Guwahati 16
Basics of MATLAB
Simple Arithmetic Operators in MATLAB

## Operator Symbol Function MATLAB Command

Addition + Trigonometric sin, cos, tan, cot, sec, csc
Subtraction - Inverse Trigo atan, acos, asin
Multiplication * Trig Degrees sind, cosd, tand
Division / Hyperbolic sinh, cosh, tanh
Exponentiation ^ Exponential exp
Square root sqrt Logarithmic log

## Indian Institute of Technology Guwahati 17

Basics of MATLAB (Tutorial)
Simple Operations
1. Compute the following quantities in MATLAB command window
25 1 1
a) and compare this with (1 ) .
25 1 25

51
b) 5+1
1

## c) 5 , ln 3 , 10 (105 ). [Hint: MATLAB command for log10 is log10(x)

2. Trigonometric functions

number 1.

## Indian Institute of Technology Guwahati 18

Basics of MATLAB (Tutorial)
Simple Operations
In the command window a complex number can be written as 5i or as 5*i.
1. Compute the following quantities using MATLAB

1+5
4 exp 2 exp 2
15

## Working with Arrays of Numbers

An array is a list of numbers or expressions arranged in horizontal rows and vertical columns .
An array with one row or column is a vector
An array with m rows and n columns is called a matrix of size .

## Indian Institute of Technology Guwahati 19

Basics of MATLAB (Arrays of Numbers)

## Working with arrays of numbers

A vector array may be a row or a column vector
How to create a row or column vector?
ROW VECTOR
A = [1 2 3 4];
COLUMN VECTOR
B = [4;5;7;8];
Semicolon (;) suppresses the output in
command window.
See the snapshot of command window to the
right.
Indian Institute of Technology Guwahati 20
Basics of MATLAB (Arrays of numbers)
Working with arrays of numbers
How to create a vector of n numbers linearly
(equally) spaced between two
given numbers a and b?
linspace command to create vector of n numbers
between two given numbers.
MATLAB command :- x = linspace(a,n,b)
For more help, type help linspace in MATLAB
command window.

## Indian Institute of Technology Guwahati 21

Basics of MATLAB (Arrays of numbers)

## Working with arrays of numbers

Some basic array operators
Array Function
Operator
.* term-by-term multiplication
./ term-by-term division
.^ term-by-term exponentiation
Example of term by term operation.
Let A and B be two vectors
A = [3 5 7 8]; and B = [7 9 3 2];
. = 3 7 5 9 7 3 8 2 = 21 45 21 16
If term-by-term multiplication is not used, then one has to
use for loop.
term-by-term calculations speed up calculation speeds.
Similarly term-by-term division and exponential operations
may be performed. Indian Institute of Technology Guwahati 22
Basics of MATLAB (Tutorial)
Working with arrays of numbers
1. Equation of a straight line
a) Compute the y-coordinates of a line with slope m = 0 . 5 and the intercept c = -2 at the
following x-coordinates: x = 0, 1.5, 2, 3, 5, 8, 10.
3
2. Create a column vector for with values 0, , , , , 5/4. Taking r = 2, calculate
4 2 4
all the coordinates of the circle ( = cos = sin ) at those . Verify if =
2 + 2 is same for all co-ordinates or not.
3. The terms of a geometric progression are a, ar, ar2, , arn. For a = 1, r = 0.5 and n = 1 to
10, find all the terms of the GP. Also find there sum Sn. To find sum use built in MATLAB
function sum. Type help sum in the MATLAB command prompt.

## Indian Institute of Technology Guwahati 23

Basics of MATLAB
Working with arrays of numbers
How to extract elements from a matrix?
How to define a matrix?

## B = A(:,1:2) extracts the first two columns of the

matrix.
C = A(2:3,2:3) extracts the last four element of the
matrix.
Indian Institute of Technology Guwahati 24
Basics of MATLAB (Tutorial + Simple Plots)
Working with arrays of numbers
Make an array of angle such that = 0,5,10, , 90. Prepare a matrix M =
[sind ; cosd ; tand ] . Now extract the values of sin and tand for = 0,45 and
cos for = 45,90 .

## Indian Institute of Technology Guwahati 25

Basics of MATLAB (Tutorial + Simple Plots)

>> theta=[0:5:90];
>> M =[ sind(theta); cosd(theta); tand(theta)];

>> M(:,theta==45)

ans =

0.7071
0.7071
1.0000

>> M(:,theta==0)

ans =

0
1
0
Indian Institute of Technology Guwahati 26
Basics of MATLAB (Tutorial + Simple Plots)

Simple Plots
Some simple commands related to plots. On-line help, type help plot in CW

Command Function
plot creates a 2-D line plot
axis changes the aspect ratio of the x-axis and the y-axis
xlabel annotates the x-axis
ylabel annotates the y-axis
title puts a title on the plot

## Indian Institute of Technology Guwahati 27

Basics of MATLAB (Simple Plots)

## Indian Institute of Technology Guwahati 28

Basics of MATLAB (Tutorial)
Simple Plots
1. Define [0, 2]. Calculate 1 = sin and 2 = cos . Plot the graph with small cicrles
o and in black color in two different figures.
2. For the previous case superpose the two plots in a single figure. (hold on command)
3. Define t : 0 20. Calculate = sin , = cos . Plot a 3-D graph using
command plot3(x,y,t).
4. Define = 0 10 1000 and calculate = 3 . Plot . log , log . and
log . log . Use semilogx, semilogy and loglog commands.

## Indian Institute of Technology Guwahati 29

Basics of MATLAB (Script files)

## Why a script file?

Small operations can be performed in the command window, but long multiple sequence
codes cannot be written in CW.
Programs written in CW cannot be saved.
What is a script file?
A script file is a user-created fie with a sequence of MATLAB commands in it .
The file must be saved with a .m extension to its name, thereby, making it an M-file.
A script file is executed by typing its name (without the .m extension) at the command
prompt

## Indian Institute of Technology Guwahati 30

Basics of MATLAB (Script files)

TOOLSTRIP

TOOLSTRIP

## Indian Institute of Technology Guwahati 31

Green Arrowhead Basics of MATLAB (Script files)

Script file can also be executed by pressing the green arrowhead in the toolstrip or by
pressing F5
Error indicator strip at the extreme right end.
Indian Institute of Technology Guwahati 32
Basics of MATLAB (Script files)

TOOL STRIP

## Indian Institute of Technology Guwahati 33

Basics of MATLAB (Tutorial: Script files)
Script File
1. Write a script file to draw a circle of arbitrary radius, where the radius of the circle is read
as an input from the user. [Hint:- Use the input command. Type help input in the
MATLAB CW].
2. Plot the graph of the function y = sin 5 cos for [2, 2]. Find the roots of this
equation graphically when y = 0.

## Indian Institute of Technology Guwahati 34

Basics of MATLAB (Function files)
Function files
A function file is also an M-file. just like a script file.
A function file has a function definition line on the top that defines the input and output
explicitly.

## Indian Institute of Technology Guwahati 35

Basics of MATLAB (Function files)
Function files
Typical example of a function file which take radius as an input from the user and gives area
and perimeter as output is shown below.

## This is the function file which is being called.

This is a script file which calls the
Indian Institute of Technology Guwahati 36
function file
Basics of MATLAB (Nested Function files)
Function files
It is possible to write a nested function file within a function file.
Maximum area of a rectangle from a number of rectangles can be calculated from given
values of length and breadths. The simple MATLAB code is shown below.

## Script file will call the function file.

The function file will then call the nested function file.
Indian Institute of Technology Guwahati CW output 37
Basics of MATLAB (Matrix Manipulation)
Arrays and Matrices Re-visited
Objective: To be familiar with Matrix, Indexing, matrix
manipulations, simple computation etc.
How to enter matrix?
Matrices are entered row-wise.
Rows are separated by semicolons and columns are
separated by spaces or commas.
Matrices are entered row-wise.
Element Aij of matrix A is accessed as A(i,j) .
Correcting any entry is easy through indexing.
Any sub-matrix of A is obtained by using range
specifiers for row and column indices.
Indian Institute of Technology Guwahati 38
Basics of MATLAB (Arrays and Matrices)

The colon
by itself as a
row or A row or a
column column of a
index matrix is deleted
specifies all by setting it to a
rows or null vector [ ] .
columns of
the matrix.

## Indian Institute of Technology Guwahati 39

Basics of MATLAB (Arrays and Matrices)
Matrices are
transposed
using the single
right-quote
character: (').

MATRIX
multiplication
is well defined
between
compatible
pairs. Their
dimensions
must agree

## Indian Institute of Technology Guwahati 40

Basics of MATLAB (Arrays and Matrices)

Square of a matrix

Concatenation of matrix
repmat command
is used to replicate
element-by- a matrix
element squaring

## Indian Institute of Technology Guwahati 41

Basics of MATLAB (Arrays and Matrices)
Commands Function of the command
Useful zeros a matrix filled with zeros
Matrix ones a matrix filled with ones
Generator rand a matrix with uniformly distributed random elements
randn a matrix with normally distributed random elements
eye identity matrix

## Indian Institute of Technology Guwahati 42

Basics of MATLAB (Arrays and Matrices)

## end command may be used as a subscript to find the end

elements of a vector or a matrix.

## Indian Institute of Technology Guwahati 43

Basics of MATLAB (Arrays and Matrices)

## Transpose of a complex matrix

Be careful when taking the
transpose of complex
matrices. The transpose
operator takes the complex
conjugate transpose
To take the transpose
without conjugating the
complex elements, use the .
operator.
Inverse of a matrix can be
found using inv command
Indian Institute of Technology Guwahati 44
Basics of MATLAB (Arrays Tutorial)

## Indian Institute of Technology Guwahati 45

Basics of MATLAB (Arrays Tutorial)

0 A(6:15,6:15)=zeros(10,10) A(1:5,16:20)=zeros(5,5)
0 0

2
2
2 4

4 8
4
10

12
6
6 14

16

8 18
8
20

0 5 10 15 20
10 nz = 275
10

12 A(16:20,16:20)=zeros(5,5)
12 0

2
14
14 4

16 8
16
10

12
18
18 14

16

20 18
20
20

0 5 10 15 20
0 5
Indian Institute
10
of Technology
15
Guwahati
20
0 5 10
nz = 250
15 20
46
nz = 400
nz = 300
Basics of MATLAB (Arrays Tutorial)

## Indian Institute of Technology Guwahati 47

Basics of MATLAB (Arrays Tutorial)

A=diag(1:6)+diag(7:11,1)+diag(12:15,2)+diag(16:18,3)+diag(19:20,4)+diag(21,5)

A= triu(A,1)'+A

## Indian Institute of Technology Guwahati 48

Basics of MATLAB (Arrays Tutorial)

## Indian Institute of Technology Guwahati 49

Basics of MATLAB (Arrays Tutorial)

>> A=rand(10);
>> A=A.*100;
>> A=fix(A);
>> A(A<10)=0;
>> A(A>90)=inf;
Indian Institute of Technology Guwahati 50
>> b = A(30<=A<=50);
Basics of MATLAB (Arrays Tutorial)

## Indian Institute of Technology Guwahati 51

Basics of MATLAB (Arrays Tutorial)

## >> fun =inline('x.^2+sin(x.*y)+y.^2');

>> x=inline('t'); >> ezcontour(fun,[-pi/2 pi/2 -pi/2 pi/2])
>> y=inline('exp(-t/2)');
>> ezplot(x,y,[0 pi/2]) >> r = inline('1+cos(theta)'); >> H = inline('x.^2/2+(1-cos(y))');
>> ezpolar(r,[0 2*pi]) >> ezsurfc(H,[-pi pi -2 2])

## Indian Institute of Technology Guwahati 52

Basics of MATLAB (Working with Anonymous Functions)

## Indian Institute of Technology Guwahati 53

Basics of MATLAB (Working with Anonymous Functions)

## Indian Institute of Technology Guwahati 54

Basics of MATLAB (Working with Anonymous Functions)

## Indian Institute of Technology Guwahati 55

Basics of MATLAB (Symbolic Computation)

## Indian Institute of Technology Guwahati 56

Basics of MATLAB (Publishing Reports)
MATLAB includes an automatic report generator called publisher. This publisher is accessible, like many other
utilities , both from the menu and the command line.

The publisher publishes a script in several formats , including HTML , XML , MS Word, PowerPoint , and Latex

First , open a new file in the editor and enter the following lines (including blank lines) . The only thing new here is the double
percent (%%) character. It indicates the beginning of a new cell

The text in a line beginning with %% is used as the title of that section (or cell) by the publisher

## Indian Institute of Technology Guwahati 57

Basics of MATLAB (Publishing Reports)

## %%Publishing reports-A simple Example

%%A Spiral Plot
% Let us plot a spiral given by
%r(t) = exp(-theta/10), 0<=theta<=10*pi

## theta = linspace(0,10*pi,200); %200 linearly spaced points

between 0 and 10*pi

r= exp(-theta/10); %compute r

## %% Now plot theta vs r using polar plot

polar(theta,r)

publish('Report_Generation','html')

cd html;
open Report_Generation.html
Indian Institute of Technology Guwahati 58
Basics of MATLAB (Graphics and GUI)

## Indian Institute of Technology Guwahati 59

Basics of MATLAB (Graphics and GUI)

## Indian Institute of Technology Guwahati 60

Basics of MATLAB (Graphics and GUI)

## Indian Institute of Technology Guwahati 61

Basics of MATLAB (Graphics and GUI)

## Indian Institute of Technology Guwahati 62

Basics of MATLAB (Graphics and GUI)

## Indian Institute of Technology Guwahati 63

Basics of MATLAB (Graphics and GUI)

## Indian Institute of Technology Guwahati 64

Basics of MATLAB (Graphics and GUI)

## Indian Institute of Technology Guwahati 65

Basics of MATLAB (Graphics and GUI)
Change the value and observe
the change in the Plot