Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

▌Objectives

Introduction to  Exploring Matlab capabilities


 Employ numerical methods in examples
Matlab  Emphasizing the appeal of MATLAB as a
programming tool.

Prepared by
Dr. Mohamed Saber Sokar
Dr. Mohamed Saber Sokar 2

▌Outline:
 Operators (Arithmetic, relational, logical )
 Using of M-File



Input / Output of data using keyboard
Description of Matlab functions
Matlab Utility functions
PART (II-2)
FUNDAMENTALS

Dr. Mohamed Saber Sokar 3 Dr. Mohamed Saber Sokar 4

▌Arithmetic operators ▌Arithmetic operators

+ addition Priority Order (from left to right):


- subtraction (1) Power, 
* multiplication (2) division or multiplication, and lastly 
/ division (3) addition or subtraction.
^ power
Use ( ) to change the priority.
' complex conjugate transpose

Dr. Mohamed Saber Sokar 5 Dr. Mohamed Saber Sokar 6

1
▌Operations on Matrices ▌Matrices Operations
Transpose B=A’
eye (n)  returns an n x n identity matrix Given A and B:
Identity Matrix eye (m,n)  returns an m x n matrix with ones on
the main diagonal and zeros elsewhere
Addition and Subtraction C =A + B , C = A - B
Addition Subtraction Product Transpose
Scalar Multiplication B = α A, where α is a scalar
Matrix Multiplication C=A*B
Matrix Inverse B = inv(A), A must be a square matrix in this case
Matrix powers B = A * A , A must be a square matrix
Determinant det (A), A must be a square matrix

Dr. Mohamed Saber Sokar 7 Dr. Mohamed Saber Sokar 8

▌Remember ▌Operators (Element by Element)

If you give MATLAB a garbage .* Element-by-element multiplication


instruction, you will get a garbage ./ Element-by-element right division
result
.\ Element-by-element left division
((Garbage in, garbage out)). .^ Element-by-element raising to a power

.' Transpose without complex conjugate

Dr. Mohamed Saber Sokar 9 Dr. Mohamed Saber Sokar 10

▌Class activity ▌Class activity


 » 3-2 <Enter>  » 3.-2 <Enter>
 » 3+2 <Enter>  » 3.+2 <Enter>
 » 2*3 <Enter>  » 2.*3 <Enter>
 » 1/2 <Enter>  » 1./2 <Enter> A.^2 point to point multiplication
 » 2^3 <Enter>  » 2.^3 <Enter>
 » 2\1 <Enter>  » 2\1 <Enter>
 the results are the same, because the
multiplication, division, and exponentiation is
done with single numbers. A^2 Matrix multiplication

Dr. Mohamed Saber Sokar 11 Dr. Mohamed Saber Sokar 12

2
▌Operators (Element by Element) ▌The use of “.” (Element Operation)
 When two arrays have the same dimensions, A = [1 2 3; 5 1 2; 3 4 -1] x = A(1,:) y = A(3 ,:)
A=
addition, subtraction, multiplication, and division 1 2 3 x= y=
apply on an element-by-element basis. 5 1 2 1 2 3 3 4 -1
3 4 -1

b = x .* y c=x./y d = x .^2

b= c= d=
3 8 -3 0.33 0.5 -3 1 4 9

K= x^2
Erorr: ??? Error using  mpower Matrix must be square.
B= x*y
Erorr: ??? Error using  mtimes Inner matrix dimensions must
agree.
Dr. Mohamed Saber Sokar 13 Dr. Mohamed Saber Sokar 14

▌The use of “.” (Element Operation) ▌Class activity


>> D = A./B
>> A = [ 2 5 6 ] ;
>> C = A.*B  >> A=[1 2 ; 4 5];
C= D=
>> B = [ 2 3 5 ]; 4 15 30 1.0000 1.6667 1.2000 Notice the difference
» >> B=A*A % Proper matrix multiplication
>> E = A.^B >> F = 3.0.^A >> E = A.^B » B= 9 12
E= F= E= 24 33
4 125 7776 9 243 729 4 125 7776

K= A^2 » >> B=A.*A % Element by element multiplication


Erorr: ??? Error using  mpower Matrix must be square. » B= 1 4
M= A*B 16 25
Erorr: ??? Error using  mtimes Inner matrix dimensions must
agree.
Dr. Mohamed Saber Sokar 15 Dr. Mohamed Saber Sokar 16

▌Class activity ▌Useful matrix operations


▌ Determinant: det(m)
» a = [1 2 3 4; 5 6 7 8];
▌ Inverse: inv(m)
» b = [1:4; 1:4];
» c = a.*b ▌ Rank: rank(m)
c = ▌ i by j matrix of zeros: m = zeros(i,j)
1 4 9 16 ▌ i by j matrix of ones: m = ones(i,j)
5 12 21 32
▌ i by i identity matrix: m = eye(i)
c(2,4) = a(2,4)*b(2,4)

Dr. Mohamed Saber Sokar 17 Dr. Mohamed Saber Sokar 18

3
▌Input /Output data ▌Input/Output of Data Using Keyboard

 Entering data interactively via keyboard  INPUT command


The general form of the input statement is
 INPUT command
Variable_name = input( ’prompt’ )
 Displaying output values
 DISP command  The command ‘input’ enables to input some data
interactively via the keyboard.
 FPRINTF command
>> x = input(’ Enter x= ’)
Enter x= 1/3
x = 0.3333
Dr. Mohamed Saber Sokar 19 Dr. Mohamed Saber Sokar 20

▌Input/Output of Data Using Keyboard ▌Input/Output of Data Using Keyboard


1. A semi-colon at the end of the input statement will prevent
the value entered from being immediately echoed on the  DISP command
screen.
2. Vectors and matrices may also be entered with input, but
The general form of the DISP statement is
the elements must enclosed in square brackets. disp (‘ comment strings’ ),disp(var_name)
3. Strings may be input if they are enclosed in quotes ' ', e.g.,
 The command ‘disp(x)’ enables displays the
>> name = input( 'Enter your name: ' );
Enter your name: ’ALI’ array, without printing the array name.
>> name = input( 'Enter your name: ' ) , >> disp('The value of x = '),disp(x)
Enter your name: ’ALI’ The value of x =
name =
ALI
or 0.3333

Dr. Mohamed Saber Sokar 21 Dr. Mohamed Saber Sokar 22

▌Class activity ▌Class activity


>> x = input(’Enter x= ’)  Draw a flow chart Write a Matlab program to
.... calculate the volume of a cylinder
>> disp('The value of x = '),disp(x) % clears the command window
% Program to calculate the volume of a cylinder
or
>> disp('The value of x = ');disp(x)

Compare disp with >> x % or v= pi*d^2*h/4

Dr. Mohamed Saber Sokar 23 Dr. Mohamed Saber Sokar 24

4
▌FPRINTF command ▌Exampls
 The fprintf function has allowed us to control the Operation Symbol Example Result
format of the output precisely. Decimal integers %d fprintf( ' %5d ', -32) -32
fprintf (’comment or format string [Width Floating point %f fprintf( ' %12.6f ', -1/pi) -0.318310
specifiers W.S]’, list of variables) Scientific notation %e fprintf( ' %14.6e ', -1/pi) -3.183099e-01
Strings %s fprintf( ' %14s', 'Hello world') Hello world
- The W.S (width specifiers) are optional. If they are left out, Percentage %% fprintf( ' Return = %5.2f%%', 6.8) Return = 6.80%
default values are used (i.e. short format) . Newline \n fprintf( ' \nBHP $%5.2f\n', 40.93) BHP $40.93

fprintf (' hello a =%g score=%% %4.2f \n', av, s)

Dr. Mohamed Saber Sokar 25 Dr. Mohamed Saber Sokar 26

▌FPRINTF command features ▌Class activity


List of special codes used in format string
Code Action Default mode
%d or %I write a numerical variable in Integer notation >> fprintf(' The temperature is %f degrees F \n ', temp)

%f write a numerical variable in decimal notation


The temperature is 78.000000 degrees F
%e or %E write a numerical variable in scientific notation
%g or %G write a numerical variable (MATLAB’s choice)
fprintf mode
%s write a string variable, %c for Single character >> fprintf(' The temperature is %4.1f degrees F \n ', temp)
%% Display the % sign
\n new line The temperature is 78.0 degrees F
\t horizontal tab
\b backspace
\\ Display the backslash \
Dr. Mohamed Saber Sokar 27 Dr. Mohamed Saber Sokar 28

▌Class activity
 M-file >> a = [1.02 3.04 5.06];
>> fprintf('%d\n',round(a));
>> name = input(' Enter your name: ' );

>> fprintf(' Hello %s!\n', name); 1


3
 Run 5
>> Enter your name: ' John'

Hello John!

Dr. Mohamed Saber Sokar 29 Dr. Mohamed Saber Sokar 30

5
▌Class activity ▌Output to files (Write data to text file)
 To capture all the results of a MATLAB session
in a file.
fprintf ('hello a =%g score=%% %4.2f ', av, a) 1st method:
 Use the command diary
A_balance = 12345;  diary my_file_name,
R_rate = 0.09; at the beginning of the session, use whatever
balance = A_balance + A_balance * R_rate; MATLAB commands you require, then use the
fprintf(... command
' Interest rate:%6.3f %% New balance:%8.2f\n',...  diary off, at the end of the session.
balance, A_balance )
Everything printed in the command window will also
be recorded in the file specified.

Dr. Mohamed Saber Sokar 31 Dr. Mohamed Saber Sokar 32

