0% found this document useful (0 votes)
1 views

IntroductiontoMATLABforEngineeringStudents-LevelII

The document is a guide titled 'Introduction to MATLAB for Engineering Students (Level II)' published in April 2023, aimed at advanced engineering students learning MATLAB programming. It covers essential topics such as M-File scripts, functions, control flow, and debugging, with practical exercises at the end of each tutorial session. The book emphasizes hands-on learning and is not affiliated with MathWorks, the creators of MATLAB.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

IntroductiontoMATLABforEngineeringStudents-LevelII

The document is a guide titled 'Introduction to MATLAB for Engineering Students (Level II)' published in April 2023, aimed at advanced engineering students learning MATLAB programming. It covers essential topics such as M-File scripts, functions, control flow, and debugging, with practical exercises at the end of each tutorial session. The book emphasizes hands-on learning and is not affiliated with MathWorks, the creators of MATLAB.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/369850211

Introduction to MATLAB for Engineering Students (Level II)

Book · April 2023


DOI: 10.13141/RG.2.2.18426.16323

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.

The user has requested enhancement of the downloaded file.


Introduction to MATLAB for
Engineering Students – Level II
First Edition: April 2023

@ Copyright – Author Retained


All rights reserved. No part of this book may be reproduced, distributed, or transmitted in any
form without the author’s prior written permission.
Readers are kindly requested to cite this book when referencing its content in academic or
professional work.
DOI: 10.13141/RG.2.2.18426.16323
ISBN: 978-1-326-50223-2
Imprint: Lulu.com
Published and distributed via Lulu.com.

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

Table 1: Difference between scripts and functions ........................................................................ 4


Table 2: Examples of input and output arguments ........................................................................ 5
Table 3: disp and fprintf commands ............................................................................................... 6
Table 4: Relational and logical operators ..................................................................................... 10

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

1.1 Introduction to Programming in MATLAB

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.

1.2 M-File Scripts

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

Save the file, for example, Solution1. m.


After that, run the file in the command window, by typing:

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

Save the file, for example, Solution2. m.


After that, run the file in the command window, by typing “Solution2”

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.

function f = factorial(n) (1)


% FACTORIAL(N) returns the factorial of N. (2)
% Compute a factorial value. (3)
f = prod (1: n); (4)

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.

Table 1: Difference between scripts and functions

Script File Function File


Stores the variable in the MATLAB workspace, Store variables in a separate workspace
which can be shared with other scripts internal to the function

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.

Table 2: Examples of input and output arguments

function D=FtoD(F) One input and output argument

function volume=Cubevolume(l,w,h) Three input arguments and one output

function [h,d]=motion(angle,v) Two input arguments and two outputs

1.4 Input to Script Files

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:

1- To assign the values in the script file


2- To assign the values in the command prompt
3- The values are entered after executing the script file

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.

% This script file calculates the average of points


% scored in three games.
% The point from each game are assigned to a variable
% by using the ‘input’ command.
game1 = input ('Enter the points scored in the first game ');
game2 = input ('Enter the points scored in the second game ');

5
game3 = input ('Enter the points scored in the third game ');
average = (game1+game2+game3)/3

1.5 Output Commands

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.

Table 3: disp and fprintf commands

disp Simple to use


Gives limited control over the appearance of output
fprintf More complicated than disp
Gives total control over the appearance of output

This difference can be further clarified by looking at the following example.

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,

Open a new script and write the following lines:

radius=input ('Enter radius in meter\n');


Area=pi*(radius)^2;
fprintf('Area is %d squared meter\n',Area)

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:

radius=input ('Enter radius in meter\n');


Area=pi*(radius)^2;
disp(Area)

In the command window, you will get the following:

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

2.1 Introduction to Control Flow and Operators

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.

2.2 Control Flow

MATLAB has four structures of control flow: the if statement, the for loop, the while loop, and
the switch statement.

1) The “if…end” structure


MATLAB supports the construct of variant “if”.
• if ... end
• if ... else ... end
• if ... elseif ... else ... end

The simplest construct of the if statement is the following:


if expression
statements
end

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)

2) Relational and Logical Operators

Relational operators compare between two numbers and determine whether this comparison is
true or false. Table 4 lists these relational operators.

Table 4: Relational and logical 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

3) The “for…end’’ Loop


In the for ... end loop, the commands execution is repeated at a fixed and predefined number
of times. Typically, it has the following syntax,

for variable = expression


statements
end

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:

4) The “while…end’’ Loop


This loop is used when the number of passes is not determined. The execution of the loop
continues until this condition is met. This loop has the following syntax:

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:

1- Use “fopen” to open a file


2- Use “fprintf” to write the output for this file
3- Use “fclose”to close the file

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:

% write some variable length strings to a script file

op = fopen('Weekdays.txt','wt'); % wt stands for write text

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

3.1 Introduction to Debugging Process

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:

• Syntax errors: such as misspelling a function name or omitting a parenthesis

• Run-time errors: are commonly apparent and difficult to track down. They result in
unexpected outcomes

3.2 Running the Debugging Process

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:

a) Open the file


b) Save the changes
c) Make sure that the file you run and any files that are called are in the directories on the
search path

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:

• Standard breakpoint, that stops at a certain line.


• Conditional breakpoint, that stops at a certain line at specified conditions.
• An error breakpoint which stops the specified type of warning or error is produced (also NaN,
or infinite value).

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.

Figure 1: Standard breakpoint set at the breakpoint alley

iii. Running with Breakpoints and Stepping through M-File


After setting up the breakpoints, run the M-file using the Command Window or the
Debugger/Editor. You will notice that:

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

iv. Values Examination


While the program execution is paused, the value of any variable currently in the workspace can
be viewed. The values of each variable can be examined to check whether a code or line has
produced the expected output or not. In case the output is as expected, further step can be taken
to the next line, and continue the execution. If the output is not as expected, then it is confirmed
that this line, or the previous one, contains an error. When a program is run, “who” or “whos”
can be used to list the variables in the Workspace.

v. Problems Correction and Ending Debugging


While the program execution is paused, assign a new value for the variable in the Workspace
browser, Command Window, or Array Editor. Then continue the execution and stepping through
the program. After identifying the problem in the code, the debugging mode can be ended by
selecting “Exit Debug Mode” from the Debug menu. To correct errors in M-File follow these steps:

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.

[2] C. F. Van Loan. Introduction to Scientific Computing. Prentice Hall, 1997.

[3] C. B. Moler. Numerical Computing with MATLAB. Siam, 2004.

[4] S. J. Chapman. MATLAB Programming for Engineers. Thomson, 2004

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

[8] K. R. Coombes, B. R. Hunt, R. L. Lipsman, J. E. Osborn, and G. J. Stuck. Differential Equations


with MATLAB. John Wiley and Sons, 2000.
[9] D. Kahaner, C. Moler, and S. Nash. Numerical Methods and Software. Prentice-Hall, 1989.
[10] D. Houcque. Applications of MATLAB: Ordinary Differential Equations. Internal
communication, Northwestern University, pages 1–12, 2005.
[11] J. C. Polking and D. Arnold. ODE using MATLAB. Prentice Hall, 2004.
[12] J. W. Demmel. Applied Numerical Linear Algebra. Siam, 1997.
[13] M.Arshad. Numerical Methods Lab Manual, 2020
[14] Matlab Marina at Georgia Southern University. Available at:
http://www.matlabmarina.com/pdf/matlab%20marina%20debugging%20exercises.pdf#

20

View publication stats

You might also like