You are on page 1of 24

MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬

‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

1. Introduction

MATLAB® is a software program for numeric computation, data analysis, and


graphics. One advantage that MATLAB has for engineers over programming
languages such as C or C++ is that the MATLAB program includes functions that
numerically solve

You can think of MATLAB as a sort of graphing calculator on steroids – it is


designed to help you manipulate very large sets of numbers quickly and with
minimal programming. MATLAB is particularly good at doing matrix operations
(The system name is derived from the phrase Matrix Laboratory (MATLAB)). It is
capable of doing symbolic computations. It also enables the use of excellent
capabilities in the field of graphics, images and documents.

MATLAB code can be integrated with other languages, enabling you to


deploy algorithms and applications within web, enterprise, and production systems.
This lead to made to Millions of engineers and scientists worldwide use MATLAB®
to analyze and design the systems and products transforming our world.

2. Uses of the program MATLAB


➢ This program is used for drawing 2D graphs and in solving difficult
mathematical equations.
➢ It allows to computationally manipulate matrices, graph mathematical
functions, implement various algorithms, create graphical user interfaces,
and communicate with programs written in other languages,including C - C
++, Java, And Fortran.
➢ The program is used with many other applications and utilities such as
(Simulink).
➢ MATLAB allows drawing three-dimensional shapes after writing their
mathematical equations in a specific window.

1
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

3. Basic MATLAB windows

Install and start MATLAB. You should see the GUI shown below. The various
windows may be positioned differently on your version of MATLAB – they are
‘drag and drop’ windows. You may also see a slightly different looking GUI if you
are using an older version of MATLAB.

To enter MATLAB windows, double-click on the MATLAB shortcut icon


(MATLAB) on your Windows desktop. Waiting a while, then you a special window
called the MATLAB desktop appears. When you start MATLAB, the desktop
appears in its default layout. This window contains other windows. They are:

• The Command Window


• The Command History
• The Workspace Window
• The Current Directory
• The File Editor Window
• The Figure Window

2
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

4. The Desktop Layout

➢ The MATLAB Command Window is the main window where you type
commands directly and execute.
➢ The Command History Window displays a log of statements that you ran in
the current and previous MATLAB sessions.
➢ The Workspace Window contains variables that you create or import into
MATLAB. The workspace shows the name of each variable, its value, its
array size. Workspace variables do not persist after you exit MATLAB.
➢ The MATLAB Editor Window is a simple text editor where you can load,
edit and save complete MATLAB programs.
➢ The Current Folder Window is a reference location that MATLAB uses to
find files.

3
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

➢ The Figure Window that floats independently from the main desktop. It is
not already present, it is launched when command execution results in
graphical output

4-1 The Command Window

➢ The Command window is where the command line prompt for interactive
commands is located.
➢ The MATLAB prompt on the command window consists of two adjacent
right angle brackets, i.e., >>.
➢ Command Window: In the 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. However, 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. By using the up arrow
(↑) key on your keyboard, the previous command can be retrieved (and
edited) for re-execution.
➢ Results of command operations will also be displayed in this window unless
the command line is terminated by a semi-colon, in which case the display
of results is suppressed.
➢ If a command or script specified on the command line is questionable or
cannot be executed because of invalid syntax, undefined variables, etc., a
diagnostic message will be displayed in the Command window in red font.
➢ The current value of any saved variable is also displayed in this window if its
name is entered at a prompt.

4
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Figure: The Matlab Command Window

4-2 The Command History

➢ The Command History Window displays a log of statements that you ran in
the current and previous MATLAB sessions
➢ The commands appear in command history will not deleted unit you delete
them. To delete command history contents, enter the command history
window and select all commands with Ctrl+A and push delete button.
➢ >> clc

The “clc” command removes everything from the Command Window

5
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

4-3 The Workspace Window

➢ A workspace is the collection of all the variables and arrays that are defined
within the command window.
➢ This window is also called the Workspace Browser.
➢ The Workspace Window contains variables that you create or import into
MATLAB.
➢ The workspace shows the name of each variable, its value, its array size.
➢ Workspace variables do not persist after you exit MATLAB.
➢ To clear workspace window , use clear command to delete a variable