▌Output to files (Write data to text file) ▌Output to files (Write data to text file)
 2nd method: Write the output directly to a file  2nd method: Write the output directly to a file
 This requires three steps:  fprintf(fileID,formatSpec,A1,...,An)
1- Open a file with the appropriate name and permissions.  Example: Write a short table of the exponential function to a
fid = fopen(my_file_name, 'w'); x text
= 0:file .1
called exp.txt
: 1;
It opens the file specified in the string my_file_name y = [x; exp(x)];
and discards any existing contents already in that file. fid = fopen('ttt.txt','w');
2- Use the fprintf specifying the file to write to. fprintf(fid,'%6s %12s\n','x‘,'exp(x)');
fprintf(fileID, formatSpecifications, variable_list);
fprintf(fid,'%6.2f %12.8f\n',y);
as required to write information to the file with identifier
fclose(fid); % Close the file
fileID.
3- At the end of your program, close the file using The first call to fprintf prints header text x and exp(x), and
fclose(fileID); the second call prints the values from variable A.
Dr. Mohamed Saber Sokar 33 Dr. Mohamed Saber Sokar 34

▌Write data to text file


fprintf(formatSpec,A1,...,An)
PART (III)

 Example: Print multiple numeric values and literal text to the
screen.
A1 = [9.9, 9900];
A2 = [8.8, 7.7 ; 8800, 7700];
formatSpec = 'X is %4.2f meters or %8.3f mm\n'; MATLAB FUNCTIONS
fprintf(formatSpec,A1,A2)

X is 9.90 meters or 9900.000 mm


X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm

The first call to fprintf prints header text x and exp(x), and
the second call prints the values from variable A.
Dr. Mohamed Saber Sokar 35 Dr. Mohamed Saber Sokar 36

6
▌Matlab mathematical Functions -01 ▌Matlab mathematical Functions-02
 Logarithmic functions: Functions for complex numbers:
log(x) (base e “ ln ”),,  z=a+j b
log10(x) (base 10) or
exp(x) (ex),  z  r
O
 Trigonometric functions:
sin(x), cos(x), tan(x),
asin(x), acos(x), atan(x)
 Hyperbolic functions:
sinh(x), cosh(x), tanh(x),
asinh(x), acosh(x), atanh(x)

Dr. Mohamed Saber Sokar 37 Dr. Mohamed Saber Sokar 38

▌Matlab mathematical Functions-02 ▌Matlab mathematical Functions-02


 Functions for complex numbers: z = a + j b  Other functions:
Matlab format Description abs(x) (absolute value),
int(x) (integer part),
real(z) real part
sign(x) (sign function returns -1, 0, or +1) ,
imag(z) imaginary part
round(x) (rounds to the closest integer),
conj(z) conjugated z = a — j b
mod (x,y) (remainder when x is divided by y)
abs(z) modulus sqrt(x) (Square root) ,
angle(z) phase angle φ= tan-1y/x factorial(n) (n!) n! - Calculating factorial
z = complex(a , b) z=a+j b
z=a+bi or z= a+i*b

Dr. Mohamed Saber Sokar 39 Dr. Mohamed Saber Sokar 40

▌Date and Time functions ▌Date and Time functions


 clock :Returns a six element date vector containing the  Date Returns a string containing the date in dd-mmm-yyyy
current time and date in decimal form: format.
[year month day hour minute seconds]). >> date
 >> d=clock ans =
d= 03-Nov-2015
1.0e+003 *
2.0150 0.0110 0.0030 0.0100 0.0200 0.0041  datestr(x,option_date_form): converts an internal
 NOW : Returns the current date and time as a serial date date x into a human readable string with current
number. It is similar to >> datenum(d) time.
>> now  Datestr(d)
ans = >> datestr(d)
7.3518e+005 ans = 03-Nov-2015 10:48:16

Dr. Mohamed Saber Sokar 41 Dr. Mohamed Saber Sokar 42

7
▌Date and Time functions ▌Date and Time functions
 datevec(x) converts an internal date x into a date  tic sets a “stopwatch” going.
vector  toc outputs the value of the stopwatch (in seconds).
>> datevec(d)
ans = >> tic
5.0000 7.0000 4.0000 0 0 0 .....
0 1.0000 11.0000 0 0 0 .....
0 1.0000 1.0000 0 0 0 .....
0 1.0000 7.0000 0 0 0 >> toc
0 1.0000 19.0000 0 0 0 Elapsed time is 200.344312 seconds.
0 1.0000 16.0000 19.0000 3.0000 21.6000
Dr. Mohamed Saber Sokar 43 Dr. Mohamed Saber Sokar 44

▌Utility functions
 They are used to interact with the file system
/workspace of the computer we are operating on.
Many thank for Your
attention

Dr. Mohamed Saber Sokar 45 Dr. Mohamed Saber Sokar 46

You might also like