You are on page 1of 42

Computer Applications (Programming by MATLAB)

Chapter One
Fundamental Concepts

1.1 Introduction

MATLAB means "Matrix Laboratory" it is a programming language


for technical computation, engineering problems, science problems,
systems simulation and more.

In MATLAB there are toolboxes - prepared sets of integrated tools for

working in a specific area (Control, Signal Processing, Neural Networks,


Optimization, PDE, Symbolic Mathematics, ...).

Also, MATLAB has high capability for data visualization.

1.2 The MATLAB System

The MATLAB system consists of five main parts:

1. Development Environment. This is the set of tools and facilities that


help you use MATLAB functions and files. Many of these tools are
graphical user interfaces. It includes the MATLAB desktop and
Command Window, a command history, an editor and debugger, and
browsers for viewing help, the workspace, files, and the search path.

2. The MATLAB Mathematical Function Library. This is a vast


collection of computational algorithms ranging from elementary
functions, like sum, sine, cosine, and complex arithmetic, to more
sophisticated functions like matrix inverse, matrix eigenvalues, Bessel
functions, and fast Fourier transforms.

1
3. The MATLAB Language. This 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 large and complex application
programs.

4. 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
customize the appearance of graphics as well as to build complete
graphical user interfaces on your MATLAB applications.

5. The MATLAB External Interfaces (API). This is a library that


allows you to write C and Fortran programs that interact with MATLAB.
It includes facilities for calling routines from MATLAB (dynamic
linking), calling MATLAB as a computational engine, and for reading
and writing MAT-files.

1.3 The MATLAB Desktop:

The desktop of MATLAB can be illustrated in the following figure:

2
Run SIMULINK
Get Help Enter a Command
New M-file

Launch Pad

Use previously run


commands View workspace or current directory

1.4 The Number System in MATLAB:

In MATLAB we can use

a. for integer numbers the following with their ranges and the number
of bits that required to represent them:

3
Form Range No. of Bits

int8 From -128 to 127 8

int16 From -32768 to 32767 16

int32 From -2147483648 to 2147483647 32

uint8 From 0 to 255 8

uint16 From 0 to 65535 16

uint32 From 0 to 4294967295 32

Table 1.1 The Forms used for integers in MATLAB

Ex.1)

a. >> int8(-200) b. >>int16(90)

ans= ans=

-128 90

c. >>int8(130) d. >>uint8(-12)

ans= ans=

127 0

e. >> int8(10) f. >> int32(457000)

ans= ans=

10 457000

So we notice that if the given number is out of the range of the form
the left then we get the minimum value of the form's range when the
given number where less than the range's minimum; and we get the

4
maximum value of the form's range when the given number is greater
than the range's maximum.

b. for the real numbers we have the following format :

Format statement Meaning Example

format or format short 4 digits with (.) 3.1416

format long 15 digits with (.) 3.1415926358979

format short e 4 digits with (.) in e-form 3.1416e+00

format long e 15 digits with (.) in e-form 3.1415926358979e+00

format short g 4 digits including(.) with or without e-form 3.1416

format long g 15 digits with (.) with or without e-form 3.1415926358979

format hex For hexadecimal system 400921fb55442d18

format bank 2 digits with (.) 3.14

format rat For rational forms 355/113

Table 1.2 The forms used for real numbers in MATLAB

1.5 Relational Operators in MATLAB:


Relational operators compare operands quantitatively, using
operators like “less than” and “not equal to.” The following table
provides a summary:

Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to

Table 1.3 The Operators forms in MATLAB

5
1.6 Arithmetic Operators in MATLAB:

The arithmetic operators in MATLAB can be given as follows:

Symbol Operation
+ Addition
- Subtraction
* Multiplication
/ Division
^ Power
Table 1.4 The arithmetic operators forms in MATLAB

1.7 Using MATLAB as a Calculator:


