0% found this document useful (0 votes)
36 views

Matlab DrWasaN

introduction to MATLAB , What is Matlab? 1Matlab Screen 2 Variables, array, matrix, indexing 3 Operators (Arithmetic, relational, logical ) 4 Display Facilities 5 Flow Control 6 Using of M-File 6 Writing User Defined Functions 7 Conclusion

Uploaded by

wasan.eng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Matlab DrWasaN

introduction to MATLAB , What is Matlab? 1Matlab Screen 2 Variables, array, matrix, indexing 3 Operators (Arithmetic, relational, logical ) 4 Display Facilities 5 Flow Control 6 Using of M-File 6 Writing User Defined Functions 7 Conclusion

Uploaded by

wasan.eng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Introduction to Matlab

DR. WASSAN ADNAN HASHIM


@ 2ND YEAR -COMPUTER SCIENCE DEPT.
Outline:
 What is Matlab?
 Matlab Screen
 Variables, array, matrix, indexing
 Operators (Arithmetic, relational, logical )
 Display Facilities
 Flow Control
 Using of M-File
 Writing User Defined Functions
 Conclusion
What is Matlab?
 Matlab is basically a high level language
which has many specialized toolboxes for
making things easier for us
 How high?
Matlab

High Level
Languages such as
C, Pascal etc.

Assembly
Advantages for Computer Vision
Strong on matrix manipulation
Strong visualization tools
Many online Computer Vision libraries
Interfaces with C (mex), Fortran, and Java

Installation
http://www.cmu.edu/computing/software/all/mat
lab/download.html
 When you first open MATLAB, notice:
1. The Command window is where you'll give
MATLAB its input and view its output.
2. The workspace shows you all of your current
working variables and other objects.
3. The history shows you all commands you used
in CW.
4. The Editor for MATLAB scripts (M-files) . To
save & run the m-file type 'F5'. To open the
editor with a new or old m-file use the command
open file_name
Matlab Screen
 Command Window
 type commands

 Current Directory
 View folders and m-files

 Workspace
 View program variables
 Double click on a variable
to see it in the Array Editor

 Command History
 view past commands
 save a whole session
using diary
MATLAB help
 For help, command description etc use F1 or following
commands:
 help command_name

 helpwin command_name

 doc command_name

 helpdesk command_name

 demo command_name
 lookfor keyword (search unknown command)

 http://www.mathworks.com/support/
 For example when running “help sin” one get
SIN Sine of argument in radians.
SIN(X) is the sine of the elements of X.
See also ASIN, SIND.
Overloaded functions
Reference page in Help browser doc sin
Some Useful commands
 what List all m-files in current directory
 dir/ls List all files in current directory
 type test Display test.m in command window
 delete test Delete test.m
 cd/chdir Change directory
 pwd Show current directory
 which test Display directory path to ‘closest’ test.m
 Who, whos current workspace vars
 Save save workspace vars to *.mat file
 clear Clear variables from workspace
 clc Clear the command window
 Load load variable from *.mat file
 Close all close all figures
MATLAB & Matrices

MATLAB treats all variables as matrices. For our


purposes a matrix can be thought of as an array, in fact,
that is how it is stored.

Vectors are special forms of matrices and contain only


one row OR one column.

Scalars are matrices with only one row AND one column
Variable Names
Variable names ARE case sensitive
Variable names can contain up to 63 characters (as of MATLAB 6.5
and newer). One can use command to verify it.
namelengthmax
Variable names must start with a letter followed by letters, digits,
and underscores.
MATLAB variables are defined by assignment. There is no need to
declare in advance the variables that we want to use or their type.
Example
x=1; % Define the scalar variable x
y=[1 2 3] % row vector
z=[1;2;3] % column vector
A=[1 2 3;4 5 6;7 8 9] % 3x3 matrix
whos % List of the variables defined
Note: terminate statement with semicolon (;) to suppress output.
Special Variables

ans Default variable name for results


