2.introduction To Matlab

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

Introduction to Matlab

Dr. Zeina Rihawi


Dr. Freeha Azmat

EDA
Topics

• What is Matlab
• Variables
• Vectors
• Scripts
Vectors

EDA
Vectors
• 1-by-1 arrays are also called scalars 5

5 88 3 11
• 1-by-N arrays are also called row vectors
3

• N-by-1 arrays are also called column vectors 7

• Row and Column vectors together form matrix 9 6 3

5 7 2

• In Matlab, all arrays of numbers are called double arrays


Vectors
You can create a row vector by using the following notation
>>p = [3 7 9]
p = 3 7 9

You can also create a column vector by separating the elements by semicolons.
>>g = [3;7;9]
g =
3
7
9
Referencing the Elements of a Vector
If A is a vector (i.e., a row or column vector), then
A(1) is its first element, A= [ a b c d]
A(2) is its second element
1 2 3 4 Index
Example
>> A = [ 3 4.2 -7 10.1 0.4 -3.5 ];
>> A(3) Ans = -7
>> Index = 5;
>> A(Index) Ans = 0.4

When you reference a vector with a colon; A(:), what happens?


Special Vectors
• Initializing a vector to zeros
>> x = zeros(1, 5)
x= 0 0 0 0 0

• Initializing a vector to ones


>> x = ones(1, 6)
x= 1 1 1 1 1 1

• Initializing a vector to random numbers


>> x = rand(1, 4)
x = 0.9501 0.2311 0.6068 0.4860
Vector Operations
• Addition and subtraction: You can add or subtract two vectors. Both
the operand vectors must be of same type and have same number of
elements.
• Scalar multiplication of vectors: multiply a vector by a number.
• Transpose of a Vector: Changes a column vector into a row vector and
vice versa.
Example
>> r = [ 1 2 3 4 ];
>> tr = r';
>> disp(tr)
1
2
3
4
Vector Operations
You can create vectors by appending one vector to another.

r = [2 4 20] ;
w = [9 -6 3];
u = [ r w]
The result is the vector u = [2, 4, 20, 9, -6, 3].

What if the vector is a char vector?

Example:
>> phrase1 = 'This is sentence #1. ';
>> phrase2 = 'This is sentence #2.';
>> sentence = [phrase1 phrase2]

sentence =

'This is sentence #1. This is sentence #2.'


Vectors with uniformly spaced
elements:

The colon operator (:) easily generates a large vector of


uniformly spaced elements.
>>x = m:q:n where m=first element, n=last element
and q stands for step size

x = 0:2:8 creates the vector x = [0,2,4,6,8]

y = -3:2 produces the vector y = [-3,-2,-1,0,1,2]


(assuming the default step size of 1)
linspace

•The linspace command also creates a linearly spaced row vector, but
instead you specify the number of values rather than the increment.

•The syntax is linspace(x1,x2,n)


where x1 and x2 are the lower and upper limits and n is the number of
points.

Example,
>> linspace(5,8,31)
is equivalent to 5:0.1:8.

•If n is omitted, the default number of values is 100.


logspace
•The logspace command creates an array of logarithmically spaced
elements.

•Its syntax is logspace(a,b,n), where n is the number of points


between 10a and 10b.

Example,

>> x=logspace(-1,1,4)

x =

0.1000 0.4642 2.1544 10.0000

•If n is omitted, the default number of values is 50.


Length and Absolute Value of a Vector

 The length command gives the number of elements in the vector.


>> x = [2, -4, 5]
>>length(x)
ans = 3

The absolute value of a vector x is a vector whose elements are the


absolute values of the elements of x.

>> x = [2, -4, 5]


>>abs(x)
ans = 2 4 5
sort

Sorts a vector y in ascending order or descending order


[ynew, indx] = sort(y, mode) % mode = 'ascend‘ or
'descend'
• where ynew is the vector with the rearranged (sorted) elements of y and
• indx is a vector containing the original locations of the elements in y.
sort
Example:
y = [-1, 6, 15, -7, 31, 2, -4, -5];