As an example of a simple interactive calculation, just type the
expression you want to evaluate. Let's start at the very beginning. For
example, let's suppose you want to calculate the expression, 1 + 2× 3.
You type it at the prompt command (>>) as follows,
>> 1+2*3
ans =
7
You will have noticed that if you do not specify an output variable,
MATLAB uses a default variable ans, short for answer, to store the
results of the current calculation. Note that the variable ans is created (or
overwritten, if it is already existed). To avoid this, you may assign a value
to a variable or output argument name. For example,
>> x = 1+2*3
x=
7
will result in x being given the value 1 + 2 * 3 = 7. This variable name
can always be used to refer to the results of the previous computations.
Therefore, computing 4x will result in

6
>> 4*x
ans =
28.0000

1.8 Mathematical Functions

MATLAB offers many predefined mathematical functions for


technical computing which contains a large set of mathematical functions.
Typing help elfun and help specfun calls up full lists of elementary
and special functions respectively.
There is a long list of mathematical functions that are built into
MATLAB. These functions are called built-ins. Many standard
mathematical functions, such as sin(x), cos(x), tan(x), ex, ln(x), are
evaluated by the functions sin, cos, tan, exp, and log respectively in
MATLAB. The following Table 1.4 lists some commonly used functions,
where variables x and y can be numbers, vectors, or matrices.

MATLAB Function Mathematical Function


cos(x) cos x
sin(x) sin(x)
tan(x) tan x
acos(x) cos-1x
asin(x) sin-1x
atan(x) tan-1x
exp(x) ex
log(x) Natural logarithm
log10(x) Common logarithm
sqrt(x) Square root
sign(x) Signum function

Table 2.1: Elementary functions(Part 1)

7
1.9 Complex Number in Matlab:

In matlab we can define a complex number z=x+yj or z=x+iy by:

>>z=x+i*y or >>z=x+j*y

Where x is the real part of z, y is the imaginary part of z, and i=j=


√−1.

We have some functions in matlab to compute:

1. The real part of z which is: real(z).


2. The imaginary part of z which is: imag(z).
−1 y
3. The angle between x and y = tan ( x ) which is: angle(z).

4. The length of z or |z|=√ x 2 + y 2 which is: abs(z).


5. The conjugate of z= z=x− jy =x−iy which is: conj(z).

Ex.:

>>x=2; >>abs(z)

>>y=3; ans:

>>z=x+i*y 3.6056

ans:

2.0000+3.0000i

>>angle(z) >>conj(z)

ans: ans:

0.9828 2.0000-3.0000i

8
1.10 Computer Number Systems:

We can convert:

1- The binary no. to decimal one by using the Matlab command:


bin2dec('no.').
2- The decimal no. to binary one by using the Matlab command:
dec2bin(no.).
3- The hexadecimal no. to decimal one by using the Matlab
command: hex2dec('no.').
4- The decimal no. to hexadecimal one by using the Matlab
command: dec2hex (no.).
5- The base n no. to decimal one by using the Matlab command:
base2dec('no.',n).
6- The decimal no. to base none by using the Matlab command:
dec2base(no.,n).

Ex.:

>>bin2dec('10') >>dec2bin(2)

ans: ans:

2 10

>>hex2dec('A') >>dec2hex(10)

ans: ans:

10 A

>>base2dec('21',8) >>dec2base(17,8)

ans: ans:

17 21

9
H.w: 1. Convert the binary number: 101011 to a number in octal system.

2. Convert the hexadecimal number: A to a number in octal system.

3. Convert the octal number: 7 to a number in binary system.

1.11 I/O Statements in Matlab:

The variables in Matlab are either numeric (integer, or real, or


complex numbers) or characters, or strings( collection of characters) or
matrix.

We can input any variable or constant to Matlab either by:

(a) Assignment: by using the general form:


>>variable or constant name=value

(b) Using input Statement: which has the following general form:
(i) >>variable or constant name=input('some massage') ;which is
used for numeric variables or constant.
(ii) >>variable or constant name=input(' some massage ','s') ;which
is used for string variables or constant.

For output as we know the Matlab directly shows the result of any
variable or constant; and we can also use the Matlab output statement:
>>disp(variable or constant name or 'massage' )
which is used either
(i) to print out the massage.
Or
(ii) the value of the variable or constant without writing it's name.

