Lab 01
Lab 01
Learning Objectives:
In this lab, you will learn:
➢ The interface of MATLAB
➢ Basic arithmetic operators
➢ Matlab variables
➢ Matrix manipulation
Description:
Examples:
Strengths of MATLAB
“Fig 1.2”
3. Workspace Browser:
The MATLAB workspace consists of the set of variables (named arrays) built up
during a MATLAB session and stored in memory.
“Fig 1.3”
4. Array Editor:
“Fig 1.5”
Addition + 3 + 22
Subtraction - 54.4 – 16.5
Multiplication * 3.14 * 6
Division / or \ 10/2 or 2\10
• Expressions are evaluated from left to right, with precedence;
Exponentiation > Multiplication & Division > Addition & Subtraction.
• The first character MUST be alphabetic followed by any number of letters, digits, or
underscore.
• The variable names are case sensitive.
• Blanks are NOT allowed in a variable name.
• Variable names can contain up to 63 characters.
• Punctuation characters are not allowed, because many of them have special meanings in
Matlab.
Examples:
>>a = 2
a=
>> 2*pi
ans =
6.2832
Types of Variables:
Type Examples
Integer 1362,-5656
Real 12.33,-56.3
Complex X=12.2 – 3.2i (i = sqrt(-1))
Complex numbers in MATLAB are represented in rectangular form. To separate real &
imaginary part
• H = real(X)
• K = imag(X)
• Conversion between polar & rectangular
• C1 = 1-2i
• Magnitude: mag_c1 = abs(C1)
• Angle: angle_c1 = angle(C1)
• Note that angle is in radians
• Extras:
Using up-arrow key allow user to recall most recently used commands
Another trick is to use a ‘letter’ prior using up-arrow
: specify range
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.
• A matrix can be created in MATLAB as follows (note the commas AND semicolons):
» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
matrix =
1 2 3
4 5 6
7 8 9
Row Vector:
• A matrix with only one row is called a row vector. A row vector can be created in MATLAB
as follows (note the commas):
» rowvec = [12 , 14 , 63]
rowvec =
12 14 63
• Row vector can also defined in a following way:
rowvec = 2 : 2 : 10; % start : step size : stop
Column Vector:
• A matrix with only one column is called a column vector. A column vector can be created in
MATLAB as follows (note the semicolons):
colvec =
13
45
-2
Extracting a Sub-Matrix:
• A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names
of both matrices and the rows and columns to extract. The syntax is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the
beginning and ending columns to be extracted to make the new matrix.
• A column vector can be extracted from a matrix. As an example we create a matrix below:
1 2 3 col_two = 2
4 5 6 5
7 8 9 8
• A row vector can be extracted from a matrix. As an example we create a matrix below:
1 2 3 » rowvec =matrix(2 : 2 , 1 : 3)
4 5 6 rowvec =
7 8 9 4 5 6
Concatenation:
• New matrices may be formed out of old ones
• Suppose we have:
a = [1 2; 3 4]
a=12
34
Input output
[a , a, a] ans = 1 2 1 2 1 2
3 4 3 4 3 4
[a ; a; a] ans =
1 2
3 4
1 2
3 4
1 2
3 4
» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
1 2 3
4 5 6
» c = a * b % Multiply each element of b by a
c=
3 6 9
12 15 18
ans =
• min(a) :Return a row vector containing the minimum element from each column.
ans = 1 2 3
• max(a) : Return a row vector containing the maximum element from each column.
ans = 7 8 9
• sum (a) : treats the columns of ‘a’ as vectors, returning a row vector of the sums of each
column.
ans = 12 14 18
• sum(sum(a)): Calculate the sum of all the elements in the matrix.
ans = 44
• size (a) : gives the number or rows and the number of columns:
>> [r c] = size(a)
r=3 c=3
• Let a =[ 4 5 6] , length(a) finds the number of elements in row vector.
• a.*b :Bitwise multiply the each element of vector ‘a’ and ‘b’:
ans =
4 10 18
Matrix Division:
• MATLAB has several options for matrix division. You can “right divide” and “left divide”.
Matrix of Zeros:
• Example;
>> zeros(2) >> zeros(1,2)
ans = ans =
0 0 0 0
0 0
Matrix of Ones:
• Example;
>> I=eye(3)
I=
100
010
001
Description:
M-files:
• MATLAB can execute a sequence of MATLAB statements stored on disk. Such files are
called "M-files"
• They must have the file type of ".m"
• To make the m-file click on File next select New and click on M-File from the pull-down
menu as shown in “Fig 2.1”
• You will be presented with the MATLAB Editor/Debugger screen as shown in “Fig 2.2”
“Fig 2.2”
• Here you will type your code, can make changes, etc.
• Once you are done with typing, click on File, in the MATLAB Editor/Debugger screen and select Save
As…
• Chose a name for your file, e.g., firstgraph.m
• Click on Save.
• Make sure that your file is saved in the directory that is in MATLAB's search path.
• There are two types of M-files:
▪ Script files
Script Files:
• Script files do not take the input arguments or return the output arguments
• Example (plotxy.m)
x = [1 2 3; 4 5 6]
y = [2 3 4; 6 7 8]
plot(x,y)
Input Function:
• Syntax : Prompt for user input
• Format : input(‘String to display’)
• Description:
Input function is used to get data from user and prompts until data has been entered.
• Example;
>> marks = input (‘Enter total marks = ’)
Enter total marks = 5
marks =
5
Disp Function:
• Syntax : Display array
• Format : disp(variable_name), disp(‘String to display’)
• Description:
Displays the array, without printing the array name. In all other ways it's the same as leaving the
semicolon off an expression except that empty arrays don't display.
• Example;
>> disp(‘ hello ’)
hello
>> a=[1 3 5];
>> disp(a)
1 3 5
If block Examples:
if (x < 10)
if (<condition>) disp(x); % only displays when x < 10
<body> end
end
if ((0 < x) & (x < 100))
disp('OK');
end
end
If block Example:
if (<condition>) if (n <= 0)
<body> disp('n is negative or zero');
else if
<body> elseif (rem(n,2)==0)
else disp('n is even');
<body> else
end disp('n is odd');
end
for block
Example:
for i = 1:1:10 a = zeros(k,k) % Preallocate matrix
for m = 1:k
<body> for n = 1:k
a(m,n) = 1/(m+n -1);
end
end
end
switch statement
Example:
switch<expression>
method = 'bilinear';
switch lower(method)
case <condition>,
case {'linear','bilinear'}
<statement>
disp('Method is linear')
PLOTTING
case 'cubic'
otherwise
TWO-DIMENSIONAL plot() COMMANDdisp('Method is cubic')
<condition>,
otherwise
<statement>
disp('Unknown method.')
end
end
Method is linear
• where x is a vector (one dimensional array), and y is a vector. Both vectors must have the same
number of elements.
• The plot command creates a single curve with the x values on the abscissa (horizontal axis) and
the y values on the ordinate (vertical axis).
• The curve is made from segments of lines that connect the points that are defined by the x and y
coordinates of the elements in the two vectors.
plot (x,y)
• Once the plot command is executed, the Figure Window opens with the following plot as shown
in “Fig 2.3”
“Fig 2.3”
plot(x,y,’line specifiers’)
Marker Specifier:
Color Specifiers:
• The specifiers are optional. This means that none, one, two, or all the three can be included in a
command.
Example:
• plot(x,y) A solid blue line connects the points with no markers.
• plot(x,y,’*’) The points are marked with * (no line between the points.)
Plot of given data using the line specifiers in the plot ( ) command
Ye 19 19 19 19 19 19 19
ar 88 89 90 91 92 93 94
Sales 1 1 1 1 1 1 2
(M) 2 3 3 4 5 7 1
>>year = [1988:1:1994];
>> sales = [127, 130, 136, 145, 158, 178, 211];
>> plot(year,sales,'--r*')
“Fig 2.4”
Formatting Commands:
title(‘string’)
Adds the string as a title at the top of the plot.
xlabel(‘string’)
Adds the string as a label to the x-axis.
ylabel(‘string’)
Adds the string as a label to the y-axis.
legend(‘string1’,’string2’,’string3’)
Creates a legend using the strings to label various curves (when several curves are
in one plot). The location of the legend is specified by the mouse.
text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y relative to the plot axes.
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
plot(x,y,x,z)
title('Sample Plot','fontsize',14);
xlabel('X values','fontsize',14);
ylabel('Y values','fontsize',14);
legend('Y data','Z data')
grid on
• Three typical ways to display multiple curves in MATLAB (other combinations are possible…)
▪ One figure contains one plot that contains multiple curves
o Requires the use of the command “hold” (see MATLAB help)
▪ One figure contains multiple plots, each plot containing one curve
o Requires the use of the command “subplot”
▪ Multiple figures, each containing one or more plots, each containing one or more curves
o Requires the use of the command “figure” and possibly “subplot”
Example:
Or
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
plot(x,y,’b’)
hold on
Plot(x,z,’g’)
hold off
grid on
Subplots:
• Subplot divides the current figure into rectangular panes that are numbered row wise.
• Syntax:
subplot(rows,cols,inde
x)
“Fig 2.6”
Example of Subplot:
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
subplot(1,2,1);
plot(x,y)
subplot(1,2,2)
plot(x,z)
grid on
Multiple Figures:
Example:
x=[0:0.1:2*pi];
y=sin(x);
z=cos(x);
figure;
plot(x,y)
figure;
plot(x,z)
grid on