pi Value of π
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i,j,1i,1j imaginary unit i, i.e. square root of -1
realmin The smallest usable positive realnumber
realmax The largest usable positive real number

SpecialVars.m
Other symbols

>> prompt
... continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range
Relational Operators

 MATLAB supports six relational operators.

Less Than <


Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
Math & Assignment Operators
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a
NOTE: 56/8 = 8\56

- (unary) + (unary)
Addition + a + b
Subtraction - a - b
Assignment = a = b (assign b to a)

Operators.m
MATLAB Logical Operators

 MATLAB supports five logical operators.

not/~ element wise/scalar logical NOT


and/& element wise logical AND
or / | element wise logical OR
&& logical (short-circuit) AND
|| logical (short-circuit) AND
Logical Functions

MATLAB also supports some logical functions.


 xor (a, b) exclusive or
 any(x) returns 1 if any element of x is nonzero
 all(x) returns 1 if all elements of x are nonzero
 isnan(x) returns 1 at each NaN in x
 isinf(x) returns 1 at each infinity in x
 finite(x) returns 1 at each finite value in x
 find(x) find indices and values of non zero
elements
Some Matrix functions

 zeros(rows, cols) – create zero matrix


 rand(rows, cols) – generate random matrix
 ones(rows, cols) – matrix with 1 in all entries
 eye (rows, cols) – identity matrix
 sub2ind, ind2sub indices manipulation
Variables
 No need for types. i.e.,

int a;
double b;
float c;

 All variables are created with double precision unless


specified and they are matrices.
Example:
>>x=5;
>>x1=2;

 After these statements, the variables are 1x1 matrices


with double precision
Array, Matrix
 a vector x = [1 2 5 1]

x =
1 2 5 1

 a matrix y = [1 2 3; 5 1 4; 3 2 -1]

y =
1 2 3
5 1 4
3 2 -1

 transpose y = x’ y =
1
2
5
1
Long Array, Matrix
 t =1:10

t =
1 2 3 4 5 6 7 8 9 10
 k =2:-0.5:-1

k =
2 1.5 1 0.5 0 -0.5 -1

 B = [1:4; 5:8]

x =
1 2 3 4
5 6 7 8
Generating Vectors from functions
 zeros(M,N) MxN matrix of zeros x = zeros(1,3)
x =
0 0 0

 ones(M,N) MxN matrix of ones


x = ones(1,3)
x =
1 1 1
 rand(M,N) MxN matrix of uniformly
distributed random x = rand(1,3)
numbers on (0,1) x =
0.9501 0.2311 0.6068
Matrix Index
 The matrix indices begin from 1 (not 0 (as in C))
 The matrix indices must be positive integer
Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)
Error: ??? Index exceeds matrix dimensions.
Concatenation of Matrices
 x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2
4 5

C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose
Matrices Operations

Given A and B:

Addition Subtraction Product Transpose


Operators (Element by Element)

.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power
The use of “.” – “Element” Operation
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Basic Task: Plot the function sin(x)
between 0≤x≤4π
 Create an x-array of 100 samples between 0
and 4π.

>>x=linspace(0,4*pi,100);

 Calculate sin(.) of the x-array


1

0.8

0.6

>>y=sin(x); 0.4

0.2

 Plot the y-array -0.2

-0.4

-0.6

>>plot(y) -0.8

-1
0 10 20 30 40 50 60 70 80 90 100
Plot the function e-x/3sin(x) between
0≤x≤4π
 Create an x-array of 100 samples between 0
and 4π.
>>x=linspace(0,4*pi,100);

 Calculate sin(.) of the x-array


>>y=sin(x);

 Calculate e-x/3 of the x-array


>>y1=exp(-x/3);

 Multiply the arrays y and y1


>>y2=y*y1;
Plot the function e-x/3sin(x) between
0≤x≤4π
 Multiply the arrays y and y1 correctly
>>y2=y.*y1;

 Plot the y2-array


0.7

>>plot(y2) 0.6

0.5

0.4

0.3

0.2

0.1

-0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities 0.7

0.6