Ex.:
Use the input statement to enter:
(i) x as a numeric value 5.8;
(ii) y as the string "hello this is the Matlab programming course";
then use the disp-function for showing their results.

>>x=input('Enter the value of x:') >>disp(x)


Enter the value of x:5.8 5.8000

10
x=
5.8000
>>y=input('Enter the char of the >>disp(y)
string y:','s') hello this is the Matlab programming
Enter the char of the string y: hello course
this is the Matlab programming
course
y=
hello this is the Matlab
programming course

1.12 Strings in Matlab:

We can deal with the string in Matlab by using the following


functions:

1. blanks(n): that puts n-spaces between the string S1 and the string
S2.
2. deblanks: which deletes the spaces between any two strings S1 and
S2( after the string S1 and after S2).
3. strrep(S1,S2,S3): which replace the string S2 in S1 by S3.
4. strcmp(S1,S2): which compare between the two strings S1 and S2.

It's result is either 1 when (S1 S2) or 0 when (S1 different from
S2).
5. strncmp(S1,S2,n): which compare the first n-character of S1 with
the first n-character of S2.
6. findstr(S1,S2): which writes the position of S2 in the string S1.
7. lower(S): which writes S in small letters.
8. upper(S): which writes S in capital letters.

Rem.: We use the Matlab function char(n0.) to convert the number no.
into a character by the ASCII.

Ex.:

11
>>char(66) >>m{1,1}='my name is ';
ans: >>m{1,2}=' AAA ';
B >>deblank(m)
>> char(65:120)
ans = ans =
ABCDEFGHIJKLMNOPQRSTUV 'my name is' ' AAA'
WXYZ[\]^_`
abcdefghijklmnopqrstuvwx

>> disp(['my name is' blanks(5) >> strcmp('ffffkkk','ffff')


'Ahmed']) ans:
my name is Ahmed 0
>>strncmp('ffffkkk','ffff',3)
>>disp(['my name is' blanks(15) ' ans=
Ahmed']) 1
my name is Ahmed

>>strrep(' my name is >> findstr(' my name is


Ahmed','Ahmed','mohamed') Ahmed','m')
ans = ans=
my name is mohamed 2 7 15

>> lower('lllllPO') >> upper('kkkPO')


ans= ans=
lllllpo KKKPO

1.13 Some Important Library Matlab Functions :

1. factorial(n): This function is used to compute n!.

2. primes(x): This function is used to compute all the prime numbers less
than or equal to x.

3. sign(x): This function is used to write the sign of x; it's result is either 1
when x>0; or 0 when x=0; or -1 when x<0.

4. fix(x): This function eliminate the fraction part.

12
5. floor(x): This function approximates x towards -∞.

6. ceil(x): This function approximates x towards +∞.

7. round(x): This function approximates x to nearest integer.

8. rem(x,y): This function is used to compute the reminder of x/y that


satisfies: x-y*fix(x/y).

9. mod(x,y): This function is used to compute the reminder of x/y that


satisfies: x-y*floor(x/y).

10. factor(x): This function is used to write the simple factors of x.

11. gcd(x,y): This function is used to find the greatest common divisor of
x and y.

12. lcm(x,y): This function is used to find the least common multiple of
x and y.

13. gamma(x): This function is used to find the result of the gamma
function of x that defined as:

∫ e−t t x−1 dt
0

14. beta(x,y): This function is used to find the beta function of x and y
which is defined by:
1

∫ t x−1 (1−t)y−1 dt
0

15. erf(x): This function is used to find the result of error function of x
which is defined by:
x
2 2

∫ e−t dt
√π 0

13
16. erfc(x): This function is used to find the result of cumulative error
function of x which is defined by:

2 2
−t
∫ e dt =1−erf ⁡(x)
√π x

Ex.:

>>factorial(5) >>primes(12)

ans= ans=

120 1 2 3 5 7 11

>>factor(40) >>sign(-90)

ans= ans=

2 2 2 5 -1

>>fix(-1.9) >>floor(-1.1)

ans= ans=

-1 -2

>>ceil(-1.9) >>round(-3.6)

ans= ans=

-1 -4

>> rem(69,11) >> mod(69,12)

ans = ans =

3 9

>>gcd(24,32) >>lcm(24,32)

ans= ans=

8 96

>> gamma(5) >> beta(6,5)

14
ans =

24 ans =

7.9365e-004

>> erf(0.5) >> erfc(9)

ans = ans =

0.5205 4.1370e-037

15
Chapter Two

Condition and Selection Statements in Matlab

We shall discuss the following conditional statements in Matlab:

2.1 if Statement:

The general form of this statement is either:

(a) if (condition or expression)


statement(s)
end
or
(b) if (condition or expression)
statement(s)
else
statement(s)
end
(c) if (condition or expression 1)
statement(s)
elseif (condition or expression 2)
statement(s)
elseif (condition or expression 3)
statement(s)
:
elseif (condition or expression n-1)
statement(s)
else
statement(s)
end

16
Ex.: Write the Matlab commands for finding the result of

(a) y= √1− x; where x is any real number.


(b) D= √b 2−4 ac ; where a,b, and c are real numbers.

Sol.:

(a) Since the square root of (1-x) is defined only when x ≤ 1 this implies
that our condition is ( x ≤ 1) and y can be evaluated easily in this
case by the following Matlab commands:

Either: Or:
x=input('enter the value of x') x=input('enter the value of x')
if (x<=1) if (x<=1)
y=sqrt(1-x) y=sqrt(1-x)
end else
disp('undefined ')
end

(b) Since the square root of (b2-4ac) is defined only when b2-4ac≥0;
So we shall denote it by x= b2-4ac and the condition will be x≥0;
and in fact we have three cases: x>0, x<0, and x=0) the Matlab
commands may be given as follows:

a=input('enter the value of a')


b=input('enter the value of b')
c=input('enter the value of c')
x=b^2-4*a*c
if (x==0)
disp('the first case')

17
y=0
elseif (x>0)
disp('The second case')
D=sqrt(x)
else
disp('The second case')
disp('Complex case ')
end

2.2 The switch-case:

The general form of this statement is either:

switch(condition or expression)

case (condition value 1 or expression value 1)

statement(s)

case (condition value 2 or expression value 2)

statement(s)

case (condition value 3 or expression value 3)

statement(s)

otherwise

statement(s)

end

18
Ex.: Write the Matlab commands to enter a student code number then
print his(her) name as the absence list.

Sol.:

code=input('give me the student code in the list')

switch (code)

case 1

disp('Ahmed')

case 2

disp('Ali')

case 3

disp('Bilal')

case 4

disp('Zaid')

case 5

disp('Yousif')

otherwise

disp('unknown code')

end

Ex.: Write the Matlab commands to input the first letter of your friends
name then print his(her)complete name?

x=input('enter a the first letter ','s')


switch x
case 'a'

19
disp('ahmed')
case 'b'
disp('belal')
otherwise disp('unkown')
end
H.W: Try to write the Matlab commands for:
(1) Finding the solution(roots) of : ax2+bx+c=0, where a, b, and c are
constants.
(2) Entering the day name then convert it into the day number (for
example 1 for Sunday , 2 for Monday,..).
(3) Input a number x then print positive when x is positive, and print
negative when x is negative.
(4) Input a number x then test if it is even or odd.
(5) Input three number x, y, and z then find their maximum and
minimum.

20
Chapter Three

Loops in Matlab

We shall discuss the following statements:

3.1 for Statements:

This statement is used to repeat the command for finite number of


times; the general form of this statement is:

for variable name=Expression

statement(s)

end

Rem.: the expression must state the

1. Initial or the start value of the variable;


2. The step size (when it is not equal to the default value 1);
3. The final or last value of the variable.

Note that you must put : between any two of the three above steps.

Ex. Use the for statement to enter 10 numbers find their summation? then
their product?

Sol.:

Note that with respect to summation we must initializes it as


sum=0; and with respect to the product we must initializes it as
product=1. Then we write the commands may be given as:

sum=0

21
product=1

for i=1:10 %(for repeating the operation ten times)

number=input('enter a number:') %(to input a number)

sum=sum+number %(to add the entered number to sum=0)

product=product*number

%(to multiply the entered number by product=1)

end

We note the following:

1. The variable name in the for statement is (i);


2. we start the loop by setting i=1 and we have to enter ten number
the step size is 1; and the last value of (i) will be at 10.
3. We use the variable number to have a the number value by the
input statement then we add it to sum whose initial value is zero;
then we multiply it the product whose initial value is one;
4. We take the new value of i as 2 and we repeat the input statement
and the summation and production statements( that takes the
updates values after the first i=1 step); and so on till i=11 which
will terminates the operation.
5. We get in each step new values of sum and product after reading a
new number.

Ex.: Write the Matlab commands to read 20 number then finds their
maximum and minimum.

Sol.:

In this problem we shall:

1. input the first number and we set it as both maxi, and mini.
2. put the loop statement form 2 to 20.

22
3. For each one of these steps we shall input another number and
test whether the maxi is less than the new number; and mini is
greater than the new number; to have new values of the
maximum and minimum.

The commands may be given as:

number=input('give me the first number:')

maxi=number

mini=number

for counter=2:20

number=input('give me a new number:')

if (maxi<number)

maxi=number

end %if-statement

if (mini>number)

mini=number

end %if-statement

end %for-statement

H.W: Use the for-statement to write the Matlab commands for each of
the following:

1. Enter 15 number then print positive for the positive ones and negative
for the negative one.

2. Compute y from the relation: y=1!+2!+3!+…+n!; where n is any


positive integer number.

23
1 2 n
3. Evaluate z from the relation: z= 1! + 2! + …+ n! ; where n is any positive

integer number.
3 2 n +1
x x x
4. Evaluate w from the relation: w= + + …+ ; where x is any
1! 3 ! (2 n+1)!

real number and n is any positive integer number.

5. Enter the mark of a passed student in 9 subjects then compute his


average .

3.2 while-Statement:

The general form of this statement can be given as follows:

while(Condition or Expression)

Statement(s)

end

Ex.: Write a program to enter a positive number(stop when the number is


negative)

Sol.:

Number=input('enter a positive number')

while(Number>0)

Number=input('enter a positive number')

end

Ex.: Write a program to input n-numbers and compute the summation of


the positive ones and the summation of the negative ones (using the while
statement)?

24
Sol.:

n=input('enter the number of numbers')


positivesum=0
negativesum=0
counter=1
while(counter<=n)
number=input('enter a number')
if(number>=0)
positivesum=positivesum+number
end
if (number<0)
negativesum=negativesum+number
end
counter=counter+1
end
disp(positivesum)
disp(negativesum)

25
Chapter Four

Matrices in Matlab

4.1 Reading Matrices to Matlab:

We can read any matrix to Matlab making use of the following:

(i) When the matrix is given, we write:


the matrix name=[elements of the first row(put a space between
any two elements); elements of the second row(put a space
between any two elements);…; elements of the last row(put a
space between any two elements)].

Ex.: Read the following matrices to Matlab:

1 −1

[ ] 3 5
A= 2 0 ; B= i 2 ?
7 9
[ ]
Sol.:

>> A=[1 -1;2 0;7 9] >>B=[3 5;i 2]

A= B=

1 -1 3 5

2 0 i 2

7 9

(ii) When the matrix is not given, we use the following loops and
the input-statement:

26
number of rows=input('enter the number of rows =')

number of columns=input('enter the number of cols =')

for i=1:number of rows

for j=1:number of columns

matrixname(i,j)=input('enter the matrix elements')

end %j

end %i

Ex.: Try to read the matrix A of size 3*2 to `Matlab?

