MCT233 Lab1
MCT233 Lab1
FACULTY OF ENGINEERING
MECHATRONICS ENGINEERING DEPARTMENT
Contents
1- Open MATLAB and identify its environment and windows.
2- Entering Commands and Expressions
3- Variables and data types in MATLAB.
4- Plotting
5- Use MATLAB Help.
6- Open M-File Script and identify its environment
7- Writing M-file
8- Conditional Statements
9- Loops
1. This Desktop manages the Command window, Working Folder, Variables Workspace and a
Help Browser as well as other tools. The desktop has the following panels:
❖ Current Folder (Working Folder) - This panel allows you to access the project folders
and files. You can change the current folder of your project by using browse icon.
❖ Command Window - This is the main area where commands can be entered at the
command line. It is indicated by the command prompt (>>).
Page 1 of 14
❖ Workspace - The workspace shows all the variables created and/or imported from files.
❖ You can change the MATLAB Desktop Layout from the “Layout” icon in the HOME
Tab. You can show also the Command History window.
Command History - This panel shows or rerun commands that are entered at the
command line.
2. Explore the other icons in HOME, PLOTS, and APPS Tabs and their different functions and
options.
Discussion:
>> 8/10
ans =
0.8000
Remember, the symbol >> automatically appears on the screen; you do not type it.
>> 5*ans
ans =
4
4. Explore what changes happened in the variables inside the Workspace window compare to step
b? Comment! The variable ans now has the value 4. Why!
Discussion:
5. You can define your own variables to write mathematical expressions. Instead of using the
default variable ans, you can assign the result to a variable of your own choosing, say, r, as
follows:
>> r=8/10
r=
0.8000
Page 2 of 14
7. A semicolon (;) at the end of a line in Command Window suppresses printing the results to the
screen. If a semicolon is not put at the end of a line, MATLAB displays the results of the line on
the screen. Even if you suppress the display with the semicolon, MATLAB still retains the
variables value.
Try the following as see the difference:
>>z=3+5;
>>c=3+5
Discussion:
Comments:
❖ Use whos, who, exist(‘x2’), exist(‘x7’), clc, clear(‘x3’), clear, exit, and quit. Hence, comment
on the outputs.
Discussion:
Page 3 of 14
9. Special variables and constants
MATLAB has several built-in special constants such as
Command Description
ans Temporary variable containing the most recent answer.
eps Accuracy of floating-point precision.
In MATLAB, "eps" refers to the precision of floating numbers.
Moreover, its value depends on the type of floating data you are
using. E.g. if data type is "double", eps is 2-52, and if it's "single" eps
is 2-23. Then, the precision value (eps) changes depending on data
type. It can also be used as a constant.
i,j The imaginary unit √−1.
Inf ∞
NaN Undefined numerical result (not a number)
pi π=3.1416
Type:
>>s = 3+7i;w = 5-9i;
>>w+s
>>w/s
>>pi
❖ Type:
>>volume=100;
>>area=20;
>>radius=50;
After you have entered these and you want to recall the volume variable to change its value, type
vol and press the up-arrow key (↑). This will recall the last-typed line that starts with the function
or variable whose name begins with vol. This feature is case-sensitive
There are many format types in MATLAB. The following table summarised some of these
formats. Explorer MATLAB help to find more
Command Description
format short Four decimal digits (the default); e.g:13.6745.
format long 16 digits; e.g: 17.27484029463547.
format short e Five digits (four decimals) plus exponent; e.g: 6.3792e+03.
format long e 16 digits (15 decimals) plus exponent; e.g: 6.379243784781294e+04.
format bank Two decimal digits; e.g:126.73.
format + Positive, negative, or zero; e.g: +.
format rat Rational approximation; e.g. 43/7.
❖ Test the previous table on x = 7 + 10/3 + 5 ^ 1.2 and comment on the results:
Discussion:
Page 5 of 14
3. Exercise 3: Variables and data types in MATLAB.
1. One of the strengths of MATLAB is the capability to handle collections of items, called arrays,
as if they were a single entity. It provides more than 15 fundamental data types. Every data type
stores data that is in the form of a matrix or array. The size of this matrix or array is a minimum
of 0-by-0 and this can grow up to a matrix or array of any size. This array can be numeric,
character, logical, cell, structure, function handle, etc. For example, numeric arrays, which are
arrays containing only numeric values within its numeric class are subclasses into single (single
precision), double (double precision), int8, int16, and int32 (signed 8-bit, 16-bit, and 32-bit
integers), and uint8, uint16, and uint32 (unsigned 8-bit, 16-bit, and 32-bit integers). On the other
hand, a character array is an array containing strings. The most commonly used data types in
MATLAB are summarised in this table
Data Type Description
Int8 8-bit signed integer
uint8 8-bit unsigned integer
int16 16-bit signed integer
uint16 16-bit unsigned integer
int32 32-bit signed integer
uint32 32-bit unsigned integer
int64 64-bit signed integer
uint64 64-bit unsigned integer
single single precision numerical data
double double precision numerical data
logical logical values of 1 or 0, represent true and false respectively
char character data (strings are stored as vector of characters)
cell array array of indexed cells, each capable of storing an array of a
different dimension and data type
structure C-like structures, each structure having named fields
capable of storing an array of a different dimension and
data type
function handle pointer to a function
2. To see your data type, go to Workspace window and right click on the columns titles and select:
Size, Bytes, and Class if there were not selected. You will see something similar to this Figure
Type:
>> str = 'Hello World!' % character class
>> n = 2345 % double class by default
>> d = double(n) % convert n to double class however it is double or
something else
>> un = uint32(789.50) % create variable un which is 32-bit unsigned integer and
has 789.50 value
>>rn = 5678.92347 % rn variable is double
Page 6 of 14
>>c = int32(rn) % convert rn variable to 32-bit signed integer
>> y=[3 2 1 6 9;2 5 6 7 8;2 6 8 9 7] % create 3x5 double matrix
>>yi= int16(y) % convert y to 16-bit signed integer
%Note: percentage sign % is used to write a comment in MATLAB
❖ Explorer the values, sizes and class type in the Workspace window for the previous
examples
❖ Compare between the size, bytes and class of:
o y=[3 2 1 6 9;2 5 6 7 8;2 6 8 9 7], y1= int16(y), y2= int32(y), and y3= uint32(y),
o What is the difference between int32 and uint32? And comment of the outputs of int32(-
6), uint32(-6), and uint32(6),
4. Exercise 4: Plotting
1. MATLAB contains many powerful functions for easily creating plots of several different types,
such as rectilinear, logarithmic, surface, and contour plots. As a simple example, let us plot the
function y= 3 cos 2x for 0 ≤ x ≤7. We choose to use an increment of 0.01 to generate a large
number of x values in order to produce a smooth curve. The function plot (x,y) generates a plot
with the x values on the horizontal axis (the abscissa) and the y values on the vertical axis (the
ordinate).
Type:
>>x = 0:0.01:7; % 0 ≤ x ≤7
>>y = 3*cos(2*x);
>>plot(x,y)
>>xlabel(‘x’) % write label x on x-axis
>>ylabel(‘y’) % write label y on y-axis
2. You can create multiple plots on the same figure, called overlay plots, by two methods either
including another set or sets of values in the plot function or using hold on command.
Type:
>> x = 0:0.01:5;
>> y = 2*sqrt(x);
>> z = 4*sin(3*x);
>>figure % to open new figure
>>plot(x,y)
>>hold on % to hold the previous plot inside the figure and don’t replace it with the new plot
>>plot(x,z)
3. Other useful plotting functions are title and gtext. These functions place text on the plot. Both
accept text within parentheses and single quotes, as with the xlabel function. The title function
places the text at the top of the plot; the gtext function places the text at the point on the plot where
the cursor is located when you click the left mouse button.
Use the data and plot in the previous example and type:
>> title('overlay 2d x,y and x,z plots')
>> gtext('y') % place the text y at the point on the plot where you place the mouse cursor
>> gtext('z') % place the text z at the point on the plot where you place the mouse cursor
You can write all these commands in one line using comma
>> plot(x,y,x,z), xlabel('x'), title('overlay 2d x,y and x,z plots'), gtext('y'), gtext('z')
Page 7 of 14
4. MATLAB provides numerous commands for plotting graphs. The following table shows some of
the commonly used commands for plotting:
Command Description
axis Sets axis limits.
fplot Intelligent plotting of functions.
grid Displays gridlines.
plot Generates xy plot.
print Prints plot or saves plot to a file.
title Puts text at top of plot.
xlabel Adds text label to x-axis.
ylabel ylabel
axes Creates axes objects.
close Closes the current plot.
close all Closes all plots.
figure Opens a new figure window.
gtext Enables label placement by mouse.
hold Freezes current plot.
legend Legend placement by mouse.
refresh Redraws current figure window.
set Specifies properties of objects such as axes.
subplot Creates plots in sub windows.
text Places string in figure.
bar Creates bar chart.
loglog Creates log-log plot.
polar Creates polar plot.
semilogx Creates semi log plot. (logarithmic abscissa (horizontal))
semilogy Creates semi log plot. (logarithmic ordinate (vertical))
stairs Creates stairs plot.
stem Creates stem plot.
❖ Explorer the help examples for subplot, semilogx, bar and stem
Page 8 of 14
❖ Explorer the MATLAB help examples and implement “Introduction to the Live Editor” and
“Basic Matrix Operations” examples
In the MATLAB Command window, you can enter commands and data, make calculations, and print results.
You can write a script in the Command window and execute the script. That is sufficient when all one needs
is a simple calculation. However, in many cases, quite a few steps are required before the final result can be
obtained. Therefore, writing a script directly into the Command window is discouraged because it will not be
saved, and if an error is made, the entire script must be retyped. In these cases, it is more convenient to group
statements together in what is called a “computer program” or “MATLAB script”. The Script window may be
used to create, edit, and execute MATLAB scripts (programs). Scripts are then saved as M-Files. These files
have the extension .m.
▪ Steps:
2. To create new MATLAB Script on MATLAB environment, there are different options:
❖ Click on new script in Home Tab.
❖ Or type edit in the MATLAB Command Window
To open M-file script or function, type:>>edit filename.m.
Once you type:>>edit, M-File script window will be shows as follows
Page 9 of 14
3. Once the M-File is created, three tabs will appear: Editor, Publish, and View. Explore the
options in these Tabs and their functions.
Discussion:
4. All MATLAB help and some functions are saved in M-File scripts. You can explore that by
typing in the Command Window for example
>>edit pi
If you type help pi, you will find what is written in the script exclude the copyright. You can’t
modify what is written as it is read only.
❖ Explorer the M-File script of this function by typing in the Command Window>> edit
isprime
i. Read the M-file script
ii. This M-file function which requires input argument X. If you click the run button ▻ in
the editor tab, you will get error as an input argument is required to run this function. To
run this function argument, type in the Command Window
>> isprime(3)
>> isprime(13)
>> isprime(20)
Comment on the results:
1. Example 1:
❖ Use the MATLAB editor to create a new M-file: >>edit
❖ Type the following statements in the M-file:
A = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = A\b
❖ Save the file in the working directory, for example, example1.m.
❖ Run the file, either by click the run button ▻ in the editor tab or in the command line, by
typing:
>> example1
Comment on the results:
2. Example 2:
❖ Use the MATLAB editor to create a new M-file: >>edit
❖ Type the following statements in the M-file:
x = 0:pi/100:2*pi;
Page 10 of 14
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,’--',x,y2,'-',x,y3,':')
xlabel('0 \leq x \leq 2\pi')
ylabel('Cosine functions')
legend('2*cos(x)','cos(x)','0.5*cos(x)')
title('Typical example of multiple plots')
axis([0 2*pi -3 3])
❖ Save the file in the working directory, for example, example2.m.
❖ Run the file, either by click the run button ▻ in the editor tab or in the command line, by
typing:
>> example2
Comment on the results:
2. Use M-file to create a script to solve quadratic equation and returns warning message if the roots
are imaginary
❖ Type this script in new m-file
a=input('Enter a parameter:');
b=input('Enter b parameter:');
c=input('Enter c parameter:');
discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');
end
❖ Run this m-file
❖ Try different values for a, b and c and comment on results
3. Modify the if construct in the previous script to the following and comment on the difference
if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');
else
disp('Roots are real, but may be repeated')
end
Page 11 of 14
4. Modify the if construct in the previous script to the following and comment on the difference
if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');
elseif discr == 0
disp('Discriminant is zero, roots are repeated')
else
disp('Roots are real')
end
Note that the \equal to" relational operator consists of two equal signs (==) (with no space between
them), since = is reserved for the assignment operator.
% First, error-check
if quiz<0|quiz>10
grade= 'X';
else
%If here, it is valid so figure out the
% corresponding letter grade using a switch
Page 12 of 14
s
w
i
t
c
h
q
u
i
z
Page 13 of 14
case 10
grade= 'A';
case 9
grade= 'A';
case 8
grade= 'B';
case 7
grade= 'C';
case 6
grade= 'D';
otherwise
grade= 'F';
end
end
fprintf ('your grade is %s,\n ',grade)
. Exercise 9: Loops
Usually, expression is a vector of the form n:s:m. A simple example of for loop is:
Type:
>>for c=1:5
x=c*c
end
n = 5; A = eye(n);
for j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end
disp(A)
❖ In the previous script use MATLAB help to identify the function of “eye” function
while expression
statements
end
x=1
while x <= 10
x = 3*x
end
It is important to note that if the condition inside the looping is not well defined, the looping will
continue indefinitely. If this happens, we can stop the execution by pressing Ctrl+C on the
keyboard.
1. Create a function that takes a matrix of any size and returns its size.
N.B.: you will use size(matrix) function to get the size of the matrix.
2. Create a function that takes a matrix of any size and prints all the
elements in the matrix.