0.5

 plot(.) 0.4

0.3

Example:
0.2

0.1
>>x=linspace(0,4*pi,100); 0

>>y=sin(x); -0.1

>>plot(y) -0.2

>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100

0.7

 stem(.) 0.6

0.5

0.4

0.3

Example:
0.2

0.1
>>stem(y) 0

>>stem(x,y) -0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
Display Facilities

 title(.)
>>title(‘This is the sinus function’)
This is the sinus function
1

0.8

 xlabel(.) 0.6

0.4

>>xlabel(‘x (secs)’) 0.2

sin(x)
0

 ylabel(.) -0.2

-0.4

-0.6

-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
Putting several graphs in one window
 The subplot command creates several plots in a single
window. Here is an example:
 >> t = (0:.1:2*pi)';
 >> subplot(2,2,1)
 >> plot(t,sin(t))
 >> subplot(2,2,2)
 >> plot(t,cos(t))
 >> subplot(2,2,3)
 >> plot(t,exp(t))
 >> subplot(2,2,4)
 >> plot(t,1./(1+t.^2))
Operators (relational, logical)

 == Equal to
 ~= Not equal to
 < Strictly smaller
 > Strictly greater
 <= Smaller than or equal to
 >= Greater than equal to
 & And operator
 | Or operator
Flow Control

 if
 for
 while
 break
 ….
Control Structures
Some Dummy Examples
 If Statement Syntax
if ((a>3) & (b==5))
Some Matlab Commands;
if (Condition_1) end
Matlab Commands
if (a<3)
elseif (Condition_2) Some Matlab Commands;
Matlab Commands elseif (b~=5)
Some Matlab Commands;
elseif (Condition_3) end
Matlab Commands
if (a<3)
else Some Matlab Commands;
Matlab Commands else
end Some Matlab Commands;
end
Control Structures
Some Dummy Examples
 For loop syntax for i=1:100
Some Matlab Commands;
end

for i=Index_Array for j=1:3:200


Some Matlab Commands;
Matlab Commands end

end for m=13:-0.2:-21


Some Matlab Commands;
end

for k=[0.1 0.3 -13 12 7 -9.3]


Some Matlab Commands;
end
Control Structures

 While Loop Syntax

Dummy Example
while (condition)
Matlab Commands while ((a>3) & (b==5))
Some Matlab Commands;
end end
Use of M-File
Click to create
a new M-File

• Extension “.m”
• A text file containing script or function or program to run
Use of M-File Save file as Denem430.m

If you include “;” at the


end of each statement,
result will not be shown
immediately
Writing User Defined Functions

 Functions are m-files which can be executed by


specifying some inputs and supply some desired outputs.
 The code telling the Matlab that an m-file is actually a
function is
function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)

 You should write this command at the beginning of the


m-file and you should save the m-file with a file name
same as the function name
Writing User Defined Functions
 Examples
 Write a function : out=squarer (A, ind)

 Which takes the square of the input matrix if the input


indicator is equal to 1
 And takes the element by element square of the input
matrix if the input indicator is equal to 2

Same Name
Writing User Defined Functions
 Another function which takes an input array and returns the sum and product
of its elements as outputs

 The function sumprod(.) can be called from command window or an m-file as


Writing User Defined Functions
 %%square.m ---- Calculates the square of a number.

 function y = square(x)
 % calculate the square of the given number 'x'
 % Arguments:
 % x (input) value to be squared
 % y (output) the result of the square
 y = x*x;
 end
 % end of square function
Notes:
 “%” is the neglect sign for Matlab (equaivalent
of “//” in C). Anything after it on the same line
is neglected by Matlab compiler.
 Sometimes slowing down the execution is
done deliberately for observation purposes.
You can use the command “pause” for this
purpose
pause %wait until any key
pause(3) %wait 3 seconds
Useful Commands

 The two commands used most by Matlab


users are
>>help functionname

>>lookfor keyword
Questions

 ?
 ?
 ?
 ?
 ?
Thank You…

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy