Introduction To MATLAB: Done By: Eng. Shima' Abed Rabbo Eng. Arwa Aqel

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

Introduction to MATLAB

DONE BY : ENG. SHIMA’ ABED RABBO


ENG. ARWA AQEL
• MATLAB is a software package for doing numerical
computation. It was originally designed for solving linear
algebra type problems using matrices. It’s name is derived
from MATrix LABoratory.

• MATLAB has since been expanded and now has built-in


functions for solving problems requiring data analysis, signal
processing, optimization, and several other types of scientific
computations. It also contains functions for 2-D and 3-D
graphics and animation.
Workspace:
Current
Explore data that
Folder:
you created or
Access your
Command Window: imported from files.
files.
Enter commands at the
command line, indicated
by the prompt (>>).
MATLAB Variables names
 Variable names are case sensitive.
 Variable names can contain up to 63 characters ( as of MATLAB 6.5
and newer).
 Variable names must start with a letter and can be followed by letters,
digits and underscores.
 Examples :
Special Variables and Constants:

 MATLAB supports the following special variables and constants:

Name Meaning

ans Most recent answer.

eps Accuracy of floating-point precision.

i or j The imaginary unit √-1.

Inf Infinity.

NaN Undefined numerical result (not a


number).
pi The number π
Commands for Managing a Session
 MATLAB provides various commands for managing a session. The
following table provides all such commands:

Command Purpose

Clc Clears command window.

clear Removes variables from memory.

help Searches for a help topic.

quit Stops MATLAB.

who Lists current variables.


Commonly used Operators and Special Characters:

 MATLAB supports the following commonly used operators


and special characters:

Operator Purpose

+ Plus; addition operator.

- Minus; subtraction operator.

* Scalar and matrix multiplication


operator.

.* Array multiplication operator.

^ Scalar and matrix exponentiation


operator.

.^ Array exponentiation operator.

\ Left-division operator.
/ Right-division operator.

.\ Array left-division operator.

./ Array right-division operator.

, Colon; generates regularly spaced elements


and represents an entire row or column.

() Parentheses; encloses function arguments


and array indices; overrides precedence .
[] Brackets; enclosures array elements.

; Semicolon; separates columns and suppresses


display.
% Percent sign; designates a comment and
specifies formatting.
= Assignment operator.
Use of Semicolon (;) in MATLAB :
 For example:
Adding Comments :

 The percent symbol (%) is used for indicating a comment


line. For example:
 In MATLAB environment, every variable is an array or
matrix.
 Multiple Assignments : You can have multiple
assignments on the same line. For example,
The format Command
 By default, MATLAB displays numbers with four decimal place values.
This is known as short format.
 However, if you want more precision, you need to use the format
command.
 The format long command displays 16 digits after decimal. For
example:
 The format rat command gives the closest rational expression resulting
from a calculation. For example,
Creating Vectors

 A vector is a one-dimensional array of numbers. MATLAB allows


creating two types of vectors: 1. Row vectors . 2. Column vectors .
 Row vectors are created by enclosing the set of elements in square
brackets, using space or comma to delimit the elements.
 For example:
 Column vectors are created by enclosing the set of
elements in square brackets, using semicolon (;) to delimit
the elements.
Creating Matrices

 A matrix is a two-dimensional array of numbers.


 In MATLAB, a matrix is created by entering each row as a sequence of
space or comma separated elements, and end of a row is
demarcated by a semicolon. For example, let us create a 3-by-3
matrix as:
Vector, Matrix, and Array Commands

Command Purpose

cat Concatenates arrays.

find Finds indices of nonzero


elements.

length Computes number of elements.

linspace Creates regularly spaced vector.


logspace Creates logarithmically spaced
vector.
max Returns largest element.

min Returns smallest element.

prod Product of each column.

size Computes array size.

sort Sorts each column.

sum Sums each column.

eye Creates an identity matrix.

ones Creates an array of ones.

zeros Creates an array of zeros.

cross Computes matrix cross products.

dot Computes determinant of an


array.
M-FILES:

 we have used MATLAB environment as a calculator.


However, MATLAB is also a powerful programming
language, as well as an interactive computational
environment.

 you have learned how to enter commands from the


MATLAB command prompt. MATLAB also allows you to
write series of commands into a file and execute the file
as complete unit, like writing a function and calling it.
 Scripts - script files are program files with .m extension. In
these files, you write series of commands, which you
want to execute together. Scripts do not accept inputs
and do not return any outputs. They operate on data in
the workspace.

 Functions - functions files are also program files with .m


extension. Functions can accept inputs and return
outputs. Internal variables are local to the function.
OPERATORS:

 An operator is a symbol that tells the compiler to perform


specific mathematical or logical manipulations .

 MATLAB allows the following types of elementary