number of rows=3;

number of columns=2;

for i=1:number of rows


for j=1:number of columns
A(i,j)=input('enter the matrix elements')
end
end

4.2 Some Important Matlab Functions for Dealing with Matrices:

Let A be a n m matrix and B be a n n matrix, X be a n 1 matrix


then:

27
1. sum(A): This function computes the summation of elements in
every column in A.

Ex.: >> sum([1 2 3;4 5 6])


[1
We have the matrix 4 5 6
2 3
]
ans = Where the sum of the first col. elements=1+4=5
5 7 9 Where the sum of the second col. elements=2+5=7
Where the sum of the third col. elements=3+6=9

2. prod(A): This function computes the product of elements in every


column in A.

Ex.: >> prod([1 2 3;4 5 6])


[1
We have the matrix 4 5 6
2 3
]
ans = Where the product of the first col. elements=1*4=4
4 10 18 Where the product of the second col. elements=2*5=10
Where the product of the third col. elements=3*6=18

3. max(A): This function finds the maximum element in every


column of A.

Ex.: >> max([1 2 3;4 5 6])


[1
We have the matrix 4 5 6
2 3
]
ans = Where the max. element in the first col. =4
4 5 6 Where the max. element in the second col. =5

Where the max. element in the third col. =6

4. min(A): This function finds the minimum element in every column


