0% found this document useful (0 votes)
12 views28 pages

Chap#3_programing

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views28 pages

Chap#3_programing

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

University of M’hamed BOUGARA of Boumerdes

Institute of Electrical and Electronics Engineering


(IGEE ex-INELEC)
Department of Power and Control engineering

EE421 – Computation and Simulation using


MATLAB /Simulink
Chapter 3: Programming Essentials in MATLAB

Dr. A. AMMAR

01/20/2025 EE421 Dr. AMMAR 1


Outlines:

1. M-File editor
2. Display and Printout Operators
3. Data Files
4. The if, else, elseif, end and switch, case, end Control Statements
5. Loop Control Statements: while, for,…..etc
6. User-Defined Functions

01/20/2025 EE421 Dr. AMMAR 2


Chapter 1: Programming Essentials in MATLAB
This chapter covers the most essential and widely used programming tools,
operators, and control statements in MATLAB, it contains a number of plain
examples that demonstrate efficient ways and tools of programming and
modeling in MATLAB
1 M-File editor
The previous chapter shows general overview of M/MLX-file editors. Scripts
(M/MLX-files) can also be written in Notepad or WordPad editors. They become
M-files as soon as they are named with file extension of *.m or *.mlx extension.

Before starting to write a script, let’s look at some essential preparation steps.
These are important to know and consider before writing actual code in any
programming language. The process of writing a script/program starts with pen
and paper. It’s composed of the steps shown in the flowchart in Fig.1

01/20/2025 EE421 Dr. AMMAR 3


01/20/2025 EE421 Dr. AMMAR 4
This flowchart illustrates these steps:
1) Clarify the problem statement.
2) Clarify/create/declare the input variables, such as var1, var2,var3 ... varN.
3) Read the values var1, var2, var3, ... varN.
4) Define the output variables, such as out1, out2, out3, ... outN.
5) Perform the computation, evaluation, and analysis operations.
6) Check the quality/correctness of the obtained results/output variables.
7) If the quality/correctness of the achieved results is not adequate,
go back to Step 3. Repeat Step 3-5 until the expected quality/correctness is
attained.
8) End and report on the results.

01/20/2025 EE421 Dr. AMMAR 5


When writing a program/script, the most time-consuming part is carrying out
verification operations in Steps 3-5. This is called debugging and it helps you
locate errors or flaws in the calculation/evaluation and analysis operations from
Step 4.
Debugging is the process of correcting the syntax of the program with respect to
the programming language, correcting the calculation/computation operations with
respect to the given problem statement and, if required, adjusting the precision of
the output.

01/20/2025 EE421 Dr. AMMAR 6


1.1 How to Create an M/MLX-File
There are a few ways to create a new script (in this case, an M/MLX-file).

• By typing >> edit in the Command Window and pressing the Enter key from the
keyboard.
• By pressing Ctrl+N keys from the keyboard.
• By clicking on for an M-file.

• By clicking on and selecting from the list, script

1.1 Warnings in Scripts

While writing M/MLX-files, including the function files M-file, editors automatically
generate warning signs that are in many instances helpful hints to improve
efficiency and locate missing or overlooked arguments.

01/20/2025 EE421 Dr. AMMAR 7


1.3 Errors in Scripts

In MATLAB, scripts can contain code that performs various computations and
analyses and defines functions. Let’s look at a few simple examples of writing
scripts in the M-file editor and see how to locate and fix common errors that occur
while writing scripts. Let’s look at a few simple examples
Example 1

solve the quadratic equation represented in this general form: ax2 + bx + c = 0.

First, open an M-file editor and type in the following commands