operations:
1. Relational Operators
2. Logical Operators
3. Set Operations
Relational Operators :
 Relational operators can also work on both scalar and non-
scalar data. Relational operators for arrays perform element-
by-element comparisons between two arrays and return a
logical array of the same size, with elements set to logical 1
(true) where the relation is true and elements set to logical 0
(false) where it is not.
Operator Description

< Less than .

<= Less than or equal to .

> Greater than .

>= Greater than or equal to .

== Equal to.

~= Not Equal to .
 Apart from the above-mentioned relational operators,
MATLAB provides the following commands/functions
used for the same purpose :
Function Description

eq(a, b) Tests whether a is equal to b .

ge(a, b) Tests whether a is greater than or equal to b .

gt(a, b) Tests whether a is greater than b .

le(a, b) Tests whether a is less than or equal to b .

lt(a, b) Tests whether a is less than b .

ne(a, b) Tests whether a is not equal to b .

isequal Tests arrays for equality .

isequaln Tests arrays for equality, treating NaN values as


equal .
Logical Operators:

 MATLAB offers two types of logical operators and functions:


1. Element-wise : These operators operate on corresponding
elements of logical arrays.
2. Short-circuit : These operators operate on scalar and logical
expressions.
 Element-wise logical operators operate element-by-element
on logical arrays. The symbols &, |, and ~ are the logical array
operators AND, OR, and NOT.
 Short-circuit logical operators allow short-circuiting on logical
operations. The symbols && and || are the logical short-
circuit operators AND and OR.
Functions for Logical Operations:
Function Description

and(A, B) Finds logical AND of array or scalar inputs; performs a logical


AND of all input arrays A, B, etc. and returns an array
containing elements set to either logical 1 (true) or logical 0
(false).
not(A) Finds logical NOT of array or scalar input; performs a logical
NOT of input array A and returns an array containing elements
set to either logical 1 (true) or logical 0 (false).
or(A, B) Finds logical OR of array or scalar inputs; performs a logical OR
of all input arrays A, B, etc. and returns an array containing
elements set to either logical 1 (true) or logical 0 (false).
xor(A, B) Logical exclusive-OR; performs an exclusive OR operation on
the corresponding elements of arrays A and B.
all(A) Determine if all array elements of array A are nonzero or true.
any(A) Determine if any array elements are nonzero; tests
whether any of the elements along various dimensions
of an array is a nonzero number or is logical 1 (true). The
any function ignores entries that are NaN (Not a
Number).

ind = find(X) Find indices and values of nonzero elements; locates all
nonzero elements of array X, and returns the linear
indices of those elements in a vector. If X is a row
vector, then the returned vector is a row vector;
otherwise, it returns a column vector. If X contains no
nonzero elements or is an empty array, then an empty
array is returned.
Programming Commands

1. If / if else
2. Switch
3. While
4. For
5. Break
6. Continue
Decision Making (if / if else):

An if ... end statement consists of a


Boolean expression followed by one
if . statement.. end or more statements .

An if statement can be followed by an


optional else statement, which
if.. Statement..else.. statement..end executes when the Boolean
expression is false.

You can use one if or elseif statement


nested if statements inside another if or elseif
statement(s).
 The general form of the ‘if’:
statement is
>> if expression
… >>
>> elseif expression
… >>
>> else
… >>
>> end
Switch

A switch statement allows a variable


switch statement : to be tested for equality against a list
of values.

nested switch statements : You can use one switch statement


inside another switch statement(s).
 The general form of the switch
statement is:
>> switch switch_expr
>> case case_expr1
… >>
>> case case_expr2
… >>
>> otherwise
… >>
>> end
Example:

>> x = 2, y = 3;
>> switch x
>> case x==y
>> disp('x and y are equal');
>> case x>y
>> disp('x is greater than y');
>> otherwise
>> disp('x is less than y');
>> end

x is less than y
LOOP TYPES :

 There may be a situation when you need to execute a


block of code several number of times. In general,
statements are executed sequentially. The first statement
in a function is executed first, followed by the second, and
so on.

 Programming languages provide various control structures


that allow for more complicated execution paths.
while loop: Repeats a statement or group of
statements while a given condition is true. It tests the
condition before executing the loop body.

for loop :Executes a sequence of statements multiple


times and abbreviates the code that manages the
loop variable.

nested loops : You can use one or more loops inside


any another loop.
while Loop :

The general form of a while statement is:

>> while expression


… >>
… >>
>> end
 Example 1:
>> n = 1;
>> y = zeros(1,10);
>> while n <= 10
>> y(n) = 2*n/(n+1);
>> n = n+1; Note: In
>> end MATLAB ‘1’ is
synonymous to
TRUE and ‘0’ is
 Example 2: synonymous to
‘FALSE’
>> x = 1;
>> while x
>> %execute statements
>> end
for Loop :

 The general form of a for statement is