z = [10, 20, 30, 40, 50, 60, 70, 80];

[ynew, indx] = sort(y, 'ascend')


znew = z(indx)
when executed, gives
ynew =
-7 -5 -4 -1 2 6 15 31
indx =
4 8 7 1 6 2 3 5
znew =
40 80 70 10 60 20 30 50
find
Determines the locations (not the values) of all nonzero elements in
a vector (or matrix) that satisfy a user-specified relational and/or
logical condition or expression Expr
indxx = find(X)
Example
>> y = [-1, 0, 15, 0, 0, 2, -4, 0];
>> indxx = find(y);
>> s = y(indxx);

Upon execution, we obtain


indxx =
1 3 6 7
s =
-1 -7 -4 -5
find

If the input of the function find is an expression, then find will


determine the locations of all elements in a vector that satisfy this
expression.

>> indxx = find(Expr)


Example:
>> y = [-1, 6, 15, -7, 31, 2, -4, -5];
>> indxx = find(y<=0)
>> s = y(indxx)
Upon execution, we obtain
indxx =
1 4 7 8
s =
-1 -7 -4 -5
min and max functions
To find the smallest element xmin and its location locmin in a vector, we
use
[xmin, locmin] = min(x)

To find the largest element xmax and its location locmax in a vector, we
use
[xmax, locmax] = max(x)
Example

Upon execution, we find that


x = linspace(-pi, pi, 10); ymax =
0.9848
y = sin(x); kmax =
[ymax, kmax] = max(y) 8
[ymin, kmin] = min(y) ymin =
-0.9848
kmin =
3

y=

-0.0000 -0.6428 -0.9848 -0.8660 -0.3420 0.3420 0.8660 0.9848 0.6428 0.0000
Scripts
Good Programming Practice

EDA
Script
Scripts 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.
Create and run script file
• Using the command prompt: type ‘edit’ in the command prompt. This will
open the editor. You can directly type edit and then the filename (with .m
extension)
• Using the IDE: Alternatively, if you are using the IDE, choose NEW ->
Script. This also opens the editor and creates a file named Untitled. You
can name and save the file after typing the code.
• After creating and saving the file, you can run it in two ways: Clicking the
Run button on the editor window or Just typing the filename (without
extension) in the command prompt: >> prog1 The command window
prompt displays the result
• The file must be in your current directory or it will not run
Script
Comment/uncomment
Run button

Real-time error check

Matlab file path


Help file

Line numbers
Comments
Comments
Single line comments:
• The percent symbol (%) is used for indicating a comment line.
• Comment will not be processed

>> 3 ^ 2 % 3 raised to the power of 2


• Comments have green colour

Multi line comments:


• Highlight the block of code that you want to comment then click on
comment button or type a Control-R to comment the whole block.
• To uncomment the block, once again select the block of code, click
on uncomment button or type Control-T key
Errors
• Single-line command:
In case of error, error
explanation will be displayed
directly and arrow to point the
error location

• Script
Error message will appear in
command window with error
location (line number) and
error explanation
Error types
• Syntax errors such as omitting a parenthesis or comma, or spelling a
command name incorrectly.

• Errors due to an incorrect mathematical procedure, called runtime


errors. Their occurrence often depends on the particular input data.
A common example is division by zero.
Help!
• The following commands can serve as an introduction to MATLAB
and allow you to get help:

• demo will bring up MATLAB Examples in the Help Browser, which has
examples of some of the features of MATLAB
• help will explain any function; help help will explain how help works
• doc will bring up a documentation page in the Help Browser
Example

Click on New  Script


Type the following code in the editor:
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
Total = NoOfStudents + TeachingStaff ...
+ NonTeachingStaff;
disp(Total);

Save the file as: ScriptExample.m


Run the file
Live Script

