MATLAB:
1. Acronym for MATRIX LABORATORY
2. Mathworks Inc.
3. Current version 8.6 R2015b
4. Language for technical computing.
5. Computation, visualization and programming
6. Its basic data element is an array (or a matrix) that does not
require dimensioning.
7. MATLAB is widely used in the engineering, science, and
mathematics curricula at more than 2,500 colleges and
universities worldwide.
8. more than 1000 MATLAB based textbooks
Entering matrices:
1) Enter an explicit list of elements.
2) Load matrices from external data files.
3) Generate special matrices using built-in functions.
4) Create matrices with your own functions in M-files.
16 3 2 13
5 10 11 8
9 6 7 12
Semicolon to suppress
4 15 14 1 output
>>A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1];
>> A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Once you have entered the matrix, it is automatically
remembered in the MATLAB workspace. You can refer to it
simply as A.
>>sum(A)
>> ans =
34 34 34 34
When you do not specify an output variable, MATLAB uses the
variable ans, short for answer, to store the results of a calculation.
Variable is the name given to the region in memory. Variable does
not require any type declarations or dimension statements.
Rules for writing variable names:
1. first character must be letter, others can be letters, numbers
and underscore(_) character, only first 63 characters are
significant.
2. MATLAB is case-sensitive in the names of commands,
functions, and variables. For example, Error is not the same as
error.
3. When naming a variable, make sure you are not using a name
that is already used as a function name. If you do define a
variable with a function name, you will not be able to call that
function until you clear the variable from memory.
4. It can not be the keyword.
5. MATLAB uses the characters i and j to represent imaginary
units. Avoid using i and j for variable names if you intend to use
them in complex arithmetic.
When MATLAB encounters a new variable name, it automatically
creates the variable and allocates the appropriate amount of
storage.
If the variable already exists, MATLAB changes its contents and, if
necessary, allocates new storage. For example,
n = 25
creates a 1-by-1 matrix named n and stores the value 25 in its
single element. To view the matrix assigned to any variable,
simply enter the variable name.
Built-in Variables
Do not reassign the values to these built-in variables.
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Subscripts
The element in row i and column j of A is denoted by A(i,j).
A(4,2) is 15.
The Colon Operator „:‟
A(2,:) 5 10 11 8 A(3,2:4)6 7 12
A(:,3) 2
11
7
14
matrix operations in MATLAB:
1) + addition
2) − subtraction
3) * multiplication
4) ^ power
A
5) ' conjugate transpose
6) \ Left division
7) / right division
If A is an invertible square matrix and b is a
compatible column, then
x = A\b is the solution of A* x = b and,
x = b/A is the solution of x *A = b.
:
>> a=[1 2 3;4 5 6]
size(x): returns number of rows
and columns in the matrix x a=
length(x): returns the length of 1 2 3
vector X ,equivalent to 4 5 6
max(size(x))
>> size(a)
ans =
2 3
>> length(a)
ans =
3
+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element division
.\ Element-by-element left division
.^ Element-by-element power
.' Unconjugated array transpose
>> u = [ 10 -11 12]; w = [2 1 3];
The scalar product is defined by
multiplying the corresponding
elements together and adding
the results to
give a single number (scalar).
>> u*w
??? Error using ==> *
Inner matrix dimensions must agree.
>> u*w' % u & w are row vectors
ans =
45
>> u.*w
ans =
20 -11 36
Example 1: Find the roots of a polynomial x4 – 12x3 + 25x + 116
Step 1. Type the coefficients of polynomial in array p
>> p = [ 1 -12 0 25 116 ]
Step 2. Use the library function roots()
>> r = roots(p )
Changing the data format
>> value = 12.345678901234567;
format short 12.3457
format long 12.34567890123457
format short e 1.2346e+001
format long e 1.234567890123457e+001
format short g 12.346
format long g 12.3456789012346
format rat 1000/81
Example 2. Solving the system of simultaneous equations
1x1 + 2x2 + 3x3 = 366
4x1 + 5x2 + 6x3 = 804
7x1 + 8x2 + 0x3 = 351
Step 1. Enter coefficient matrix as:
>> A = [ 1 2 3 ; 4 5 6 ; 7 8 0 ]
Step 2. Enter b matrix as:
>>b = [ 366 ; 804 ; 551 ]
Step 3. The values of x1, x2 and x3 can be found out using 3
different ways.
>> x1 = inv (A) * b
x1= x = A\b is the solution of A* x = b
2.7778
66.4444
76.7778
How to solve this by left division?
>> x2=A\b
x2 =
2.7778
66.4444
76.7778
How to solve this by right division?
>>x3=(b'/A')' x = b/A is the solution of x *A = b.
x3 =
2.7778
66.4444
76.7778
Right division is defined in terms of left division by
b/A = (A' \b')'
Which method to use? The answer lies partially in evaluation of
efficiency of algorithm discussed later.
Example 3. Plot a sine function
y = sin (x) 0x 2π
Step 1: Create 30 points between 0 & 2 π and store them in array
x.
Step 2: Find the sine of points in array x
Step 3: Plot command generates a plot
The corresponding commands are as follows:
>> x = linspace(0,2 * pi ,30) ;
>> y = sin (x) ;
>> plot (x,y)
Comments: 1. no labels/title/grid 2. default color and line style 3. data points
Also try the following in continuation with example 3.
To plot cosine on the same axis, type
>> z = cos (x) ;
>> plot ( x, y, x, z)
To plot sine Vs cosine:
>> plot ( y , z)
to place grid on the graph:
>> grid
To place labels on X-axis & Y-axis and to give title to the above
generated graph, use the commands xlabel(), ylabel() and title()
receptively.
Script File :
Instead of typing a series of commands directly in a
command window, this group of commands can be placed into a
file. This file containing commands can then be executed by
typing its name in command window. This file is called as script
file or M-file (since it has a file extension “.m”).
Example 4. Temperature conversion program, which accepts
temperature in Fahrenheit as input through keyboard, converts it
into degree Celsius and outputs the result to screen in a formatted
way.
Step 1. In the command window, select “New-M file” from “File”
menu. A „Editor‟ window will appear. Type in the following lines.
% temperature conversion program
tf = input ( „ Enter the temp. in degree Fahrenheit :‟ ) ;
tc = 5 / 9 * ( tf – 32 ) ;
fprintf ( „ % 6.2 f deg. Fah. = % 6.2 f degree celcius \n‟, tf ,tc);
Step 2. Select „Save ‟ from „File‟ menu. The following dialog box
appears.
Type in the file name as shown. Finally save it by clicking push
button “ Save”.
Step 3. Close/Minimize the Editor window. Type in name of the
program to execute the file in command window.
>>test
Sample runs of program:
Enter the temp. in degree Fahrenheit :100
100.00 deg. Fah.= 37.78 degree celcius
Enter the temp. in degree Fahrenheit :[100 110]
100.00 deg. Fah.=110.00 degree celcius
37.78 deg. Fah.= 43.33 degree celcius
Line 1. % marks the beginning of a comment.
Line 2.‟input‟ function - Allows you to enter data through
keyboard.
Displays a string in the command window and waits for the user to
type in a response. When user types in and presses Enter, that is
stored in the variable on the left.
Line 3. Assignment statement: variable=expression
Line 4. „fprintf‟ function - Allows to display formatted data on the
monitor.
- Displays one or more values along with
the related text.
Conversion Characters in fprintf()
Conversion characters specify the notation of the output.
fprintf(‟ x =%1.12g \n‟,pi)
fprintf(‟ x =%1.10e \n‟,pi)
fprintf(‟ x =%6.2f \n‟,pi)
Conversion specifications begin with the % character and contain
these optional and required elements:
Flags (optional)
Width and precision fields (optional)
A subtype specifier (optional)
Conversion character (required)
You specify these elements in the following order:
Flags
You can control the alignment of the output using any of these optional flags.
Character Description Example
A minus sign (-) Left-justifies the converted argument in %-5.2f
its field.
A plus sign (+) Always prints a sign character (+ or -). %+5.2f
Zero (0) Pad with zeros rather than spaces. %05.2f
Field Width and Precision Specifications
You can control the width and precision of the output by including these
options in the format string.
Character Description Example
Field A digit string specifying the minimum number of %6f
width digits to be printed.
Precision A digit string including a period (.) specifying the %6.2f
number of digits to be printed to the right of the
decimal point.
Conversion Characters
Conversion characters specify the notation of the output.
Specifier Description
%c Single character
%d Decimal notation (signed)
%e Exponential notation (using a lowercase e as in 3.1415e+00)
%E Exponential notation (using an uppercase E as in 3.1415E+00)
%f Fixed-point notation
%g The more compact of %e or %f, as defined in [2]. Insignificant
zeros do not print.
%G Same as %g, but using an uppercase E
%o Octal notation (unsigned)
%s String of characters
%u Decimal notation (unsigned)
%x Hexadecimal notation (using lowercase letters a-f)
%X Hexadecimal notation (using uppercase letters A-F)
Escape Characters
This table lists the escape character sequences you use to specify non-
printing characters in a format specification.
Description
Character
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\\ Backslash
\‘ ‘ or ‘ ‘ (two single quotes) Single quotation mark
%% Percent character
Complex Arithmetic:
z1=1+2i (always interpreted as complex number)
% or you can multiply by i, like this
z1=1+2*i (interpreted as a complex number if i is not
assigned any value)
z2=2-3i
% add and subtract
z1+z2
z1-z2
% multiply and divide
z1*z2
z1/z2
1. complex numbers can be elements of arrays and matrices
2. When working with complex numbers we quite often want to
pick off the real part or the imaginary part of the number, find its
complex conjugate, or find its magnitude. Or perhaps we need
to know the angle between the real axis and the complex
number in the complex plane.
z=3+4i
real(z)
imag(z)
conj(z)
abs(z)
angle(z)
Program: Plot frequency response of RC low pass filter (R=6kΩ, C=1μF)
%frequency response of RC low pass filter
R=16e3;C=1e-6;%Initalization
f=[Link];%create array of input frequencies
res=1./(1+j*2*pi*f*R*C);%calculate response
mag=abs(res);%Magnitude response
ph=angle(res);%Phase response
%Plotting frequency response
subplot(211);
loglog(f,mag);
title('Amplitude response');
xlabel('frequency(Hz)');
ylabel('output/input ratio');
grid on;
subplot(212);
semilogx(f,ph);
title('Phase response');
xlabel('frequency(Hz)');
ylabel('output-input phase');
grid on;
Special Matrices:
% load I with the 4x4 identity matrix
I=eye(4,4)
% load Z with a 5x5 matrix full of zeros
Z=zeros(5,5)
% ones:
% load X with a 3x3 matrix full of ones
X=ones(3,3)
% rand:
% load Y with a 4x6 matrix full of random numbers between 0 and
1
% The random numbers are uniformly distributed on [0,1]
Y=rand(4,6)
Example 5: subplot function
%example for subplot function
x=0:1/100:1;%crates a row vector 1x101
y=sin(3*pi*x);
subplot(221) (or subplot(2,2,1))
subplot(221), plot(x,y)
species that the figure
xlabel('x'),ylabel('sin 3 pi x')
window should be split into a
subplot(222), plot(x,cos(3*pi*x))
2x2 array and we select
xlabel('x'),ylabel('cos 3 pi x')
the first subwindow.
subplot(223), plot(x,sin(6*pi*x))
xlabel('x'),ylabel('sin 6 pi x')
subplot(224), plot(x,cos(6*pi*x))
xlabel('x'),ylabel('cos 6 pi x')
title(„sinusoids of different frequencies‟);
Programs:
Program 6. Plot a function f(x)=sin(2x) and its derivative on the
same plot
Source code:
%plotting function and its derivative
x=0:pi/20:2*pi;
y1=sin(2*x);
y2=2*cos(2*x);
plot(x,y1,'r--',x,y1,'b*',x,y2);
xlabel('x');
ylabel('y');
title('Plot of f(x)=sin(2x) and its derivative');
grid on;
Program 7. Write MATLAB script file that returns the equivalent
resistance of series combination of R1, R2 and R3 where R1 =
100 Ω, R2 = 90 Ω, R3 = 10 Ω.
% Equivalent resistance of series combination
Resist = [100 90 10];
Requi = sum(Resist);
disp(„********************************‟)
disp(„The equivalent resistance is=‟); disp(Requi);
disp(„ Ohms‟)
disp(„********************************‟)
*************************************************
The equivalent resistance is =
200 Ohms
*************************************************
MATLAB file types
M-files: 1. ASCII text files with .m extension to the filename.
2. Two types: script files
function files
3. All library functions are M files
4. Some are in compiled format (cannot be modified)
while others are in pre-compiled format
(can be copied and modified)
MAT files: 1. binary data files with .mat as extension to the
filename.
2. created when data is saved on the secondary
storage with save command.
3. can be brought to the workspace using load
command for the new session
FIG files 1. binary figure files with a .fig extension to the
filename
2. can be saved in other formats such as jpeg, bmp
etc. for inclusion in MS Word or PowerPoint
P- files: 1. compiled M-files with a .p extension
2. can be executed in MATLAB without being parsed and
compiled.
MEX files: MALTAB callable Fortran and C programs with a .mex
extension to the filenames.
Program 9: Write a script file to draw a circle of radius r
%a script file to draw a circle of radius r
r=input('Enter radius of a circle:');
theta=linspace(0,2*pi,100);
x=r*cos(theta);
y=r*sin(theta);
plot(x,y);
axis('equal');%to set the scale of both axes same
title(['Circle of radius ',num2str(r)]);
to label plot with numerical values
Program 9: Write a function file to draw a circle of radius r
function[x,y]=draw_circle(r);
%a function file to draw a circle of radius r
theta=linspace(0,2*pi,100);
x=r*cos(theta);
y=r*sin(theta); body of a
plot(x,y); function
axis('equal');%to set the scale of both axes same
title(['Circle of radius ',num2str(r)]);
Function syntax:
keyword Name of function
function[x,y]=draw_circle(r);
Output list Input list
function definition line
1. Function file begins with a function definition line. (If this line is
absent, file is script file).
2. File name should be same as name of function.
How to execute a function?
If function definition line is:
function[x,y]=draw_circle(r);
This function can be called by:
[x1 y1] = draw_circle(r1)
draw_circle(5)
Comparison
%Purely inductive circuit; voltage and current waveforms
%Initialization
V=230; %supply voltage;
f=50; %supply frequency in Hz;
L=20e-3; %Inductance;
no_cycles=2; %number of cycles for plot
delta_t=1e-3; %time increment
%Computation
Vm=sqrt(2)*V; %Voltage amplitude
w=2*pi*f; %supply frequency in rad/s
XL=w*L; %Inductive reactance
T=1/f; %Time period of waveforms
t=0:delta_t:no_cycles*T; %time vector for plot
v=Vm*sin(w*t); %Equation for supply voltage
iL=(Vm/XL)*sin(w*t-pi/2); %Equation for current through L
%Plotting
plot(t,v,t,iL);grid;
xlabel('Time(s)'); ylabel('v(V) and iL(A)');
title('voltage and current waveforms in purely inductive circuit');
gtext('v');gtext('iL');
Place text with mouse
two ways to create a new function 1. as a file saved to permanent storage
2. at a command prompt or in a script file
provide quick means of 1. Inline functions
creating simple functions
without having to store a 2. Anonymous functions
user function to a file
each time
Syntax of writing anonymous functions:
variable = @ (var1,var2,...) expression
where „variable' is the name of the variable to which handle of the function is
assigned.
'var1', 'var2', etc. are a comma separated list of arguments of the function,
'expression' is a single mathematical expression involving those variables.
The expression can include any built-in or user-defined functions.
A function handle is a value that provides a means of calling
(referencing) a function indirectly. When a function handle is
created, MATLAB captures all the information needed to execute
the function at any time.
Inline functions
Similar to anonymous function, inline function is a single-line,
user-defined function that is defined without creating a separate
function file (M-file). Inline functions are gradually being replaced
by anonymous functions.
An inline function is created with the inline command according
to the following format:
name_of_function = inline('mathematical expression typed as a
string')
The statement below creates an anonymous function that finds
the square of a number. The @ operator constructs a function
handle for this function, and assigns the handle to the output
variable sqr.
>>sqr = @(x) x.^2;
>>a = sqr(5)
a=
25
>> sqr([2 3])
ans =
4 9
>> F=inline('x.^2');
>> F(5)
ans =
25
Anonymous functions are meant to supersede inline functions.
They are more powerful and far less prone to errors, especially
when passed to other functions.
The syntax is not very attractive, but they are very convenient and
are faster to evaluate than inline function.
Workspaces in MATLAB
• MATLAB (or Base) Workspace:
For command line and script file variables.
• Function Workspaces:
Each function has its own workspace for local variables.
Communicate to Function Workspace via inputs &
outputs.
(Promotes structured coding & prevents name
conflicts.)
• Global Workspace:
Global variables can be shared by multiple workspaces.
(Must be initialized in all relevant workspaces.)
using Global Variables
• Don‟t use global variables as far as possible.
• Can be used to share large volume of data among many
functions so that data does not have to copied each time
a function is called.
• If you absolutely must use them:
– Avoid name conflicts
– whos global (List current global variables, long form)
– clear global (Removes 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.
Do the same thing at the command line if you want the base workspace to
access the variable.
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.
function h = falling(t) The two global statements make the
global GRAVITY value assigned to GRAVITY at the
h = 1/2*GRAVITY*t.^2; command prompt available inside the
function.
You can then modify GRAVITY
>>global GRAVITY interactively and obtain new solutions
>>GRAVITY = 32; without editing any files
>>y = falling((0:.1:5)');
Comparing efficiency of algorithms: flops, tic and toc.
Two measures of the efficiency of an algorithm :
the number of floating point operations (flops) performed
the elapsed time
The old versions of MATLAB had function flops to keep a running
total of the flops performed.
However, it is no longer available.
Revisiting Example 2. Solving the system of simultaneous
equations
1x1 + 2x2 + 3x3 = 366
4x1 + 5x2 + 6x3 = 804
7x1 + 8x2 + 0x3 = 351
>>A = [ 1 2 3 ; 4 5 6 ; 7 8 0 ];
>>b = [ 366 ; 804 ; 551 ];
The values of x1, x2 and x3 can be found out using
>>x = inv (A) * b
or
>>x=A\b
>>tic, x = inv (A) * b; toc
>>tic, x = A\b; toc
>> tic,x = inv (A) * b;toc
Elapsed time is 0.000208 seconds.
>> tic,x = A\b;toc
Elapsed time is 0.000088 seconds.
It should be noted that, on timesharing machines, elapsed time
may not be a reliable measure of the efficiency of an algorithm
since the rate of execution depends on how busy
the computer is at the time.