of A.

Ex.: >> min([1 2 3;4 5 6])


[1
We have the matrix 4 5 6
2 3
]
ans = Where the min. element in the first col. =1

28
1 2 3 Where the min. element in the second col. =2

Where the min. element in the third col. =3

5. mean(A): This function computes the mean of the elements in


every column of A.

Ex.: >> mean([1 2 3;4 5 6])


[1
We have the matrix 4 5 6
2 3
]
ans = Where the mean of elements in the first col. =2.5000
2.5000 3.5000 4.5000 Where the mean of elements in the second col. =3.5000
Where the mean of elements in the third col. =4.5000

6. zeros(n,m): This function constructs a matrix of size n m of zero


elements only. Sometimes we write zeros(n) to get a square matrix
of size n with zero elements only.

Ex.: >> zeros(2,3) >>zeros(2)

ans = ans=
1 0
0 0 0
0 0
0 0 0

7. ones(n,m): This function constructs a matrix of size n m of ones


elements only. Sometimes we write ones(n) to get a square matrix
of size n with ones elements only.

Ex.: >> ones(2,3) >>ones(2)

ans = ans=
2 1
1 1 1

29
1 1 1 1 1

Ex. Construct the following matrix using the above function:

99 99 99
[
A= 99 99 99 ?
99 99 99 ]
Sol.:

>>A=99*ones(3)

ans=

99 99 99

99 99 99

99 99 99

8. diag(B): This function prints the elements of the main diagonal of


Bn ×n .

Ex.:
[ 1 2]
We have the matrix 3 4 the
>> diag([1 2;3 4])
elements of the main diagonal of
ans = it is 1 and 4.

9. sort(A): This function sort the element of each column in


ascending order.

Ex.:>> sort([1 2;0 -9])


[1 2 ]
We have the matrix 0 −9 ; after

30
ans =
[ 0 −92 ]
sorting will be 1
0 -9

1 2

10. det(B): This function computes the determinant of the square

matrix B of size n n.

Ex.:>> det([1 2 3; 4 5 6;5 7 8]) Ex.: >> det([1 2;4 5])

ans = ans =

3 -3

11. inv(B): This function computes the inverse of the square matrix B

−1
of size n n if det(B)≠0 (i.e Finding ( B ) if it is possible).

Ex.: >> inv([1 2;3 7]) Ex.: >> inv([1 2 3;4 5 6])

ans = ??? Error using ==> inv

7.0000 -2.0000 Matrix must be square.

-3.0000 1.0000

12.eig(B): This function computes the set of all eigenvalues of the

square matrix B of size n n.

31
Ex.: >> eig([1 2;3 4]) Ex.: >> eig([1 2 3;4 5 6;5 6 9])

ans = ans =

-0.3723 14.9732

5.3723 -0.6198

