IntroductiontoMATLABforEngineeringStudents-LevelII
IntroductiontoMATLABforEngineeringStudents-LevelII
net/publication/369850211
CITATIONS READS
0 3,316
1 author:
Abdellatif M. Sadeq
Qatar Naval Academy
105 PUBLICATIONS 657 CITATIONS
SEE PROFILE
All content following this page was uploaded by Abdellatif M. Sadeq on 21 April 2025.
Disclaimer
This book is an independent publication and is not affiliated with, endorsed by, or sponsored by
MathWorks or MATLAB. The MATLAB logo or related imagery is used solely to acknowledge the
use of the software during a one-month free trial license provided by MathWorks for academic
purposes.
Contents
1. Tutorial Lesson 1 ...................................................................................................................... 1
1.1 Introduction to Programming in MATLAB........................................................................ 1
1.2 M-File Scripts .................................................................................................................... 1
1.3 M-File Functions ............................................................................................................... 4
1.4 Input to Script Files........................................................................................................... 5
1.5 Output Commands ........................................................................................................... 6
Exercise 1 ..................................................................................................................................... 8
2. Tutorial Lesson 2 ...................................................................................................................... 9
2.1 Introduction to Control Flow and Operators ................................................................... 9
2.2 Control Flow ..................................................................................................................... 9
2.3 Saving Output to a File ................................................................................................... 14
Exercise 2 ................................................................................................................................... 15
3. Tutorial Lesson 3 .................................................................................................................... 16
3.1 Introduction to Debugging Process ................................................................................ 16
3.2 Running the Debugging Process ..................................................................................... 16
Exercise 3 ................................................................................................................................... 19
i
List of Tables
ii
List of Figures
Figure 1: Standard breakpoint set at the breakpoint alley ......................................................... 177
Figure 2: MATLAB Program to Sum positive Elements of an Array Containing Errors ............... 179
iii
Preface
“Introduction to MATLAB for Engineering Students II” is an introductory course for MATLAB that
is given as a step by step guide for engineering students (advanced level) and those seeking to
learn programming in MATLAB. This file is not a comprehensive introduction to programming in
MATLAB such as the reference manual, however it focuses on the programming basics using
MATLAB, which is useful for engineering students in their courses. In principle, this workshop
aims to familiarize the students with the use of MATLAB software for programming and
debugging codes. Also, this workshop assumes that the students have a satisfied knowledge of
MATLAB basics. The document is designed in such a way to be used by the students while they
are working on the computer. The emphasis here is learning by doing. At the end of each tutorial
session, there will be an exercise given as a quiz, which is estimated to be solved in 30 minutes.
The availability of technical computing platforms such as MATLAB is currently reshaping the
applications and role of computer laboratory projects to get the students involved in more
intense problem-solving experience. In addition, this availability provides a chance to conduct
numerical experiments easily and to tackle complicated and more realistic problems. Basically,
the document is divided into three laboratory sessions devoted for students seeking to build the
fundamentals of programming using MATLAB software.
iv
1. Tutorial Lesson 1
So far, all the commands were executed in the command window. The commands that are
entered in this window cannot be saved and executed for many times. Thus, it is necessary to
use a platform where these commands can be written, saved, and then executed for several
times. This can be done using the script files or scripts for short. The commands written in these
scripts can be edited and then saved again. In this section, two topics are handled: M-File scripts
and M-File functions.
A script file is an external file containing a sequence of MATLAB statements. They have the file
extension name as extension .m and are usually called M-files. M-files can be scripts which
execute a series of MATLAB statements, or they can be functions which accept some arguments
and then produce one or more outputs.
Example,
Create M-file that can find a solution for the following system of equations once executed:
x + 2y+ 3z = 1
4x + 5y+ 6z = 1
7x + 8y =1
Solution,
Create a new M-file by tapping on “New Script”. After that, enter the following commands in
the file:
1
A= [1 2 3;4 5 6;7 8 0];
b= [1;1;1];
S=A\b
You will notice that when execution ends, the variables (A, b, and S) remain in the workspace.
To see a list for them, enter “whos” at the command prompt.
Example,
Plot these cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5* cos(x), in the interval
0 ≤ x ≤ 2π.
Solution,
Create a new M-file by tapping on “New Script”. After that, enter the following commands in
the file:
2
x = 0:pi/100:2*pi;
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])
3
1.3 M-File Functions
Functions are defined as programs that accept input arguments and return output arguments.
The workspace for the M-File function is separated from the MATLAB base workspace. The
following lines show the anatomy of a simple M-File function.
The first line in the anatomy introduces the keyword function. It gives the function a name and
an order of arguments. In this case of function factorial, there is one input and one output
argument. The second and third lines give a description for the function factorial and the last line
is the Program code which executes the actual computations. Both scripts and functions might
have this structure, except for the line of function definition which belongs only to functions. Like
the scripts, the M-file function will be saved with the extension “.m”. Table 1 summarizes the
main differences between the script and function files.
Do not accept input arguments Accept input arguments and return output
arguments
Useful for executing a series of commands Useful for extending the language of MATLAB
for the desired application
As mentioned earlier, the output arguments follow the word “function” and they are listed inside
brackets in the left side (in case of more than one output argument). However, the input
4
arguments are listed inside parentheses on the right side following the function name. There
could be more than one input/output arguments as the following examples in Table 2 clarify.
When executing a script file, the variable within the file must have assigned a value. The
assignment of values for these variables can be done in three ways:
The first two cases have been encountered before. Thus, the focus here on the third point. In this
case, the user is asked to enter a value for the variables after running the script file. This can be
done using the “input” command, as the following example demonstrates.
5
game3 = input ('Enter the points scored in the third game ');
average = (game1+game2+game3)/3
MATLAB displays the outputs automatically when executing commands. In addition to that, it can
give the option to display the results using different commands. Two of the most frequently used
commands to display the outputs are: “disp” and “fprintf”. The difference between these two
commands is explained in Table 3.
Example,
Write a script file that asks the user to enter the radius of the circle to find its area. Use input and
fprintf commands to display a mix of text and numbers. Recall the conversion formulation, 𝐴 =
𝜋𝑟 2
Solution,
6
Save the file with a name of your choice, for example (AreaC). After that, run the file in the
command window by writing the name of the file as the following:
Alternatively, if “disp” is used instead of “fprintf”, the area of the circle will be displayed without
a text. In the script write the following line:
7
Exercise 1
a) Create a new M-file by tapping on “New Script”, which can help the user to plot the following
set of functions: y1=3sin (x), y2=sin (x), y3=2sin (x) on the interval [0, 2π] taking π/50 as a step
size. Make sure that each function line has a unique shape or color, and the axes and legends
names are written on the chart
b) Write a function by tapping on “New function”. This function file asks the user to enter the
widths and heights of rectangle 1 and rectangle 2 to find the sum of their areas. Use input
and fprintf commands to display a mix of text and numbers. Recall the conversion
formulation, 𝐴 = 𝑤 ∗ ℎ
Additional References
• Chapter 7 of https://cepr.org/sites/default/files/40013_Intro%20to%20Matlab.pdf
• Chapter 6 of http://mayankagr.in/images/matlab_tutorial.pdf
8
2. Tutorial Lesson 2
MATLAB can be also used for programming. Like other programming languages, it has some
decision-making structures to control the execution of commands. These control flow structures
are commonly used in script M-files and function M-files, and examples for them are: “if-else-
end” and “while” loops constructions. Previously in chapter 1, the commands have been
executed one by one, however here in this chapter, the flow control structure is introduced,
which makes possible to skip commands or to execute certain group of commands.
MATLAB has four structures of control flow: the if statement, the for loop, the while loop, and
the switch statement.
9
Example: This example is given based on the familiar quadratic formula,
a=input('Enter the value of a\n');
b=input('Enter the value of b\n');
c=input('Enter the value of c\n');
discr = b*b - 4*a*c;
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
fprintf('Discriminant equals to %d \n',discr)
Relational operators compare between two numbers and determine whether this comparison is
true or false. Table 4 lists these relational operators.
Operator Description
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
∼= Not equal to
| OR operator
& AND operator
10
∼ NOT operator
It is a great idea to indent the loops for readability, more specifically when they are nested.
MATLAB editor can do it automatically. Multiple for loops could be nested, in which case
indentation assist in improving the readability. The coming statements form the 5-by-5
symmetric matrix A with (i, j) elements i/j for j ≥ i:
Example,
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)
The preceding lines have been entered in a new script file, then saved and given a name “EyeA”.
After executing the file in the command window, the following appears:
11
Example,
n = 5; A = eye(n);
for j=1:n
for i=1:n
A(i,j)=i/j;
end
end
disp(A)
The preceding lines have been entered in a new script file, then saved and given a name “EyeB”.
After executing the file in the command window, the following appears:
while expression
statements
12
end
Example,
x=2
while x <= 9
x = 3*x
end
The preceding lines have been entered in a new script file, then saved and given a name “xfile”.
After executing the file in the command window, the following appears:
It is important to notice that if the condition inside the loop is not defined well, the looping will
keep execute indefinitely. If this happens, the looping can be stopped by pressing Ctrl-C.
13
2.3 Saving Output to a File
One use for the command “fprintf” is to display the output on the screen. Another use for it, is
to write the output of a computation to a file. Thus, the saved data can be used by another
software or by MATLAB. To save the computation results in a text format using the command
“fprintf”, the followings steps must be followed:
Example,
Before writing the code in the script file, create a new text file using Notepad or MS Word, keep
it empty and save it with a certain name such as “Weekdays”. After that, write the following code
in a new script file:
fprintf(op,'Sunday\nMonday\nTuesday\nWednesday\n')
fprintf(op,'Thursday\nFriday\nSaturay\n')
fclose(op);
You will notice that the all the weekdays are written in the newly created text file.
14
Exercise 2
1) In a new script file, write a MATLA code that asks the student to enter his final grade out of
100. The code will show the student grade in letter according to the below table:
Grade ≥90 A
90 > Grade ≥ 85 B+
85 > Grade ≥ 80 B
80 > Grade ≥ 75 C+
75 > Grade ≥ 70 C
70 > Grade ≥ 60 D
Grade < 60 F
2) In a new script file, write a MATLAB code that can show the multiples of the number “5” up
to 70 using the “while” loop.
Additional References
• http://www.eecs.umich.edu/courses/engin101/Matlab/chapter_5_control_structures.pdf
• http://www.math.wsu.edu/kcooper/M300/matlabflow.php
15
3. Tutorial Lesson 3
In this section, the general techniques which are generally followed to find errors in MATLAB are
discussed. Debugging is known as the process of finding errors in the program or code, then
isolate and fix them. Two types of errors can be fixed with the help of debugging:
• Run-time errors: are commonly apparent and difficult to track down. They result in
unexpected outcomes
The errors in M-files can be debugged using the Editor/Debugger along with the debugging
functions available in the Command Window. The debugging process consists of:
i. Preparation of debugging
ii. Setting up the breakpoints
iii. Running an M-File with the breakpoints Stepping through the M-File
iv. Values Examination
v. Problems Correction and Ending Debugging
i. Preparation of debugging
Here we use the debugger/editor for debugging. The followings should be performed to prepare
for debugging:
16
ii. Setting up the Breakpoints
Set breakpoints to stop the execution of the file at certain locations and examine where the
problems might be. Three types of breakpoints exist:
Notice that breakpoints cannot be set while MATLAB is running, for example, during M-file
execution. Standard breakpoints can be set in the Editor by clicking the breakpoint alley at an
executable line where you desire to set the breakpoint. Alternatively, the breakpoint can be set
by pressing on F12. Figure 1 shows a sample for a standard breakpoint that is set on the
breakpoint alley.
• The prompt in the Command Window changes to K>> and this indicates that MATLAB in the
debug mode.
17
• The program will pause at the first breakpoint and will continue the execution after clicking
on continue. A green arrow is used to indicate for the pause.
• In breakpoints, we can step through programs, examine variables, and run other calling
functions.
a) Quit debugging mode (errors are not corrected during the debugging mode)
b) Make changes in the M-file
c) Save the M-file
d) Clear the breakpoints
e) Run the M-file again to ensure it gives the expected results
18
Exercise 3
19
Bibliography
[1] The MathWorks Inc. MATLAB 7.0 (R14SP2). The MathWorks Inc., 2005.
[5] D. J. Higham and N. J. Higham. MATLAB Guide. Siam, second edition edition, 2005
[6] J. Cooper. A MATLAB Companion for Multivariable Calculus. Academic Press, 2001.
[7] A. Gilat. MATLAB: An introduction with Applications. John Wiley and Sons, 2004.
20