Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

AIN SHAMS UNIVERSITY

FACULTY OF ENGINEERING
MECHATRONICS ENGINEERING DEPARTMENT
Credit Hours Programs
Spring Semester, 2018

MCT 456: Dynamic Modeling and Simulation


Lab. 1: MATLAB Fundamentals

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. Exercise 1: Open MATLAB and Exploring MATLAB Environment


 Steps:
1. To start MATLAB on a Microsoft Windows system, double-click on the MATLAB icon on the
Desktop or in All Programs. You will then see the default appearance of MATLAB Desktop
shown in Figure 1.1.

Figure 1.1: The default view of MATLAB desktop.

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:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

2. Exercise 2: Entering Commands and Expressions


1. Make sure the cursor is at the prompt in the Command window. For example, to divide 8 by 10,
type 8/10 and press Enter (the symbol / is the MATLAB symbol for division if you used \
symbol it will divide 10 by 8). Your entry and the MATLAB response look like the following on
the screen

>> 8/10
ans =
0.8000

Remember, the symbol >> automatically appears on the screen; you do not type it.

2. Explore what variables now in the Workspace window


3. MATLAB assigns the most recent answer to a variable called ans if it doesn’t have assigned
variable, which is an abbreviation for answer. A variable in MATLAB is a symbol used to
contain a value. You can use the variable ans for further calculations; for example, using the
MATLAB symbol for multiplication (*), we obtain

>> 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

6. Compare the results if you typed x=8\10 and y=8/10. Comment!


Comments:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

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:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

8. Commands for managing the work session


The following table summarizes some commands and special symbols used for managing the
work session.

Command/special symbol Description


… Ellipsis; continues a line.
; Semicolon; suppresses screen printing; also denotes
a new row in an array.
, Comma; separates elements of an array.
: Colon; generates an array having regularly spaced
elements.
whos Lists the current variables and sizes and indicate if
they have imaginary parts.
who Lists the variables currently in memory.
exist(‘variable_name’) Determines if a variable exists having the name
‘variable_name’
clc Clears the Command window.
clear var1 var2 Removes the variables var1 and var2 from
memory.
clear Removes all variables from memory.
quit Stops MATLAB.

Use these commands and write your comments


>> x1=[1 2 3 ...
3 4 5 ...
6 7 8]
>>x2 = [0, 4, 3, 6] % row vector
>>x3=[0 4 3 6]
>>x4 = [0; 4; 3; 6] % column vector
>>x5=[1,2,3;4,5,6;7,8,9] %Matrix
>>x6=[1 2 3;4 5 6;7 8 9] %Matrix
>>t=0:1:10

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

10. Arrow (↑) Key


You can use the smart recall feature to recall a previously typed function or variable.
 Press the up-arrow key (↑) several times and write what you find.
Discussion:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

 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

11. Tab Key


You can use the tab completion feature to reduce the amount of typing. MATLAB automatically
completes the name of a function, variable if you type few letters of the name and press the Tab
key ↹ in your keyboard. If the name is unique, it is automatically completed. For example, if you
type sq and press Tab, MATLAB displays all functions starts with sq in pop-up list. Move inside
this list using keyboard arrows and choose sqrt and press tab key ↹ again. The sqrt is used to
calculate the square root of a number.
>>sqrt(25)

12. Formatting Commands


The format command controls how numbers appear on the screen. By default, MATLAB displays
numbers with four decimal place values. This is known as short format. However, if you want
more precision, you need to use the format command. The format long command displays 16
digits after decimal.
 Type:
>> format short
>> x = 7 + 10/3 + 5 ^ 1.2
Page 4 of 14
Then Type
>>format long
>> x = 7 + 10/3 + 5 ^ 1.2
Compare the results
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

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:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

 To return the formatting to MATLAB default. Type


>>format
Use format, by itself, resets the output format to the default, which is the short, fixed-
decimal format for floating-point notation and loose line spacing for all output lines.

13. Built-in Functions


MATLAB uses hundreds or maybe thousands of the built-in functions built, such as the sqrt and
sin functions. You need to use MATLAB help search to find the suitable function for your
application. The following Table lists some of the mathematical built-in functions:
Math. Function MATLAB syntax
ex exp(x)
sqrt(x)
√𝑥
ln 𝑥 log(x)
log10 𝑥 log10(x)
cos 𝑥 cos(x)
sin 𝑥 sin(x)
tan x tan(x)
cos-1x acos(x)
-1
sin x asin(x)
-1
tan x atan(x)
 Use help command to learn how to use these functions