a=input('Enter, a = ');
b=input('Enter, b = ');
c=input('Enter, c = ');
D=b^2-4*a*c;
disp(['Discriminant of the
equation is: ' num2str(D)])
Once the file is saved with the file extension *.m, it can be executed.

01/20/2025 EE421 Dr. AMMAR 8


input: Prompt for user input
disp: Display array
num2str Convert numbers to character representation

There are two more steps left in to calculate the two roots of the quadratic equation.
The remaining steps can be inserted after line 5. If illegal operations/errors
occur while writing the script, the M/MLX-file editor will automatically detect them and
underline them with red waves:

01/20/2025 EE421 Dr. AMMAR 9


Error and warning messages like these are shown on the right edge of the editor’s
scrollbar. If there is a red colored wavy line showing an error, that script cannot be
executed.
If there are any warning signs with orange wavy underlines , that script can be
executed without a problem.
Finally, after fixing the script. The green button in the right corner indicates that
the syntax is correct and the script is ready for execution

01/20/2025 EE421 Dr. AMMAR 10


2 Display and Printout Operators: disp, display, sprintf, and
fprintf

There are several commands and operators (built-in functions) that display
computation results in the Command Window or export them into external files
compatible with MATLAB. They are disp(), display(), sprint(), and
fprintf().

disp() and display() are straightforward ways to display comments, strings, or


numerical values in the Command Window without any additional formatting tools
or characters. However, They cannot write data into external files.

There is a difference in outputs from disp() and display(). The disp() command
displays outputs only without a variable name. On the other hand, display()
displays the variable name and its value as a simple calculation.

01/20/2025 EE421 Dr. AMMAR 11


Example 2
Given

Display computation results of the function f(t) with disp() and display()
Solution 2
t=[0, pi/4, pi/2, 3*pi/4, pi];
disp(['Sine of ', num2str(t(1)),' is equal to: ', num2str(sin(t(1))) ])
disp(['Sine of ', num2str(t(2)),' is equal to: ', num2str(sin(t(2))) ])
disp(['Sine of ', num2str(t(3)),' is equal to: ', num2str(sin(t(3))) ])
disp(['Sine of ', num2str(t(4)),' is equal to: ', num2str(sin(t(4))) ])
disp(['Sine of ', num2str(t(5)),' is equal to: ', num2str(sin(t(5))) ])
01/20/2025 EE421 Dr. AMMAR 12
On the other hand, sprint() and fprintf() can substitute all functions of
disp() and display(). They can be used to print various data types in the
Command Window, by using formatting operators and characters. Moreover, they
can print textual and numerical data into external files.

The fprintf function displays one or more values together with related text, and
lets the programmer control the way that the displayed value appears. The general
form of this function when it is used to print to the Command Window is:
fprintf(format,data)

01/20/2025 EE421 Dr. AMMAR 13


where format is a string describing the way the data is to be printed and data
is one or more scalars or arrays to be printed. The format is a character string
containing text to be printed plus special characters describing the format of the
data.
For example, the function
fprintf('The value of pi is %f \n',pi)

will print out 'The value of pi is 3.141593'

The characters %f are called conversion characters; they indicate that a value in
the data list should be printed out in floating-point format at that location in the
format string. The characters \n are escape characters; they indicate that a line
feed should be issued so that the following text starts on a new line.

sprintf is the same as fprintf except that it returns the data in a MATLAB
variable rather than writing to a file.

01/20/2025 EE421 Dr. AMMAR 14


Table 1 lists the conversion characters and Table 2 lists the escape characters
used to specify non-printing characters.1

01/20/2025 EE421 Dr. AMMAR 15


3. Data Files

There are many ways to load and save data files in MATLAB, For the moment, we
will consider only the load and save commands, which are the simplest ones to
use.

The save command saves data from the current MATLAB workspace into a
disk file. The most common form of this command is
save filename var1 var2 var3

where filename is the namsacde of the file where the variables are saved, and
var1, var2, and so forth are the variables to be saved in the file. By default, the
filename will be given the extension “mat”,

MATLAB saves MAT-files in a special compact format which preserves many


details, including the name and type of each variable, the size of each array, and all
data values.
01/20/2025 EE421 Dr. AMMAR 16
The load command is the opposite of the save command. It loads data from
a disk file into the current MATLAB workspace. The most common form of this
command is:
load filename

where filename is the name of the file to be loaded. If the file is a MAT-file, then
all of the variables in the file will be restored, with the names and types the same
as before. If a list of variables is included in the command, then only those
variables will be restored.

01/20/2025 EE421 Dr. AMMAR 17


4 Logical Expressions

A logical expression is one that evaluates to either true or false. They may contain
numerical, logical and relational operations. Numerical operations involve numbers
and their result is a number. Relational operators compare two numbers and
their result is true or false. Finally, logical operations connect two logical variables.
The result is again, true or false.

Table shows the most often used relational and logical operations as well as their
MATLAB syntax.

01/20/2025 EE421 Dr. AMMAR 18


4. The if, else, elseif, end and switch, case, end Control Statements
The control statements if ... elseif... else ... end are also called
conditional statements. They are employed to logically select which block of the
code is to be executed while running the whole script according to the given
information. The general structure of these control statements follows:

This indicates that if logical statement A is true, then X operations will be


executed. If logical statement B is true, Y operations will be executed. If none
of the logical statements is true, W operations will be executed.

01/20/2025 EE421 Dr. AMMAR 19


MATLAB supports the variants of “if" construct.

if ... End
if ... else ... end
if ... elseif ... else ... end

It should be noted that:


• elseif has no space between else and if (one word)
• no semicolon (;) is needed at the end of lines containing if, else, end
• the end statement is required

A relational operator compares two numbers by determining whether a


comparison is true or false. Relational operators are shown in Table 3.

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

01/20/2025 EE421 Dr. AMMAR 20


Example:
Use an if-else statement to define a function for the following piecewise function:

function f = example(x)
if x > 3
f = 2*x - 5;
else
f = x^2 - 8;
end

01/20/2025 EE421 Dr. AMMAR 21


4.1 Switch/case

The switch command is an alternative to using nested statements or if-else-


elseif statements in some cases. Switch tests against the equality of an
expression against certain value(s). Switch statements work best against a
discrete set of values, while in the case of the piecewise function example with
inequalities, one would still need an if-statement.
Example:
z = input('Enter an integer: ');
switch mod(z,2)
case 0
disp('you entered an even integer')
case 1
disp('you entered an odd integer')
otherwise
disp('you did not enter an integer')
end

01/20/2025 EE421 Dr. AMMAR 22


5. Loop Control Statements: while, for,…..etc
5.1 The ‘‘for...end’’ loop
The for statement instructs the computer to perform all subsequent expressions up
to the end statement for a specified number of counted times.
The syntax is:

Usually, expression is a vector of the form i:s:j. A simple example of for loop is

5.2 The ‘‘while...end’’ loop

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

01/20/2025 EE421 Dr. AMMAR 23


5. 3 Other flow structures

The break statement. A while loop can be terminated with the break statement,
which passes control to the first statement after the corresponding end. The break
statement can also be used to exit a for loop.

If a break statement is executed in the body of a loop, the execution of the body will
stop and control will be transferred to the first executable statement after the loop. An
example of the break statement in a for loop is as follows:
for ii = 1:5
if ii == 3
break;
end
fprintf('ii = %d\n',ii);
end
disp(['End of loop!']);

01/20/2025 EE421 Dr. AMMAR 24


The continue statement can also be used to exit a for loop to pass immediately to
the next iteration of the loop, skipping the remaining statements in the loop

If a continue statement is executed in the body of a loop, the execution of the current
pass through the loop will stop and control will return to the top of the loop. The
controlling variable in the for loop will take on its next value, and the loop will be
executed again. An example of the continue statement in a for loop is as follows:

for ii = 1:5
if ii == 3
continue;
end
fprintf('ii = %d\n',ii);
end
disp(['End of loop!']);

01/20/2025 EE421 Dr. AMMAR 25


6. User-Defined Functions

Another type of M-file is a function file. Unlike a script file, all the variables in a
function file are local variables, which means their values are available only within
the function. Function files are useful when you need to repeat a set of commands
several times. They are the building blocks of larger programs.
To create a function file, open the Editor as described previously.

The first line in a function file must begin with a function definition line that has a list of
inputs and outputs. This line distinguishes a function M-file from a script M-file. Its
syntax is as follows:

function [output arguments] = function_name(input arguments)


The output arguments are those variables whose values are computed by the
function, using the given values of the input arguments.

01/20/2025 EE421 Dr. AMMAR 26


Note that the output arguments are enclosed in square brackets (which are optional
if there is only one output), while the input arguments must be enclosed with
parentheses. The function_name should be the same as the file name in which it
is saved (with the .m extension)

Functions operate on variables within their own workspace (called local variables),
which is separate from the workspace you access at the MATLAB command prompt.
Consider the following user-defined function fun

function z = fun(x,y)
u = 3*x;
z = u + 6*y.^2;
end

01/20/2025 EE421 Dr. AMMAR 27


A function may have more than one output. These are enclosed in square
brackets. For example, the following function circle computes the area A and
circumference C of a circle, given its radius as an input argument.

function [A, C] = circle(r)


A = pi*r.^2;
C = 2*pi*r;
end
Global Variables

The global command declares certain variables global, and therefore their values
are available to the basic workspace and to other functions that declare these
variables global. The syntax to declare the variables A, X, and Q is global A X Q.
Use a space, not a comma, to separate the variables.

01/20/2025 EE421 Dr. AMMAR 28

You might also like