Chap#3_programing
Chap#3_programing
Dr. A. AMMAR
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
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
• 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.
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.
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
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.
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:
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().
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.
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)
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.
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”,
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.
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.
if ... End
if ... else ... end
if ... elseif ... else ... 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.
function f = example(x)
if x > 3
f = 2*x - 5;
else
f = x^2 - 8;
end
Usually, expression is a vector of the form i:s:j. A simple example of for loop is
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:
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!']);
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!']);
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:
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
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.