0% found this document useful (0 votes)
24 views23 pages

Introduction

The document provides an overview of MATLAB, a numerical computing environment and programming language, detailing its advantages and disadvantages. It covers various topics including arithmetic operators, variable types, arrays, matrix operations, and control flow structures like if/else and switch statements. Additionally, it highlights built-in functions and commands for efficient programming within MATLAB.

Uploaded by

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

Introduction

The document provides an overview of MATLAB, a numerical computing environment and programming language, detailing its advantages and disadvantages. It covers various topics including arithmetic operators, variable types, arrays, matrix operations, and control flow structures like if/else and switch statements. Additionally, it highlights built-in functions and commands for efficient programming within MATLAB.

Uploaded by

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

MTH 250: MATHLAB II

1
Programming
with MATLAB
© Md. Mamun-Ur-Rashid Khan, MTH – 250
What is MATLAB ?
2

* MATLAB stands for Matrix Laboratory


* MATLAB is a numerical computing environment and programming language
* Created by the MathWorks, MATLAB allows easy
# Matrix manipulation
# Plotting of functions and data
# Implementation of Algorithms

Advantages of MATLAB
* Quick and easy coding
• * Works with matrices easily
• * Lots of predefined functions (solve, dsolve etc.)
• * High quality graphics and visualization
• * m-files are portable
• * Extensive documentation (‘help’)
© Md. Mamun-Ur-Rashid Khan, MTH – 250
Disadvantages of MATLAB
3
* Uses a large amount of memory and slow the computer
* Expensive software

MATLAB Windows

1. MATLAB Windows

Command Current Command


Workspace
Window Directory History

2. Editor Window 3. Figure Window


© Md. Mamun-Ur-Rashid Khan, MTH – 250
Arithmetic Operators
4
Operations Symbol Example
Addition + 5+3
Subtraction - 5-3
Multiplication * 5*3
Right Division / 5/5
Left Division \ 5\1=1/5
Exponentiation ^ 5^2=25

Order of Precedence
Precedence Mathematical Operation
First Parenthesis, For nested innermost are executed first
Second Exponentiation
Third Multiplication, Division (equal precedence)
Fourth Addition and Subtraction
© Md. Mamun-Ur-Rashid Khan, MTH – 250
Using MATLAB as a calculator
5  >> 12^3+(3+2*5)
 >> 12+(2*6-4*(4+6^5)) etc.

Using “help” command


>> help sum

Some Useful Built in commands


clc delete log asinh real ceil
clear pwd log10 rem imag fix
clear all disp sqrt sinh mean floor
quit fscanf acos mod median round
who fprintf gcd abs std sign
whos input sin angle rand sum
cd exp factorial conj randn prod
© Md. Mamun-Ur-Rashid Khan, MTH – 250
6
Variable Name = Variable Value
 Variable Name :
• combination of letters (a-z, A-Z), numbers (0-9) and underscore (_);
• must begin with a letter;
• case sensitive (a and A are different)

 Variable Value :
• integer : 2 -3 12 -35 40
• double precision : 2.1 -3.07
• scientific notation : 2.1E-8 3.07E+10
• complex : i j 2.1i 3-j
• others : pi NaN inf nan
• string : ’abc’ ’abcdefg123’ ’2’

© Md. Mamun-Ur-Rashid Khan, MTH – 250


7 Numeric Variable String Variable Expression Involving
Variables

>> x=4 >> name=’myname’ >> x=2; y=3.7;


x= name = >> xy=x*y
4 myname xy =
7.4000
>> y0=5+3.3i >> my_string=’best’
y0 = my_string = >> x=3.2; y=5.1; z=-1.7;
5+3.3i best a=2; b=1;
>> XYZ=3*x+y^a+b/z
XYZ =
35.0218

© Md. Mamun-Ur-Rashid Khan, MTH – 250


Arrays
8

What is an array?

* An array is the fundamental unit of data in MATLAB.


* It is either a vector (1 × n and m × 1) or a matrix (m × n).
* A scalar is a 1 × 1 array.
* Arrays with higher dimension can also be defined, but they are difficult to handle.

row vector (1 × n): column vector (m × 1) :


>> x = [1 2 3] >> y = [1;2;3]
x= y=
123 1
2
3

© Md. Mamun-Ur-Rashid Khan, MTH – 250


9 Matrix (m × n) : semicolon concatenates arrays in up-down direction, whereas
space concatenates them in left-right direction.

>> A=[5 6 ; 7 8] >> a=[1 2; 3 4] >> aA=[a A]


A= a= aA =
56 12 1256
78 34 3478
Range
Form: startvalue:increment:lastvalue
• The default step size is 1. • The users can specify their • The step size can be
own step size. negative.
>> a = 1:10
a= >> b = 2:0.2:3 >> c = .8 : -0.3 :-.8
1 2 3 4 5 6 7 8 9 10 b= c=
2.0000 2.2000 2.4000 2.6000 0.8000 0.5000 0.2000 -0.1000 -
2.8000 3.0000 0.4000 -0.7000