6
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Managing the workspace

The contents of the workspace persist between the executions of separate commands.
Therefore, it is possible for the results of one problem to have an effect on the next
one. To avoid this possibility, it is a good idea to issue a clear command at the start
of each new independent calculation.

>>clear
The command clear or clear all removes all variables from the workspace. This frees
up system memory.

In order to display a list of the variables currently in the memory, type


>>who
while, whos will give more details which include size, space allocation, and class
of the variables.

7
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

4-4 The Current Directory

➢ Also called the current folder.


➢ It shows all the files in the selected folder.
➢ The Current Folder Window is a reference location that MATLAB uses to
find files.
➢ It allows the user to manipulate files interactively.

8
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

4-5 The Figure Window

➢ The figure window is used to display graphics.


A figure can be a two- or three-dimensional plot of data.
➢ When figures are created a new window automatically opens.
➢ The Figure Window that floats independently from the main desktop.
➢ It is not already present, it is launched when command execution results in
graphical output

4-6 The File Editor Window

• The MATLAB Editor Window is a simple text editor where you can load,
edit and save complete MATLAB programs.
• It is also called Edit/Debug Window.
• An Editor Window is created when you create a new M-file or open an
existing one.
• There are several ways to open an editor window:

Click the New Script icon

9
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Click the New icon and then select Script

4-7 M – files

An m-file, or script file, is a simple text file where you can place MATLAB
commands. When the file is run, MATLAB reads the commands and executes
them exactly as it would if you had typed each command sequentially at the
MATLAB prompt. A new m-file can be created by selecting

Home tab -----> New script

or :

click on the New button from the toolbar. This opens up a floating editing window
(Blank m-file ) into which a sequence of commands can be entered.

10
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

 In summary the former MATLAB desktop (Figure 2) which, by default, is


divided into 4 windows:

1-Command Window: This is the main window, and contains the command

prompt (»). This is where you will type all commands.

2- Command History: Displays a list of previously typed commands. The

command history persists across multiple sessions and commands can be

dragged into the Command Window and edited, or double-clicked to run

them again.

11
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

3. Workspace: Lists all the variables you have generated in the current

session. It shows the type and size of variables, and can be used to

quickly plot, or inspect the values of variables.

4. Current Directory: Shows the files and folders in the current directory.

The path to the current directory is listed near the top of the MATLAB

desktop. By default, a MATLAB folder is created in your home directory

on your M:drive, and this is where you should save your work

As you work in MATLAB, you issue commands that create variables and call
functions. For example, create a variable named a by typing this statement at the
command line:

a=1

MATLAB adds variable a to the workspace and displays the result in the Command
Window.

a=

Create a few more variables.

b=2

b=

c=a+b

c=

12
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

d = cos(a)

d=

0.5403

When you do not specify an output variable, MATLAB uses the variable ans, short
for answer, to store the results of your calculation.

sin(a)

ans =

0.8415

Notes:

• A semicolon " ; " at the end of a MATLAB statement suppresses printing of


results.

• If a statement does not fit on one line, use " . . . ", followed by Enter to indicate
that the statement continues on the next line. For example:

>> S= sqrt (225)*30 /...

