matlab
DESCRIPTION
Matlab basicsTRANSCRIPT
GETTING STARTED WITH MATLAB
This lab is to familiarize the students with MATLAB environment through it some
preliminary MATLAB functions.
Introduction to MATLAB
• Too add comment the following symbol is used "%".
• Help is provided by typing “help” or if you know the topic then “help function_name” or
“doc function_name”.
• If you don't know the exact name of the topic or command you are looking for, type "lookfor
keyword" (e.g., "lookfor regression")
• Three dots “...” are used to continue a statement to next line (row).
• If after a statement “;” is entered then MATLAB will not display the result of the statement
entered otherwise result would be displayed.
• MATLAB is case sensitive, so “dsp” is not same as “DSP”. • Use the up-arrow to recall commands without retyping them (and down arrow to go forward in commands).
Basic functionalities of MATLAB
Defining a scalar:
>> 𝑥 = 1
x = 1
Defining a column vector:
>> 𝑣 = [1; 2; 3]
v = 1 2 3
Defining a row vector
>> 𝑤 = [2 1 4]
w = 2 1 4
Transpose a vector
>> 𝑊 = 𝑤′
W = 2
1
4
Defining a range for a vector
>> X = 1: .5: 5
X =
Columns 1 through 7
1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000
Columns 8 through 9 4.5000 5.0000
Empty vector
>> 𝑦 = [ ]
y = []
Defining a matrix
>> 𝑀 = [1 2 3; 4 5 6]
M = 1 2 3 4 5 6
Zero matrix
>> M = zeros(2,3) % 1st parameter is row, 2nd parameter is column.
M = 0 0 0 0 0 0
ones matrix
>> b = ones(2, 3)
b = 1 1 1
1 1 1
Identity matrix
>> I = eye(3)
I = 1 0 0
0 1 0 0 0 1
Define a random matrix or vector
>> R = rand(1,3)
R =
0.1576 0.9706 0.9572
Access a vector or matrix
>> 𝑅(3)
ans = 0.9572
� or >> 𝑅(1,2) ans =
0.9706
Access a row or column of matrix
>> I(2, : ) %2nd row
ans = 0 1 0
>> 𝐼(: ,2) %2nd col
ans =
0
1
0
I(1:2,1:2)
ans =
1 0 0 1
size and length
>> size(I)
ans = 3 3
>> length(I) ans =
3
�
Operations on vector and matrices in MATLAB MATLAB utilizes the following arithmetic operators;
+ Addition
- Subtraction
* Multiplication
/ Division
^ Power operator
‘ transpose
Some built in functions in MATLAB
abs Magnitude of a number (absolute value for real
numbers)
angle Angle of a complex number, in radians
cos Cosine function, arguments is in radians
sin Sine function, arguments in radians
exp Exponential function
sqrt Square root
round Round off to nearest integer
max Maximum value
min Minimum Value
ceil Round towards +∞
floor Round towards −∞
Relational operators in MATLAB Relational operators: =(equal), ~=3D (not equal), etc.
Let >> 𝒂 = [𝟏 𝟏 𝟑 𝟒 𝟏] a = 1 1 3 4 1
>> 𝒅 = (𝒂 == 𝟏)
d=
1 1 0 0 1
>> 𝒅 = (𝒂 < 𝟏)
d =
0 0 0 0 0
>> 𝒅 = (𝒂 > 𝟏)
d =
0 0 1 1 0
>> 𝒅 = (𝒂 <= 𝟏)
d =
1 1 0 0 1
>> 𝒅 = (𝒂 >= 𝟏)
d =
1 1 1 1 1
>> 𝒅 = (𝒂 ~ = 𝟏)
d =
0 0 1 1 0
Basic Plotting in MATLAB MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of computation is
possible with very few commands. You are highly encouraged to plot mathematical functions and results
of analysis as often as possible.
• To plot a graph, MATLAB command is: plot(x, y)
Plot command has different arguments.
Example:
Note:
• 0:𝑝𝑖/100: 2 ∗ 𝑝𝑖 𝑦𝑖𝑒𝑙𝑑𝑠 𝑎 𝑣𝑒𝑐𝑡𝑜𝑟 𝑡ℎ𝑎𝑡
- Starts at 0,
- Takes steps (or increments) of 𝜋/100,
- Stops when 2𝜋 𝑖𝑠 𝑟𝑒𝑎𝑐ℎ𝑒𝑑.
• If you omit the increment, MATLAB automatically increments by 1.
• Adding title, axis label and annotations
• Multiple data set in one plot command
The result of multiple data set in one graph
• Specifying Line styles and color.
plot(x, y, ′style_color_marker′)
Control Flow in MATLAB
Like other computer programming language, MATLAB has decision making statements to control the
flow of program. • the for loops
• the while loops
• the if-else-end constructions
• the switch-case constructions
Syntax of the for loop is shown below
for k = array commands end
The commands between the for and end statements are executed for all values stored in the array. Example
for n=0:10 x(n+1) = sin(pi*n/10); end
x = Columns 1 through 7
0 0.3090 0.5878 0.8090 0.9511 1.0000
0.9511
Columns 8 through 11
0.8090 0.5878 0.3090 0.0000
Syntax of the while loop is
while expression
statements end
This loop is used when the number of repetitions is not known in advance. Suppose that the number
is divided by 2. The resulting quotient is divided by 2 again. This process is continued till the current
quotient is less than or equal to 0.01. What is the largest quotient that is greater than 0.01? To answer this question we write a few lines of code q = pi; while q > 0.01
q = q/2; end q =
0.0061 Syntax of the simplest form of the construction under discussion is
if expression commands
end This construction is used if there is one alternative only. Two alternatives require the construction
if expression
commands (evaluated if expression is true) else commands (evaluated if expression is false) end
If there are several alternatives one should use the following construction
if expression1 commands (evaluated if expression 1 is true) elseif expression
2 commands (evaluated if expression 2 is true) elseif …
... else
commands (executed if all previous expressions evaluate to false) end
Syntax of the switch-case construction is
switch expression (scalar or string) case value1 (executes if expression evaluates to value1) commands case value2 (executes if expression evaluates to value2) commands
... otherwise statement
end Switch compares the input expression to each case value. Once the %match is found it executes
the associated commands.
In the following example a random integer number x from the set {1, 2, … , 10} is generated. If x = 1
or x = 2, then the message Probability = 20% is displayed to the screen. If x = 3 or 4 or 5, then the
message Probability = 30 is displayed, otherwise the message Probability = 50% is generated. The
script file fswitch utilizes a switch as a tool %for handling all cases mentioned above
% Script file (fswitch). x = ceil(10*rand); %Generate a random integer in {1, 2, ... , 10}
switch x case {1,2}
disp('Probability = 20%');
case {3,4,5}
disp('Probability = 30%');
otherwise disp('Probability = 50%');
end
Creating functions using m-files
So far, all the commands were executed in the command window. The commands entered in the
command window cannot be saved or executed again several times. Therefore, there is different
way of executing the commands is possible in MATLAB.
• create a file with list of commands
• Save the file
• Execute the file.
If needed, corrections or changes can be made to the commands in the file. The files of this type
are called script files.
This section covers the following topics:
• m-file script • m- file functions
A script file is an external file that contains a sequence of MATLAB commands. Script files have a
filename extension .𝑚 and are often called M-files. M-files can be scripts that simply execute a series of
MATLAB statements, or they can be functions that can accept arguments and can produce one or more
outputs.
Example:
• Use MATLAB editor to create a file: File → New → M − file
• Enter the following statements in the file
𝐴 = [1 2 3; 3 3 4; 2 3 3];
𝑏 = [1; 1; 2];
𝑥 = 𝐴/𝑏
• Save the file as “first.m”
• Run the file, in command line as
>> 𝑓𝑖𝑟𝑠𝑡
𝑥 =
−0.5000
1.5000
−0.5000
When execution completes, the variables (A, b, and x) remain in the workspace. Function file will be
discussed later.
Exercises:
1. Operate with the vectors V1 = [1 2 3 4 5 6 7 8 9 0] V2 = [0.3 1.2 0.5 2.1 0.1 0.4 3.6 4.2 1.7 0.9] V3 =
[4 4 4 4 3 3 2 2 2 1] a) Calculate, respectively, the sum of all the elements in vectors V1, V2, and V3
b) How to get the value of the fifth element of each vector?
What happens if we execute the command V1(0) and V1(11)? (Remember if a vector
has N elements, their subscripts are from 1 to N). c) Generate a new vector V4 from V2, which is composed of the first five elements of V2.
d) Generate a new vector V5 from V2, which is composed of the last five elements of V2.
e) Derive a new vector V6 from V2, with its 6th element omitted.
f) Derive a new vector V7 from V2, with its 7th element changed to 1.4.
g) Derive a new vector V8 from V2, whose elements are the 1st, 3rd, 5th, 7th, and 9th elements
of V2
h) What are the results of
9-V1 V1*5 V1+V2 V1-V3 V1.*V2 V1*V2 V1.^2 V1.^V3 V1>V3
V3-(V1>2) 2. Compare a script and a function
a) Write a script: In the main menu of Matlab,
select file -> new -> M-file A new window will pop up. Input the following commands:
x = 1:5; y = 6:10;
g = x+y; and then save the file as myscript.m