>> for variable=expression
… >>
… >>
>> end
 Example:

>> for x = 0:0.05:1


>> printf(‘%d\n’,x);
>> end
The Nested Loops :

 Example:

>> n=2 ; m=3 ;


>> a = zeros(n,m);
>> for i = 1:n
>> for j = 1:m
>> a(i,j) = 1/(i+j);
>> end
>> end
The break Statement.

The continue Statement.


 break terminates the execution of for and while loops
 In nested loops, break terminates from the innermost loop only
 Example:
>> y = 3;
>> for x = 1:10
>> printf(‘%5d’,x);
>> if (x>y)
>> break;
>> end
>> end
FUNCTIONS:
 A function is a group of statements that together perform a task. In
MATLAB, functions are defined in separate files. The name of the file
and of the function should be the same.

 Functions can accept more than one input arguments and may
return more than one output arguments Syntax of a function
statement is :
Plotting Commands :
 To plot the graph of a function, you need to take the
following steps:

1. Define x, by specifying the range of values for the


variable x, for which the function is to be plotted.

2. Define the function, y = f(x) .

3. Call the plot command, as plot(x, y)


 Adding Title, Labels, Grid Lines, and Scaling on the Graph
:

▪ MATLAB allows you to add title, labels along the x-axis


and y-axis, grid lines and also to adjust the axes to
spruce up the graph.
▪ The xlabel and ylabel commands generate labels along
x-axis and y-axis.
▪ The title command allows you to put a title on the graph.
▪ The grid on command allows you to put the grid lines on
the graph.
▪ The legend command.
 Setting Colors on Graph: Table # 1.
 Setting Axis Scales :

 Generating Sub-Plots :
Example 1 : (array)
fx>> x = [ -2 -1 0 1 2 3 4 5 6 ];
y = [ -2 -1 0 1 2 3 4 5 6];
plot(x,y,'g-')

Example 2 : (interval)
fx>> syms x y
x= 0:0.5:4
y=exp(x)
plot(x,y)
Example 3:
fx>> x = 0:0.1:2;
y=sin(x);
z=cos(x);
plot (x,y,'b--*',x,z,'ro')
xlabel('x')
ylabel('sin and cos')
title ('function')
legend('sin(x)','cos(x)')
grid on
ALGEBRA :
 Solving Basic Algebraic Equations in MATLAB .
 Solving Quadratic Equations in MATLAB .
 Solving Higher Order Equations in MATLAB .
Example 1:
Solve the following equations on matlab (i.e. find the value of x, y and z ?)?
3x + 10y - z = 0
-2x + y - 10z = -2
x+y-z=3

x
y
z
Example 2:
Solve the following polynomial function f(x) on matlab (i.e. find the value of x?)?
f(x) = x4 + 7x3 - 5x + 9
** There are different ways to find the root x:
Example 3:
Find the value of the following polynomial function f(x) at x = 0 on matlab (i.e. find f(x=0) ?
f(x) = x2 - 7x + 12
** There are different ways to find f(0):
DIFFERENTIAL

 Derivatives of Exponential, Logarithmic, and Trigonometric Functions.


 Computing Higher Order Derivatives .
 Finding the Maxima and Minima of a Curve .
Example 1:
Find f’(x=0) for the polynomial function f(x) = 3x2 + 2x + 1
** There are different ways to find f’(0):
Example 2:
Find for the polynomial function f(x,y) = x4 - exp(x*y) :
𝑑𝑓 𝑑𝑓 𝑑2𝑓 𝑥 =1
, and ቤ
𝑑𝑥 𝑑𝑦 𝑑𝑦 2 𝑦 =2
Finding the Maxima and Minima of a Curve:

 Let us find the stationary points of the function f(x) = 2x3 + 3x2 − 12x + 17.
 Take the following steps :
 Ex : (step #1)
syms x
y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function
ezplot(y)
 (step #2):
syms x
y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function
ezplot(y, [-2, 2])
 (step#3):Next, let us compute the derivative.
g = diff(y)
 (step #4):Let us solve the derivative function, g, to get the values where it becomes
zero.
s = solve(g)
INTEGRATION

 Finding Indefinite Integral Using MATLAB .


 Finding Definite Integral Using MATLAB .
Example 1:
Find ‫ 𝑥𝑑 𝑥 𝑓 ׬‬and ‫ 𝑥𝑑 𝑥 𝑓 ׭‬for the polynomial function f(x) = x3 + 5
** There are different ways to find these integrals:
Example 2:
2 2 2
Find ‫׭‬−1 𝑓(𝑥, 𝑦) 𝑑𝑦 𝑑𝑥 and ‫׬‬−1 ‫׬‬−1 𝑓 𝑥, 𝑦 𝑑𝑦 𝑑𝑥 , for the polynomial function f(x,y) = x2 * y2

You might also like