• Live scripts contain output and graphics with the code that produced
them, together in a single interactive environment called the Live
Editor. 
• To create a live script in the Live Editor, go to the Home tab and
click New Live Script . It has .mlx extension.
• You can divide your code into sections and run each section
individually by clinking the vertical striped bar to the left of the code.
• The output is displayed to the right of the code.
Good programming practice
A good program is:

• Efficient
• Correct (correct syntax & semantics)
• Readable (Easy to read & understand)
• Easy to maintain & enhance
Good programming practice

Keep in mind when using script files:

1. The name of a script file must begin with a


alphabet, and may include digits and the
underscore character, up to 63 characters.

2. Do not give a script file the same name as a variable.

3. Do not give a script file the same name as a MATLAB


command or function. You can check to see if a command,
function or file name already exists by using the exist
command.
Programming style guidelines
• Use mnemonic variable names (names that make sense; for example,
radius instead of xyz)

• Although variables named result and RESULT are different, avoid this as
it would be confusing

• Store results in named variables (rather than using ans) if they are to
be used later

• Do not use ans in expressions


Common mistakes
• Putting a space in a variable name
• the format of an assignment statement as
• expression = variablename
rather than
• variablename = expression

• Using a built-in function name as a variable name, and then trying to


use the function

• Forgetting the operator precedence rules


Exercises

EDA
Exercise
1. Calculate the area and circumference of a circle with a radius of 4 cm.

Area = 50.27 cm2

Circumference = 25.13 cm

2. Create a script file called ShpereScript that will compute and display
volume of a shpere, assume radius=5cm.
Exercise – Flow in a circular channel
The flow rate Q in m3/s in an open channel of circular cross-section
shown in the figure is given by

23/2 Dc5/2 g θ - 0.5sin  2θ 


3/2

Q=
8 sinθ 1 - cosθ 
5/2

Where g = 9.8 m/s2 is the gravitational constant and Dc is given by


d
Dc  1  cos 
2

• If we assume that d = 2 m and θ = 60 ͦ = π/3, write Matlab script to calculate Q


Important Functions

EDA
Commands for managing the
work station
Command Purpose
clc Clears command window
clear Removes variables from memory
exist Checks for exitence of file or variable
global Declares variables to be global
help Searches for a help topic
lookfor Searches help entries for a keyword
quit Stops Matlab
who Lists current variables
whos Lists current variable and indicates if they have
imaginary parts
Decimal-to-Integer Conversion
Functions
Matlab function x y Description
2.7 2.0000
y = fix(x) -1.9 -1.0000 Round towards zero
2.49-2.51j 2.0000-2.0000i
2.7 3.0000
y = round(x) -1.9 -2.0000 Round to nearest integer
-2.49-2.51j 2.0000-3.0000i
2.7 3.0000
y = ceil(x) -1.9 -1.0000 Round toward infinity
2.49-2.51j 3.0000-2.0000i
2.7 2.0000
y = floor(x) -1.9 -2.0000 Round toward minus infinity
2.49-2.51j 2.0000-3.0000i
Complex Number Manipulation
Functions

Matlab function z y Description


z = complex(a,b) a+b*j Form complex number; a and b real
y = abs(z) 3+4j 5 Absolute value:
y = conj(z) 3+4j 3-4j Complex conjugate
y = real(z) 3+4j 3 Real part
y = imag(z) 3+4j 4 Imaginary part
y=angle(z) a+b*j atan2(b,a) Phase angle in radians:
References
• Ossman, Kathleen and Bucks, Gregory
Introduction to MATLAB Programming. University of Cincinnati

• Palm, William J. Introduction to MATLAB. University of Rhode Island

• Attaway, Stormy. Matlab: a practical introduction to programming


and problem solving. Butterworth-Heinemann, 2013.

• Magrab, Edward B., and Shapour Azarm. An engineer's guide to


MATLAB. Prentice Hall PTR, 2000.

• MIT courseware

You might also like