(20*sqrt (100)

• If we don’t specify an output variable, MATLAB uses the variable ans (short for

answer), to store the last results of a calculation.

• Use Up arrow and Down arrow to edit previous commands you entered in

Command Window.

• Insert " % " before the statement that you want to use it as comment; the
statement will appear in green color.

13
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

•it is possible to enter multiple statements per line. Use commas (,) or semicolons (;)
to enter more than one statement at once. Commas (,) allow multiple statements per
line without suppressing output.

>> a=7; b=cos(a), c=cosh(a)

b = 0.6570

c = 548.3170

•When the symbol % (percent) is typed at the beginning of a line, the line is
designated as a comment. This means that when the Enter key is pressed the line is
not executed.

Rules About Variable Names

There are a set of rules that must be followed in choosing the names of variables,
which are:

1. Must begin with a letter.


2. Can be up to 63 characters long.
3. Can contain letters, digits, and the underscore character ,the symbol ( _ ) can
be used to connect two words.
4. Cannot contain punctuation characters (e.g., period, comma, semicolon).
5. MATLAB is case sensitive: it distinguishes between uppercase and lowercase
letters. For example, AA, Aa, aA, and aa are the names of four different
variables.
6. No spaces are allowed between characters (use the underscore where a space
is desired).
7. Avoid using the name of a built-in function for a variable (i.e., avoid using
cos, sin, exp, sqrt, etc.). Once a function name is used to define a variable,
the function cannot be used.
8. Constants and variables can be assigned values using the assignment operator,
a single equal character ( = ), e.g., a = 3
14
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Keywords

There are 20 words, called keywords, cannot be used as variable names:

 When typed, these words appear in blue.


 An error message is displayed if the user tries to use a keyword as a variable
name.
 The keywords can be displayed by typing the command iskeyword. This
command causes MATLAB to list all reserved names.

>> iskeyword

ans = 'break'

'case'

'catch'

'classdef'

…….

Note: You cannot assign these reserved names as your variable names.
Note: MATLAB allows you to reassign built-in function names as variable
names, but that is not recommended! – so be carefully when you select
the name of your variables

>>sin=4
sin =
4

15
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

>>sin(3)
??? Index exceeds the number of array elements (1).

'sin' appears to be both a function and a variable. If this is unintentional, use 'clear
sin' to remove the variable 'sin' from the workspace.

In the above example you have defined a variable “sin” – but “sin” is also a
built-in function – and this function will no longer work! If you accidently do so,
use the clear command to reset it back to normal

Example:

Note: All MATLAB commands are written in lowercase letters, such as:

( if,while,for,…)

You can recall previous commands by pressing the up- and down-arrow keys,
↑ and ↓. Press the arrow keys either at an empty command line or after you type the
first few characters of a command. For example, to recall the command b = 2, type
b, and then press the up-arrow key.

Note: Once you have assigned a value to a variable, MATLAB remembers and save
it in workspace windows. To remove a value from a variable you can use the ‘clear’
statement

>>clear a

>>a

If you type ‘clear’ and omit the variable, then everything gets cleared. it is useful
when you want to start a fresh calculation.

16
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Predefined Variables

Notice that:

• If you do put a semicolon, the operation will be completed but MATLAB will
not print the result. This can be useful when you want to do a sequence of
calculations.
• Special numbers, like `pi’ can use in MATLAB directly.
• The Command History window keeps track of everything you have typed.
You can double left click on a line in the Command history window to repeat
it, or right click it to see a list of other options.
• If you screw up early on in a sequence of calculations, there is no quick way
to fix your error, other than to type in the sequence of commands again. You
can use the ‘up arrow’ key to scroll back through a sequence of commands.
Again, there is a better way to use MATLAB that gets around this problem.
• You can right click the command window and delete everything (but this will
not reset variables). You can also delete lines from the Command history, by
right clicking the line and selecting Delete Selection. Or you can delete the
entire Command History.
• You can get help on MATLAB functions by highlighting the function, then
right clicking the line and selecting Help on Selection.

17
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Rule on File names

• command files should be named with a suffix of ".m",


• An m-file typically contains a sequence of MATLAB
• commands that will be executed in order
• A file may contain a collection of commands, functions
• A file may also be just data (strings, numbers

5. MATLAB help

Help is available through the online manual – Click on the question-mark in the strip
near the top right of the window).

By default the help window opens inside the MATLAB GUI, but you can drag it out
so it occupies a new window on your desktop.

If you already know the name of the MATLAB function you want to use the
help manual is quite good – you can just enter the name of the function in the search,
and a page with a good number of examples usually comes up. It is more challenging
to find out how to do something, but most of the functions you need can be found
by clicking on the MATLAB link on the main page and then following the menus
that come up on subsequent pages.

18
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

6. MATLAB Operators

Basic MATLAB operators for computation includes symbols that distinguish


between operations on elements within matrices and between matrices as a whole.
The following notations contain a comprehensive listing of all MATLAB operators,
symbols, and special characters. are as follows:

A-Arithmetic Operators

Symbol Role
+ Addition
- Subtraction
.* Element-wise multiplication
* Matrix multiplication
./ Element-wise right division
/ Matrix right division
.\ Element-wise left division
\ Matrix left division
(also known as backslash)
.^ Element-wise power
^ Matrix power

19
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Table 1.1. Scalar arithmetic operations

Mathematical expressions are evaluated starting from the left, with the
exponentiation operation having the highest order of precedence, followed by
multiplication and division with equal precedence, followed by addition and
subtraction with equal precedence. Parentheses can be used to alter this order. the
order in which the arithmetic operations are evaluated is given in Table 1.2.
MATLAB arithmetic operators obey the same precedence rules as those in most
computer programs.

Table 1.2 Order of arithmetic operations Precedence

Precedence Mathematical operations

First ( ) ,The contents of all parentheses are evaluated first, starting


from the innermost parentheses and working outward.
Second Exponentiation (power) ^ , evaluated from left to right.

Third Multiplication * and division / with equal precedence,


evaluated from left to right.

Fourth Addition + and subtraction - with equal precedence, evaluated


from left to right

20
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

In summary:

The MATLAB language performs basic math operations +, -, *, /, ^ in addition to


using parentheses. The system works on the basis of the following priority in the
sequence of calculations:

1-Perform operations inside the brackets.


2- Implementing powers at the beginning >> 2 + 3 ^ 2 ----------- 2 + 9 = 11
3- Multiplication and division: from left to right >> 3 * 4/5 = 12/5 ---------- 2.4
4- Addition and subtraction: from left to right >> 3 + 4-5 = 7-5 ----------- 5

Examples:

>> 10\5 >> 10/5 >> 3^2


ans = ans = ans =
0.5000 2 9

>> 1/0

Warning: Divide by zero.

ans = Inf

Another special value is NaN, which stands for not a number. NaN is used to
express an undefined value. For

example.

>> Inf/Inf

ans = NaN

21
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

B-Relational, Logical & Boolean Operators


The MATLAB relational & logical operators are the following symbols:

Relational Operators

Symbol Role
== Equal to(for logical equality)
~= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

Logical Operators

Symbol Role More Information


& Find logical AND and
| Find logical OR or
&& Find logical AND (with short-circuiting) Logical Operators:
|| Find logical OR (with short-circuiting) Short-Circuit && ||
~ Find logical NOT not
Note: 1 for true , 0 for false.

22
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

7. MATLAB as a calculator

Note1:

Using , or ; between statements

x=-13, y=5*x, z=x^2+y

x=-13; y=5*x, z=x^2+y

x=-13; y=5*x; z=x^2+y

Examples for use MATLAB like a calculator without specifying


variables.

>> 2+3

ans= 5

>> 5ˆ3

ans= 125

>>2.5^2

ans = 6.2500

>> 3*(23+14.7-4/6)/3.5

ans= 31.7429

>> 1/0

Warning: Divide by zero.

ans = Inf

23
MATLAB 2024- 2023 ‫الجامعة التكنولوجية‬
‫المرحلة الثانية‬ ‫قسم هندسة النفط والغاز‬

Another special value is NaN, which stands for not a number. NaN is used to express
an undefined value. For

example.

>> Inf/Inf

ans = NaN

Note: To close MATLAB by selecting Exit MATLAB from the File menu in the
MATLAB desktop window or by typing the Exit command in the Command
window, or in the desktop corner (×) the upper-right MATLAB sign.

Note: Here are few additional useful commands:


▪ To abort a MATLAB computation, type ctrl-c
▪ To continue a line, type . . .

MATLAB Exercises

EX1:
Find the value of y:

Y=x^2+2^x+8 where x = 7/pi


EX2:
Find the value of f :

Where x = 18 y =7 z= 3.5

24

You might also like