>>help exp
It will give you details about the function inputs and outputs in addition to suggesting other
functions. If you click on Reference page for exp, it will open MATLAB help document with
full details about the function. Explorer the other mathematical functions on the previous
table.
 Compare between the outputs of cos, cosd, acos, and acosd and identify the following
o What is the input and output arguments for each one of them? Use help command
o If you want the cosine of 60o using cos and cosd
o If you want the inverse cosine of 0.5 for both acos and acosd
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

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

user classes objects constructed from a user-defined class

java classes objects constructed from a Java class

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)

Or you can do it this way


>>figure % open new figure
>>plot(x,y,x,z), xlabel(‘x’)

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 these plotting function by using help command. For example,


>>help fplot
and then try the help examples. For example,
>> fplot(@(x) sin(x))

 Explorer the help examples for subplot, semilogx, bar and stem
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

5. Exercise 5: USE MATLAB Help System


MATLAB has a comprehensive Help system. To explore the more advanced features of MATLAB
not covered in this course, you will need to know how to use effectively the MATLAB Help System.
MATLAB has many options to get help either using MATLAB help or MathWorks website
http://www.mathworks.com/.
 Explorer the MATLAB help options using the Help pop-up list in the MATLAB HOME Tab as
shown in this figure.
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Page 8 of 14
 Explorer the MATLAB help examples and implement “Introduction to the Live Editor” and
“Basic Matrix Operations” examples
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

6. Exercise 6: Open Script file and identify its environment

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

The default view of MATLAB Script.

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 MATLAB function isprime, by typing in the Command Window>>help


isprime
i. What this function is used for?
Discussion:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
 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:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

7. Exercise 7: Writing M-file

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:
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________

8. Exercise 8: Conditional Statements

1. MATLAB supports the variants of "if" construct.


 if ... end
 if ... else ... end
 if ... elseif ... else ... end

The simplest form of the if statement is


if expression
statements
end

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
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

5. Relational and logical operators


A relational operators, which compares two numbers by determining whether a comparison is true or
false, are commonly used in conditional statements. Some relational operators are shown in the
Table

Note that the \equal to" relational operator consists of two equal signs (==) (with no space between
them), since = is reserved for the assignment operator.

6. The switch statement


A switch statement can often be used in place of a nested if-else or if statement with many elseif
clauses. Switch statements are used when an expression is tested to see whether it is equal to one of
several possible values. The general form of the switch statement is:
switch switch_expression
case case_expersion_l
action_l
case case_expersion_2
action_2
case case_expersion_3
action_3
otherwise
action_n
end
 Type this script in new m-file
% This script returns the letter grade corresponding
% to the integer quiz grade argument using switch
% Format of call: swi tchletgrade ( integerQuiz)
% Returns a character

quiz=input('quiz mark:') % input mark between 0 and 10

% 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
switch quiz
Page 12 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)

 Draw the flow chart of the previous script


 Test it on different grades and comment on the results
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

. Exercise 9: Loops

1. The ''for...end'' loop


In the for ... end loop, the execution of a command is repeated at a fixed and predetermined
number of times. The syntax is

for variable = expression


statements
end

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

 Write this script and run it

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
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

 Write this script and run it


Page 13 of 14
%Demonstrates subplot using a for loop
for n=1:3
x= linspace(0,2*pi,20*n);
y = sin(x);
subplot(1,3,n)
plot(x,y,'ko')
xlabel ('x')
ylabel ('sin (x)')
title ('sin plot')
end

 In the previous script, what is the function of subplot?


 Comment on the three plots produced in the previous plot
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

2. The ''while...end'' loop


This loop is used when the number of runs is not specified. The looping continues until a stated
condition is satisfied. The while loop has the form:

while expression
statements
end

The statements are executed as long as expression is true.

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.

 Write this script and run it

%Prompts the user for positive numbers and echo prints as


%long as the user enters positive numbers
%Counts the positive numbers entered by the user
counter=0;
inputnum=input ('Enter a positive number: ' );
while inputnum >= 0
fprintf ( 'You entered a %d. \n \n' , inputnum)
counter=counter+ 1;
inputnum= input ('Enter a positive number : ') ;
end
fprintf ( ' Thanks, you entered %d positive numbers. \n' , counter)

 Draw the flow chart of the previous script and explain it


_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________
_______________________________________________________________________________________

Page 14 of 14

You might also like