© Md. Mamun-Ur-Rashid Khan, MTH – 250


Accessing Array Elements

10 Accessing single elements Accessing multiple elements

>> x = [1 2 3]; >> a=[1 1 1; 2 2 2; 3 3 3 ]


>> x(2) a=
ans = 111
2 222
>> z=[1 2 3; 4 5 6]; 333
>> z(2,3) >> a(1,1:3)
ans = ans=
6 111
>> a(2:end, 2:end)
ans =
22
33
Array Making Functions

zeros(m,n) : m × n zero matrix rand(m,n) : m × n matrix of uniform random


ones(m,n) : m × n matrix consisting of one variables
eye(n) : n × n identity matrix randn(m,n) : m × n matrix of normal random
diag(a) : diagonal matrix formed using vector a variables
magic(n) : n × n magic square
© Md. Mamun-Ur-Rashid Khan, MTH – 250
Matrix Operators
A’ or transpose(A) transpose of matrix A
11 det(A) determinant of A
inv(A) inverse of matrix A
A’ Hermitian transpose of matrix A
conj(A) complex conjugate of matrix A

Array Arithmetic
Sum Difference
>> A=[1 1; 2 2]; >> DIFF=A-B
>> B=[3 3; 4 4]; DIFF =
>> SUM=A+B -2 -2
SUM = -2 -2
44
66
Product Left/Right Division
>> A=[2.3 -1.9; 3 -2]; A\b solves Ax = b
>> B=[-9.3 3*2; 4/3 4]; b/A solves xA = b
>> A*B The left/right matrix division is more
PROD = efficient than inv(A) method
-23.9233 6.2000
-30.5667 10.0000
© Md. Mamun-Ur-Rashid Khan, MTH – 250
Element-wise Operations
12 Often one requires to perform operations on each element of a matrix instead of the
whole matrix.
Example : To compute square of every element of a matrix, one requires A.^2.

Observe the difference between A.^2 and A^2.

>> A = [1 2 ; 3 4]; >> A2 = A^2


>> Ae2 = A.^2 A2 =
Ae2 = 7 10
14 15 22
9 16
>> B = [1/2 1/2;1/2 1/2]; >> AB=A*B
>> AeB = A.*B AB =
AeB = 1.5000 1.5000
0.5000 1.0000 3.5000 3.5000
1.5000 2.0000

© Md. Mamun-Ur-Rashid Khan, MTH – 250


Function with matrix arguments
13
>> A=[0 pi/2; pi 3*pi/2]; >> B=[4 9; 16 25];
>> cosA=cos(A) >> sqB=sqrt(B)
cosA = sqB =
1.0000 0.0000 23
-1.0000 -0.0000 45

>> C=[1 log(1); 0 log(2)]; >> D=[10 1; 100 1e6];


>> expC=exp(C) >> log10D=log10(D)
expC = log10D =
2.7183 1.0000 10
1.0000 2.0000 26

Functions for Manipulating Arrays

size(A) : dimension of A sum(A, dim) : sum elements of A along


length(A) : length of A dimension dim
max(A) : maximum of each column of A prod(A, dim) : product elements of A
along dimension dim

*** More functions : reshape(A,m,n) sort(A,dim) flipud(A) fliplr(A)


© Md. Mamun-Ur-Rashid Khan, MTH – 250
Relational and Logical Operators
14
Symbol Meaning Example Result
== Equal to 1==2 0
>= Greater Equal 1>=2 0
<= Less Equal 1<=2 1
~= Not Equal 1~=2 1
> Greater 1>2 0
< Less 1<2 1
& AND 5&0 0
| OR 8 | (9==10) 1
~ NOT ∼(3>2) 0
xor Exclusive OR xor(3,’a’<’b’) 0

** MATLAB interprets zero as false and non-zero as true.


** The function xor(a,b) returns logical 1 (TRUE) when either a or b, but not both, is non-
zero and logical 0 (FALSE) when a and b are both zero or non-zero.
© Md. Mamun-Ur-Rashid Khan, MTH – 250
Relational Operators
** Characters are ordered alphabetically.
15 ** Be careful: ’==’ is equivalent relational operator while ’=’ is an assignment operator.
** Relational operators are element-wise operators.
>> X=[ 1 -2; -1, 2]; >> X=[ 1 -2; -1, 2];
>> X>=1 >> Y=[2 -1; 2 -3];
ans =1 0 >> X<=Y
01 ans =1 1
10
** A run time error appears when the arrays are of different sizes.
** As strings are arrays of characters, they should be of same size when they are
compared, otherwise a run time error occurs.

Boolean Operators
Logical operators can also be used to make element-wise comparison provided arrays
are of same dimension or one of them is a scalar.
>> a=[1 2; 2 3]; >> b | 0
>> b=[0 21; 2 31]; ans =
>> a & b 01
ans = 11
01
11 © Md. Mamun-Ur-Rashid Khan, MTH – 250
Branching
16
if/else