0.6465

13. std(X): This function computes the standard deviation of X n× 1 that


n n
1
2
given by S = ∑ ( x − x)2; where x= 1n ∑ x i.
n−1 i=1 i i=1

Ex.: >> std([11 21 3]) Ex.: >> std([1 21 31])

ans = ans =

9.0185 15.2753

14.A': This function computes the transpose of any matrix( making


every row as a column) .

Ex.: >> A=[1 2 3;4 5 6]; Ex.: >> [1 21 31]'

>> A' ans =

ans = 1

1 4 21

2 5 31

3 6

15. flipud(A) : This function Flips the matrix A up to down.

32
Ex.>>A=[3 5 7]; Ex. >>A=[1 4;2 5;3 6];

>> flipud(A’) >> flipud(A)

ans: ans:

7 3 6
5 2 5
3 1 4

16.fliplr(A): Flips matrix A left to right.

Ex. >>A =[1 3 5 7 9]; Ex. >>A=[1 4;2 5;3 6];


>>fliplr(A)
ans: >>fliplr(A)
9 7 5 3 1
ans:

4 1
5 2
6 3

17. flipdim(A,dim): Flips array A along specified dimension.

Rem.: When the value of dim is 1, the array is flipped row-wise down.
When dim is 2, the array is flipped column-wise left to right.

i.e flipdim(A,1) is the same as flipud(A), and flipdim(A,2) is the same as


fliplr(A).

Ex. >>A =[1 3 5 7 9]; Ex. >>A=[1 4;2 5;3 6];


>>fliplr(A)
ans: >>flipdim(A,1)
9 7 5 3 1
ans:

3 6
2 5
1 4

18. rot90(A): Rotates matrix A counterclockwise by 90 degrees.

33
Rem. rot90(A,k) rotates matrix A counterclockwise by k*90 degrees,
where k is an integer.

>> rot90(X,2) Ex. >>X =[1 2 3;4 5 6;7 8 9];


>> rot90(X)
ans: ans:
9 8 7 3 6 9
2 5 8
6 5 4 1 4 7
3 2 1
Rem.: We can use some of the above functions to solve a set of linear
equation s:
a 11 x 1 +a12 x2 +a 13 x 3+ …+a 1n x n=b1

a 21 x1 + a22 x 2+ a23 x 3 +…+ a2 n x n=b2 ¿


¿

a n1 x 1+ an 2 x 2 +a n3 x 3+ …+a nn x n=b n¿
¿

in Matlab by using:

>>A=[a 11 a12 … a 1n ; a 21 a22 … a2 n ; …; an 1 an 2 … a nn ¿ ;

>>B=[b 1 ;b2 ;… ; bn ¿;

>>solution=inv(A)*B

Rem.:

The notation : is called colon, we can use the colon to create a


vector of indices to select rows, columns, or elements of arrays, where:

1. A(:,j) means the jth column of the matrix A;


2. A(i,:) means the ithrow of the matrix A.

Ex. Write the Matlab instructions to find:

a. the summation of the seventh row in a matrix An×m;


34
b. the average of the elements of the fourth column of An×m.

sol.:

n=input('enter the number of rows =')

m=input('enter the number of cols =')

for i=1:n

for j=1:m

A(i,j)=input('enter the matrix elements')

end %j

end %i

if (n>=7) % for computing the sum of the row no.7

sum(A(7,:))

end % if n>=7

if (m>=4) % for computing the mean of the col. no.4

mean(A(:,4))

end % if m>=4

Ex. Write the Matlab instructions to interchange the second row by the
fifth row in a matrix An×m.

sol.:

n=input('enter the number of rows =')

m=input('enter the number of cols =')

for i=1:n

for j=1:m

35
A(i,j)=input('enter the matrix elements')

end %j

end %i

if (n>=5) % to be sure that there is row no.5

T=A(2,:);

A(2,:)=A(5,:);

A(5,:)=T;

end % if n>=5

A % to print A after changing rows

Ex. Write the Matlab instructions to delete the fifth column in a matrix
An×m.

sol.:

n=input('enter the number of rows =')

m=input('enter the number of cols =')

for i=1:n

for j=1:m

A(i,j)=input('enter the matrix elements')

end %j

end %i

if (m>=5) % to be sure that there is row no.5

A(:,5)=[]

end % if m>=5

A % to print A after deleting col. 5

36
Chapter Five

Applications

5.1 Functions Definition:

We can define any function f to Matlab by using the following


instructions:

>>syms variable1 variable2 …

>>f=function rule

where syms represents the variables of the given function.

Ex.1: Define the function f(x,y,z)=x sinzy to Matlab?

Sol.:

>>syms x y z

>>f=x*sin(z*y)

f=

x*sin(z*y)

37
5.2 Derivatives:

To find the derivative of any function by using the Matlab we first


define the function as we did above method and the following Matlab
instruction:

>>diff(f , variable name)

where f is the defined function that will be differentiated with respect to


the variable name.

Ex. Compute f x ; f y ; and f xy for Ex.(1) in Matlab?

>>syms x y z >>diff(f , y)

>>f=x*sin(z*y) ans=
x*z*cos(z*y)
f=
>> diff(diff(f,y),x)
x*sin(z*y)
>>diff(f , x) ans =

ans= z*cos(y*z)
sin(z*y)

5.3 Integration:

To evaluate the integral of any function by using the Matlab, we first


define the function as we did in the above method and the following
Matlab instruction:

>>int(f , variable name, a , b)

for finding the definite integral of f w.r.t variable name from a to b. (i.e
this function is used to compute the area under the curve of f from a to b).
Also we can use the instruction:

38
>>int(f )

to compute the indefinite integral of the function f (anti derivative of f).


π 2 7

∫ cos3t dt ∫∫ x y dy dx
Ex.: Find ∫ sin2 x dx ; 0 ; 1 3 by Matlab?

Sol.:

>> syms x y t

>>f1=sin(2*x)

>>int(f1) % for ∫ sin2 x dx


>>f2=cos(3*t)

>>int(f2 , t, 0 , pi)

>>f3=x*y

>>int(int(f3,y,3,7),x,1,2)

5.4 Graphics in Matlab:


We can graph any function in Matlab by

a)
>>x=starting value:step size: Final value; .for 2-dim plotting
>>y=function at x;
>>plot(x,y)

And

b)
>>t= starting value:step size: Final value;
.for 3-dim plotting

39
>>x= function at t;
>>y=function at t;
>>plot3(t, x, y)

Ex.: Graph the following functions:


(1) sin(2x); (2) cos(t pi/2); (3) exy.
Sol.:
(1)

Or >>x=-2*pi:0.05*pi:2*pi;
>>x=-2*pi:0.05*pi:2*pi; >>y=sin(2*x);
>>plot(x,sin(2*x)) >>plot(x,y)

(2)

Or >>t=-4*pi:0.005*pi:4*pi;
>>t=-4*pi:0.005*pi:4*pi; >>y=cos(t*pi/2);
>>plot(t, cos(t*pi/2)) >>plot(t,y)

(3)

Or >>x=-2*pi:0.05*pi:2*pi;
>>x=-2*pi:0.05*pi:2*pi; >>y=0:0.01:2;
>>y=0:0.01:2; >>plot3(x,y,exp(x,y))
>>z=exp(x,y)
>>plot3(x,y,z)

H.w:
40
1.
2.
3.

5.5 Laplace Transforms:

We can compute the laplace transform of any function f(t) in Matlab


as the following instructions:

>>syms t s

>>f=function of t;

>>laplace(f)

Also, we can compute the inverse of the laplace transform of any


function F(s) in Matlab as the following instructions:

>>syms t s

>>F=function of s;

>>ilaplace(F)

1 1
Ex.: Compute:
L
[]; [ ]
t2
L−1 2
s −1

Sol.:

>>syms s t

>>f=1/(t^2);

>>laplace(f)

>>F=1/(s^2-1)

41
>>ilaplace(F)

42

You might also like