basic: if-end with else with elseif


if logical_expression if logical_expression if logical_expression_1
statement 1 statement 1 statement 1
statement 2 statement 2 statement 2
... ... :: ...
end else elseif
statement 1 logical_expression_2
statement 2 statement 1
... statement 2
end ...
else
statement 1
statement 2
...
end

© Md. Mamun-Ur-Rashid Khan, MTH – 250


if/else examples
17
1. Compute inverse of a matrix 3. Determine if an array is a
when it is non-singular: matrix, vector or empty.

if (abs(det(A)) > eps) z=min(size(A));


display(inv(A)); if (z>=2)
end display(’A is a matrix’);
elseif (z==1)
display(’A is a vector’);
2. Compute inverse of a matrix else
when it is non-singular and display(’A is empty’);
display ’matrix is singular’ when end
it is singular.

if (abs(det(A)) > eps)


display(inv(A));
else
display(’matrix is singular’);
end

© Md. Mamun-Ur-Rashid Khan, MTH – 250


18 switch
switch expression switch expression
case case_1, case {case_1,case_2,case_3},
statement 1 statement 1
statement 2 statement 2
... ...
case case_2, case case_4,
statement 1 statement 1
statement 2 statement 2
... ...
otherwise,%optional otherwise,
statement 1 statement 1
statement 2 statement 2
... ...
end end

© Md. Mamun-Ur-Rashid Khan, MTH – 250


switch example
19
Display the number of days of a month=input(’Please enter the month: ’);
month. nbofdays=0;
switch month
January : 31 case {’January’,’March’,’May’,’July’}
February : 28∗ nbofdays=31;
March : 31 case {’August’, ’October’,’December’}
April : 30 nbofdays=31;
May : 31 case ’February’
June : 30 nbofdays=28;
July : 31 case {’April’,’June’,’September’,’November’}
August : 31 nbofdays=30;
September : 30 end
October : 31 if(nbofdays==0)
November : 30 fprintf(’Please enter a correct month
December : 31 name!\n’);
* 28 days during most years, 29 days else
during leap years fprintf(’The month %s has %d days.\n’, month,
nbofdays);
end
© Md. Mamun-Ur-Rashid Khan, MTH – 250
Loops:: for and while
20 Basic for loop structure: Basic while structure:
for counter=start:step:finish while logical_expression
do stuff do stuff
end end
examples
for i=1:10 for i=3:10 for index=1:2:10
display(rand); v(i) = rank(magic(i)); display(index)
end end end
for index=[1 3 2;4 2 1] i=0; i=[ 1 2];
display(index) while i <10 while i <10
end i=i+1; i=i+1;
end end
i=[ 1 12]; z = 0; while (abs(z)<=2)
while i <10 for i=1:1000 z = z^2 + i
i=i+1; z = z^2 + i end
end if (abs(z)>2)
break
end
end
© Md. Mamun-Ur-Rashid Khan, MTH – 250
Simple Plotting Tools:: plot command
21 >> x=-pi:0.01:pi; >> x=-pi:0.01:pi;
>> plot(sin(x)) >> y=cos(x);
>> plot(x,y)
** use figure to create new figure and close all to close all
colour line style markers
r red - solid (default) + cross
g green -- dashed o circle
b blue : dotted * star
c cyan -. dash-dotted . dot
m magenta none no line; handy x x
y yellow for markers s star
b black d diamond
p pentagram
user-defined color use hold on to plot multiple use legend to add legend
>> a = 0:pi/20:2*pi; lines on the same figure >> x=-pi:0.01:pi;
>> plot(a,sin(a),’-.r*’) >> x=-pi:0.01:pi; >> plot(x, cos(x),’r’,x,sin(x),’b’)
>> title(’sin plot’) >> plot(x, cos(x),’r’) >> legend(’cos(x)’,’sin(x)’);
>> xlabel(’values of a’) >> hold on
>> ylabel(’sin(a)’) >> plot(x, sin(x),’b’)
>> hold off © Md. Mamun-Ur-Rashid Khan, MTH – 250
Script M-files
22
* A script m-file is a text file containing a sequence of MATLAB commands;
* Script m-files are useful for automating series of MATLAB commands;
* All m-files names must end with the extension .m;
* By typing the filename at the command window prompt, you execute the commands in
the m-file.

Function M-files
Form::
function [out1,...,outn]=function_name(in1,...,inm)
...
executable statements
...
out1=...
...
outn=...
...
end
© Md. Mamun-Ur-Rashid Khan, MTH – 250
* end: The end statement is optional, but having it is a good programming technique.
23
* [ ]: If there is only one output variable, then brackets may be dropped.
* function name: The function name function_name is defined using same rules as for
variable names.
* saving a function: A function must be saved by the same name as function_name.
* calling a function: A function can be called by its name together with a list of input
arguments.
* function workspace: Each function has its own function workspace, separate from each
other and the base workspace.

© Md. Mamun-Ur-Rashid Khan, MTH – 250

You might also like