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

112CCE Graphical Programming Lab Manual

Uploaded by

ayyash187
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

112CCE Graphical Programming Lab Manual

Uploaded by

ayyash187
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 300

Graphical Programming

King Khalid University


112CCE College of Computer Science
Department of Computer Engineering

LABORATORY MANUAL

112CCE - 1
Graphical Programming Lab

Student Information
Name: ___________________________________________________________________________________

ID Number: ________________________ Serial Number: _____ Group Number: ___________

1442-1443
112CCE: Graphical Programming KKU-CS-CE

Syllabus and Course Outline


Week Experiment
Name of the experiment Date
Number Number
1 Start of classes and Manual Registration
2 Chapter 1 Starting with MATLAB
3 Chapter 1 Starting with MATLAB
4 Chapter 2 Vectors and Arrays
5 Chapter 2 Vectors and Arrays
6 Chapter 3 Mathematical Operation with Arrays
7 Chapter 3 Mathematical Operation with Arrays
8 Chapter 4 Two Dimensional Plots
9 Chapter 4 Two Dimensional Plots
10 Chapter 5 Programming in MATLAB
11 Chapter 5 Programming in MATLAB
12 Chapter 6 Three Dimensional Plots
13 Chapter 6 Three Dimensional Plots
14 Chapter 7 Graphical User Interface
15 Chapter 7 Graphical User Interface
16 Final Exam

Grades:
 Lab Activity 15 marks
 Home Work 15 marks
 Mid-1 Exam 10 marks
 Mid-2 Exam 10 marks
 Final Exam 50 marks

Lab Policy:
 Attendance is Mandatory.
 Copies in labs will get a grade of ZERO.
 Lab reports/activities are due on the same lab session. LATE lab reports will have a 20% penalty, if they are
given within one week of the due date.

© Computer Engineering Dept. – Mohammed Rahmathullah Page 2


112CCE: Graphical Programming KKU-CS-CE

Academic Calendar Year

© Computer Engineering Dept. – Mohammed Rahmathullah Page 3


112CCE: Graphical Programming KKU-CS-CE

Computer Engineering Lab Rules and Policies


GENERAL LABORATORY SAFETY POLICY
The University of King Khalid University (KKU) is committed to providing a safe
learning and working environment for its students, staff and faculty.
The University of King Khalid University (KKU) and College of Computer Science
require all students, visitors, staff and faculty to obey all Laboratory Safety Rules when
present in all Computer Engineering laboratories at all times.

GENERAL LABORATORY SAFETY RULES


Food, drinks (water, coffee, tea,….), substances and related utensils shall not be brought
into, stored or consumed in any laboratory.
Smoking is prohibited in all laboratories at all times.
Avoid all horseplay in the laboratory.
Do not reboot, turn off, or move any workstation or PC.
Do not load any software on any lab computer. Only lab operators and technical support
personnel are authorized to carry out these tasks.
Do not reconfigure the cabling/equipment without prior permission.
Do not leave a workstation or a login unattended.
Do not leave processes in the background without prior approval from the Systems
Manager.
Unauthorized users are not permitted in the computer labs. The departmental computer
resources are to be used to support the instructional and research activities of the
Computer Engineering (CE) Department. Abuse of these resources or conduct not in
accord with University policy shall not be tolerated.
Games may not be played on Computer lab systems or servers or cell phone,……. Etc.
Footwear shall be serviceable, provide full coverage of the feet and have non-skid soles;
All occupants shall be familiar with the locations and operation of safety and emergency
equipment, including but not limited to, fire extinguishers, first aid kits, emergency
eyewash stations and emergency showers, emergency power off system, fire alarm pull
stations, emergency telephones, and emergency exits and egress plans.
Learn and know what to do in an emergency.
Unauthorized person(s) shall not be allowed in a laboratory for any reason.
"Authorized" means having an official university business in the laboratory with the
permission of the College of Engineering. Anyone under the age of eighteen must be
under the immediate and direct supervision of a qualified authorized person at all times.
Laboratories shall be secured when unoccupied.

© Computer Engineering Dept. – Mohammed Rahmathullah Page 4


112CCE: Graphical Programming KKU-CS-CE
Never open (remove cover) of any equipment in the laboratories. Never "jump,"
disable, bypass or otherwise disengage any safety device or feature of any equipment in
the laboratories.
All safety instructions, warnings, posted signs, verbal orders shall be complied with by
all personnel.
Report all problems and potential hazards in the Laboratories and Technical Support
Unit (LTS U) room 13 /3/A -Computer Science Bldg-A.
In case of emergency, dial 998.

Electrical Safety Guidelines


Be familiar with the electrical hazards associated with your workplace.
You may enter the laboratory, only when authorized to do so and only
during authorized hours of operation.
Be as careful for the safety of others as for yourself. Think before you act. Be tidy and
systematic.
Remove metal bracelets, rings or watch straps when working in the laboratories.
Food, drinks (water, coffee, tea,….), and other substances are strictly prohibited in the
laboratory at all times. Avoid working with wet hands and clothing.
Use extension cords (wires) only when necessary and only on a temporary basis.
Request new outlets if your work requires equipment in an area without an outlet.
Discard damaged cords(wires), cords that become hot, or cords with exposed wiring.
Before equipment is energized ensure, (1) circuit connections and layout have been
checked by a Teaching Assistant (TA) or Lecturer and all colleagues in your group give
their assent.
Know the correct handling, storage and disposal procedures for batteries, cells,
capacitors, inductors and other high energy-storage devices.
Experiments left unattended should be isolated from the power supplies. If for a special
reason, it must be left on, a barrier and a warning notice are required.
Equipment found to be faulty in any way should be reported to the LTSU immediately
and taken out of service until inspected and declared safe.
Voltages above 50V RMS AC and 120V DC are always dangerous. Extra precautions
should be considered as voltage levels are increased.
Never make any changes to circuits or mechanical layout without first isolating the
circuit by switching off and removing connections to power supplies.
Every lab is equipped with and Emergency Power Off System. This consists of a large
switch on the wall labeled 'Emergency Power Off'. When this switch is
depressed, electrical power to the lab will shut off, except for the lights. Only authorized
personnel are permitted to reset power once the Emergency Power Off system has been
engaged.

© Computer Engineering Dept. – Mohammed Rahmathullah Page 5


112CCE: Graphical Programming KKU-CS-CE

Electrical Emergency Response


The following instructions provide guidelines for handling two types of electrical emergencies:
1. Electric Shock:
When someone suffers a serious electrical shock, he or she may be knocked unconscious. If the
victim is still in contact with the electrical current, immediately turn off the electrical power
source. If you cannot disconnect the power source, depress the Emergency Power Off switch.
IMPORTANT:
Do not touch a victim that is still in contact with a live power source; you could be electrocuted.
Have someone call for emergency medical assistance immediately. Administer first-aid, as
appropriate.
2. Electrical Fire:
If an electrical fire occurs, try to disconnect the electrical power source, if possible. If the fire is
small and you are not in immediate danger; and you have been properly trained in fighting fires,
use the correct type of fire extinguisher to extinguish the fire. When in doubt, push in the
Emergency Power Off button.
DANGER: NEVER use water to extinguish an electrical fire.
The above general laboratory safety rules are designed to safeguard you and your co-workers, fellow
students and colleagues and are a minimum requirement for individuals working in laboratories at the
King Khalid University, Abha. Specialized training and rules may apply depending type and scope of
activities involved.
-------------------------------------------------------------------------------------------------------------------------------------
I have read and understand these rules and procedures, I agree to abide by these rules
and procedures at all times while using these facilities, I understand that failure to
follow these rules will result in disciplinary action may be taken.
Student Name: -------------------------------------------------------------------------- Student ID: --------------------------
Lab #: - -------------------- Date: - ------------------------------ Signature: - ------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------

© Computer Engineering Dept. – Mohammed Rahmathullah Page 6


112CCE: Graphical Programming KKU-CS-CE

CONTENTS
S. No. Chapter Name Page No
1. Starting with MATLAB 8

2. Vectors and Arrays 62

3. Mathematical Operation with Arrays 101

4. Two Dimensional Plots 149

5. Programming in MATLAB 185

6. Three Dimensional Plots 248

7. Graphical User Interface 277

© Computer Engineering Dept. – Mohammed Rahmathullah Page 7


Chapter No.
King Khalid University
College of Computer Science
Department of Computer Engineering
1

Graphical Programming
112-CPE-1
Starting with MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Eng. Abdelmoty M. Ahmed


CHAPTER -1 TEXTBOOKS

PAGES TO STUDY:
PAGE:3 TO PAGE:35

PAGES TO STUDY:
PAGE:5 TO PAGE:33
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Introduction
 MATLAB is a powerful language for technical computing.
 The name MATLAB stands for MATrix LABoratory, because its basic
data element is a matrix (array).
 MATLAB can be used for math computations, modeling and simulations,
data analysis and processing, visualization and graphics, and algorithm
development.
 MATLAB is widely used in universities and colleges in introductory and
advanced courses in mathematics, science, and especially engineering.

 In industry the software is used in research, development, and design.


 The standard MATLAB program has tools (functions) that can be used
to solve common problems.
 In addition, MATLAB has optional toolboxes that are collections of
specialized programs designed to solve specific types of problems.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

MATLAB: An Introduction with Applications is intended for students who are using MATLAB for the first time and
have little or no experience in computer programming.

History of MATLAB:
 Moler, the chairman of the computer science department at the University of New Mexico, started developing MATLAB
in the late 1970s.
 In the 1980’s, MATLAB was rewritten in C with more functionality (such as plotting routines)
 The Mathworks, Inc. was created in 1984.
 The Mathworks is now responsible for development, sale, and support for MATLAB.
 R2017a

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Strengths of MATLAB
 MATLAB is relatively easy to learn.
 MATLAB code is optimized to be relatively quick when performing matrix operations.
 MATLAB may behave like a calculator or as a programming language.
 MATLAB is interpreted, errors are easier to fix.

Weaknesses of MATLAB
 MATLAB is NOT a general purpose programming language
 MATLAB is an interpreted language (making it for the most part slower than a compiled language
such as C++)
 MATLAB is designed for scientific computation and is not suitable for some things (such as parsing
text- to analyze (a string of characters) in order to associate groups of characters with the syntactic units
of the underlying grammar)
Graphical Programming-CPE112-1 Lecture 1
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Chapter l Starting with MATLAB


Icons
 Window Action icon – the icon showing a down arrow with a
circle around it, i.e., It is in the upper, right corner of most
MATLAB windows
 Help icon – the question-mark icon ( ) in the Resources
Section of the desktop toolbar
 Layout icon – ( ) in the Environment Section of the desktop
toolbar
Graphical Programming-CPE112-1 Lecture 1
King Khalid University
Faculty of Computer Science
Computer Engineering Department

This chapter describes:


 MATLAB windows
 Command Window in detail
 How to do basic arithmetic
 Create basic variables
 Introductory script files

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

• 1.1 Starting MATLAB, MATLAB Windows

Workspace
Window
Current Folder Window

Store all
Variables

Command
History
Window

Command Window
Graphical Programming-CPE112-1 Lecture 1
King Khalid University
Faculty of Computer Science
Computer Engineering Department

• 1.1 Starting MATLAB, MATLAB Windows

Workspace
Window
Current Folder Window

Store all
Variables

Command
History
Window

Command Window
Graphical Programming-CPE112-1 Lecture 1
King Khalid University
Faculty of Computer Science
Computer Engineering Department

MATLAB windows Window Purpose


Command Window Main window, enters variables, runs
programs.
Figure Window Contains output from graphic
commands.
Editor Window Creates and debugs script and
function files.
Help Window Provides help information.
Command History Window Logs commands entered in the
Command Window.
Workspace Window Provides information about the
variables that are stored.
Current Folder Window Shows the files in the current folder.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Command Window: The Command Window is MATLAB 's main window and opens when
MATLAB is started.
Figure Window opens automatically after any command that draws a graph.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Editor Window: Use Editor Window to write and debug MATLAB scripts. Open with edit
command.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Help Window: Get Help Window by clicking on Help icon (question mark) in tool strip

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

More Fun with Windows:


 To reopen a window, click the Layout icon and then click on the window name
 To get the default window layout (shown before) click the Layout icon, then click Default.
 Undocking a window means removing it from the main MATLAB window and then
being able to move it independently. To undock a window:
 Drag the window’s title bar until the cursor is outside the MATLAB window, then release
the cursor or “Click on the Window Action icon, then click on Undock”
 To dock a window: Click on the Window Action icon, then click on Dock.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Command Window is MATLAB’s main window.


Use it to:
Execute commands
Open other windows
Run programs that you’ve written
Manage the MATLAB software

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Basic procedure:
1. At prompt (>>), type in MATLAB
command
2. Press ENTER key
3. MATLAB displays result in Command
Window, followed by a prompt
4. Repeat from step 1

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Notes on Command Window


 To start a command, make sure cursor is next to prompt
 MATLAB won’t respond until you press ENTER
• It then executes only last command
• Commands before last one may still be visible, but MATLAB doesn’t execute them
 Can type several commands in same line by putting a comma between commands
• Hard to read, so don’t do this often
 If command too long to fit on line, can continue to next line by typing ellipsis (3
periods, i.e., … ) and then pressing ENTER

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

When cursor is in bottom command line:


•  key moves cursor one character to left
•  key moves cursor one character to right
•  key recalls preceding command
•  key recalls command that follows one being displayed.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

PAGE-UP key moves up to previous commands in a window-size at a time.


 PAGE-DOWN key moves down to previous commands in a window-size
at a time.
 BACKSPACE key deletes character to left of cursor.
 DELETE key deletes character to right of cursor.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

To quickly execute a previous command but with minor changes.


1. Recall command with up- and down-arrow keys.
2. Use left- and right-arrow keys to move to characters to be altered.
3. Use BACKSPACE or DELETE to remove old character, then type new character.
4. Press ENTER to execute modified command.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Semicolon (;)
 When typed at end of command, suppresses output. (Only prompt displayed at next
line)
• Useful for preventing display of large outputs

Percent sign(%)
When typed at beginning of line, MATLAB treats line as a comment and doesn’t
execute line.
clc command
• Clears Command Window display
Up and down arrows still bring back previous commands

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Command History Window


• Shows previous commands, including ones from previous MATLAB sessions
• Double-clicking on command puts it in Command Window and executes it
• Can drag command to Command Window, make changes in command, then execute it
• To clear one or more commands, select the lines to delete, right click, choose Delete
Selection
• To clear entire history, right click, select Clear Command History

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

In this chapter will only discuss arithmetic with scalars (single numbers)
• Can do arithmetic directly on numbers (like a calculator)
• Can store numbers in variables

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Symbols for arithmetic are:

Operation Symbol Example


Addition + 5+3
Subtraction – 5–3
Left division rarely used with scalars

Multiplication * 5*3
Right division / 5/3
Left division \ 5\3=3/5
Exponentiation ^ 5 ^ 3 (means 53 = 125)

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Order in which MATLAB does arithmetic


Precedence Mathematical Operation

First Parentheses. For nested parentheses, the


innermost are executed first.
Second Exponentiation.
Third Multiplication, division (equal precedence).
Fourth Addition and subtraction.

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Precedence order
• Same as most calculators
• Same as doing arithmetic by hand
• For multiple operations of same precedence,
MATLAB goes left to right
• Can change order by using parentheses

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Can use MATLAB as a (very expensive!) calculator


1. Type in mathematical expression
2. Press Enter key
3. MATLAB displays answer in Command Window as ans = followed by the result
Your display may appear on more than one line and have blank lines between text

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Can control display of numbers with format command


• Once enter command, format stays the same until another format command
• Default format is fixed point with four digits to right of decimal point
• fixed-point means decimal point always between one’s-digit and one-tenth’s digit
• Format only affects display of numbers. MATLAB always computes and saves numbers
in full precision

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Some types of formatting

Graphical Programming-CPE112-1 Lecture 1


King Khalid University
Faculty of Computer Science
Computer Engineering Department

1.3 ARITHMETIC OPERATIONS WITH SCALARS

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

1.3.1 Order of Precedence

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Computer Programming Lecture 2


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Computer Programming Lecture 2


King Khalid University
Faculty of Computer Science
Computer Engineering Department

1.4 DISPLAY FORMATS

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

1.5 ELEMENTARY MATH BUILT-IN FUNCTIONS

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

1.6.1 The Assignment Operator


Variable_ name = A numerical value, or a computable expression

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

The Law of Cosines

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 2
112CPE– Graphical Programming– Lab Manual -Experiment #1 KKU-CSC-CE

Activity

1
King Khalid University
College of Computer Science
Department of Computer Engineering

Graphical Programming
112-CPE-1

Starting with MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________
Data Submitted: _______________ Marks: …../2mark Instructor Signature: _________

Prepared by

Eng. Abdelmoty M. Ahmed

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 3 -


112CPE– Graphical Programming– Lab Manual -Experiment #1 KKU-CSC-CE

Lab Work - Activities


Activity No.1:- For the resistor network shown below, use MATLAB® to calculate the total resistance seen
by the V1 source. Break up the calculation by defining variables for resistances of pieces of the circuit as you go.

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
Activity No.2:- Calculate Using MATLAB

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 4 -


112CPE– Graphical Programming– Lab Manual -Experiment #1 KKU-CSC-CE
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
Activity No.3:- Define the variable x as x = 2.34, then evaluate:

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
………………………………………………………………………………………………………………
……………………………………………………………………………………………………………….
………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 5 -


112CPE– Graphical Programming– Lab Manual -Experiment #1 KKU-CSC-CE

Activity No.4:- Calculate Using MATLAB

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
………………………………………………………………………………………………………………
……………………………………………………………………………………………………………….
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
…………………………………………………………………………………………………………….…
………………………………………………………………………………………………………………
……………………………………………………………………………………………………………….
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 6 -


Experiment
King Khalid University
College of Computer Science
Department of Computer Engineering
2
Graphical Programming
112-CPE-1

Vectors and Arrays in MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Eng. Abdelmoty M. Ahmed


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Chapter2
Creating Arrays
The array is a fundamental form that MATLAB uses to store data.

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Arrays : May be of various dimensions.


A 1D array is called a vector.
A 2D array or matrix.
We can also have 3D, as well as, ND arrays.
In case of a 3D array, imagine a Rubik’s cube with each cell having a value inside it.

1D array: Vector
2D array: Matrix 3D array
Graphical Programming Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

CREATING A TwO-DIMENSIONAL ARRAY (MATRIX)

Graphical Programming Lecture 3


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

The zeros, ones and, eye Commands

Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

THE TRANSPOSE OPERATOR

Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

ARRAY ADDRESSING

Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 3
King Khalid University
Faculty of Computer Science
Computer Engineering Department

ARRAY ADDRESSING

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Matrix

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

USING A COLON : IN ADDRESSING ARRAYS

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

ADDING ELEMENTS TO EXISTING VARIABLES

Adding elements to a vector:

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Adding elements to a matrix:

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

DELETING ELEMENTS

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

BUILT-IN FUNCTIONS FOR HANDLING ARRAYS

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

STRINGS AND STRINGS AS VARIABLES

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 4
King Khalid University
Faculty of Computer Science
Computer Engineering Department

 The variable x can be used in mathematical expressions,


whereas the variable y cannot.

Lecture 4
112CPE– Graphical Programming– Lab Manual -Experiment #2 KKU-CSC-CE

Activity

2
King Khalid University
College of Computer Science
Department of Computer Engineering

Graphical Programming
112-CPE-1

Vectors and Arrays in MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________
Data Submitted: _______________ Marks: …../2mark Instructor Signature: _________

Prepared by

Eng. Abdelmoty M. Ahmed

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 3 -


112CPE– Graphical Programming– Lab Manual -Experiment #2 KKU-CSC-CE

Lab Work - Activities


Activity No.1:-

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
Activity No.2:-
Create a column vector with 15 equally spaced elements in which the first element is –21 and
the last element is 12.

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 4 -


112CPE– Graphical Programming– Lab Manual -Experiment #2 KKU-CSC-CE

Activity No.3:-
Use a single command to create a row vector (assign it to a variable named b) with 19 elements such that
b = 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 Do not type the vector explicitly.

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
………………………………………………………………………………………………………………
……………………………………………………………………………………………………………….
………………………………………………………………………………………………………

Activity No.4:- Create the following matrixes by typing one command. Do not type individual elements
explicitly.

Solution
………………………………………………………………………………………………………………
……………………………………………………………………………………………………………….
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
………………………………………………………………………………………………………………
…………………………………………………………………………………………………………….…
………………………………………………………………………………………………………………
……………………………………………………………………………………………………………….

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 5 -


Activity

King Khalid University


College of Computer Science
Department of Computer Engineering
3

Graphical Programming
112-CCE-1

Mathematical Operations in Arrays Using MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________
Data Submitted: _______________ Marks: …../2mark Instructor Signature: _________

Prepared by

Eng. Abdelmoty M. Ahmed


King Khalid University
Faculty of Computer Science
Computer Engineering Department

Chapter 3: Mathematical Operations


1. Addition And Subtraction

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

3.2 ARRAY MULTIPLICATION

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 6
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Computer Programming Lecture 6


King Khalid University
Faculty of Computer Science
Computer Engineering Department
King Khalid University
Faculty of Computer Science
Computer Engineering Department

ARRAY DIVISION

Identity matrix

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Inverse of a matrix:

The matrix B is the inverse of the matrix A if, when the two
matrices are multiplied, the product is the identity matrix.
Both matrices must be square.

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Determinants:

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Array division:
MATLAB has two types of array division, right division and left division
Left division, \ :
Left division is used to solve the matrix equation AX = B.

The solution X is obtained numerically using a method that is based on


Gauss elimination

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Right division, I :

The right division is used to solve the matrix equation XC = D.

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

ELEMENT-BY-ELEMENT OPERATIONS

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 7
King Khalid University
Faculty of Computer Science
Computer Engineering Department

USING ARRAYS IN MATLAB BUILT-IN MATH FUNCTIONS

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

BUILT-IN FUNCTIONS FOR ANALYZING ARRAYS

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

GENERATION OF
RANDOM NUMBERS

Lecture 8
King Khalid University
Faculty of Computer Science
Computer Engineering Department

Lecture 8
Activity

King Khalid University


College of Computer Science
Department of Computer Engineering
3

Graphical Programming
112-CCE-1

Mathematical Operations in Arrays Using MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________
Data Submitted: _______________ Marks: …../2mark Instructor Signature: _________

Prepared by

Eng. Abdelmoty M. Ahmed


112CCE– Graphical Programming– Lab Manual -Experiment #3 KKU-CSC-CE

Lab Work - Activities


Activity No.1:-

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 2 -


112CCE– Graphical Programming– Lab Manual -Experiment #3 KKU-CSC-CE

Activity No.2:-

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 3 -


Activity

King Khalid University


College of Computer Science
Department of Computer Engineering
4

Graphical Programming
112-CCE-1

Two-Dimensional Plots Using MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________
Data Submitted: _______________ Marks: …../2mark Instructor Signature: _________

Prepared by

Eng. Abdelmoty M. Ahmed


CHAPTER - 4

Two Dimensional Plots


Topics Covered:
1. Plotting basic 2-D plots.

The plot command.

The fplot command.


Plotting multiple graphs in the same plot.
Formatting plots.
105
MAKING X-Y PLOTS

MATLAB has many functions and commands that can be used to


create various types of plots.

In our class we will only create two dimensional x – y plots.


106
EXAMPLE OF A 2-D PLOT
Plot title Legend
Light Intensity as a Function of Distance
1200
Theory
y axis Experiment

label 1000

Text
Tick-mark
800
INTENSITY (lux)

Comparison between theory and experiment.

600

400
Data symbol

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
106-
TWO-DIMENSIONAL plot() COMMAND
110

The basic 2-D plot command is:

plot(x,y)

where x is a vector (one dimensional array), and y is a vector.


Both vectors must have the same number of elements.

 The plot command creates a single curve with the x values on


the abscissa (horizontal axis) and the y values on the ordinate
(vertical axis).

 The curve is made from segments of lines that connect the


points that are defined by the x and y coordinates of the
elements in the two vectors.
106-
110
CREATING THE X AND Y VECTORS

 If data is given, the information is entered as the elements of the


vectors x and y.

 If the values ofy are determined by a function from the values


of x, than a vector x is created first, and then the values of y
are calculated for each value of x. The spacing (difference)
between the elements of x must be such that the plotted curve
will show the details of the function.
106-
PLOT OF GIVEN DATA 107

Given data:

x 1 2 3 5 7 7.5 8 10

y 2 6.5 7 7 5.5 4 6 8

A plot can be created by the commands shown below. This can be


done in the Command Window, or by writing and then running a
script file.

>> x=[1 2 3 5 7 7.5 8 10];


>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)

Once the plot command is executed, the Figure Window opens with
the following plot.
106-
PLOT OF GIVEN DATA 107
106-
LINE SPECIFIERS IN THE plot() COMMAND 107

Line specifiers can be added in the plot command to:


 Specify the style of the line.
 Specify the color of the line.
 Specify the type of the markers (if markers are desired).

plot(x,y,’line specifiers’)
106-
LINE SPECIFIERS IN THE plot() COMMAND 107

plot(x,y,‘line specifiers’)

Line Specifier Line Specifier Marker Specifier


Style Color Type

Solid - red r plus sign +


dotted : green g circle o
dashed -- blue b asterisk *
dash-dot -. Cyan c point .
magenta m square s
yellow y diamond d
black k
107-
LINE SPECIFIERS IN THE plot() COMMAND 108

 The specifiers are typed inside the plot() command as strings.

 Within the string the specifiers can be typed in any order.

 The specifiers are optional. This means that none, one, two, or
all the three can be included in a command.
EXAMPLES:
plot(x,y) A solid blue line connects the points with no markers.
plot(x,y,’r’) A solid red line connects the points with no markers.
plot(x,y,’--y’) A yellow dashed line connects the points.
plot(x,y,’*’) The points are marked with * (no line between the
points.)
plot(x,y,’g:d’) A green dotted line connects the points which are
marked with diamond markers.
110-
PLOT OF GIVEN DATA USING LINE 111
SPECIFIERS IN THE plot() COMMAND

Year 1988 1989 1990 1991 1992 1993 1994

Sales (M) 127 130 136 145 158 178 211

>> year = [1988:1:1994];


>> sales = [127, 130, 136, 145, 158, 178, 211];
>> plot(year,sales,'--r*')

Line Specifiers:
dashed red line and
asterisk markers.
110-
PLOT OF GIVEN DATA USING LINE 111
SPECIFIERS IN THE plot() COMMAND

Dashed red line and


asterisk markers.
111-
CREATING A PLOT OF A FUNCTION 112

−0.5 x
Consider: y = 3.5 cos(6 x) for − 2 ≤ x ≤ 4
A script file for plotting the function is:

% A script file that creates a plot of


% the function: 3.5^(-0.5x)*cos(6x)
x = [-2:0.01:4]; Creating a vector with spacing of 0.01.
y = 3.5.^(-0.5*x).*cos(6*x);
Calculating a value of y
plot(x,y) for each x.

Once the plot command is executed, the Figure Window opens with
the following plot.
111-
A PLOT OF A FUNCTION 112
−0.5 x
y = 3.5 cos(6 x) for − 2 ≤ x ≤ 4
111-
CREATING A PLOT OF A FUNCTION 112
If the vector x is created with large spacing, the graph is not accurate.
Below is the previous plot with spacing of 0.3.

x = [-2:0.3:4];
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)
112-
THE fplot COMMAND 113

The fplot command can be used to plot a function


with the form: y = f(x)

fplot(‘function’,limits)

 The function is typed in as a string.

 The limits is a vector with the domain of x, and optionally with limits
of the y axis:

[xmin,xmax] or [xmin,xmax,ymin,ymax]
 Line specifiers can be added.
112-
113
PLOT OF A FUNCTION WITH THE fplot() COMMAND

A plot of: y = x 2 + 4 sin( 2 x) − 1 for − 3 ≤ x ≤ 3

>> fplot('x^2 + 4 * sin(2*x) - 1', [-3 3])


114-
116
PLOTTING MULTIPLE GRAPHS IN THE SAME PLOT

Plotting two (or more) graphs in one plot:

1. Using the plot command.


2. Using the hold on, hold off commands.
114-
USING THE plot() COMMAND TO PLOT 115
MULTIPLE GRAPHS IN THE SAME PLOT

plot(x,y,u,v,t,h)

Plots three graphs in the same plot:

y versus x, v versus u, and h versus t.

 By default, MATLAB makes the curves in different colors.


 Additional curves can be added.
 The curves can have a specific style by adding specifiers after
each pair, for example:

plot(x,y,’-b’,u,v,’—r’,t,h,’g:’)
114-
USING THE plot() COMMAND TO PLOT 115
MULTIPLE GRAPHS IN THE SAME PLOT

Plot of the function, y = 3 x 3 − 26 x + 10 and its first and second


derivatives, for − 2 ≤ x ≤ 4 , all in the same plot.

x = [-2:0.01:4]; vector x with the domain of the function.


y = 3*x.^3-26*x+6; Vector y with the function value at each x.
−2≤ x ≤ 4

yd = 9*x.^2-26; Vector yd with values of the first derivative.


ydd = 18*x; Vector ydd with values of the second derivative.
−2≤ x ≤ 4

plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

Create three graphs, y vs. x (solid blue


line), yd vs. x (dashed red line), and ydd
vs. x (dotted black line) in the same figure.
114-
USING THE plot() COMMAND TO PLOT 115
MULTIPLE GRAPHS IN THE SAME PLOT

120

100

80

60

40

20

-20

-40
-2 -1 0 1 2 3 4
115-
USING THE hold on, hold off, COMMANDS 116
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT

hold on Holds the current plot and all axis properties so that
subsequent plot commands add to the existing plot.

hold off Returns to the default mode whereby plot commands


erase the previous plots and reset all axis properties
before drawing new plots.

This method is useful when all the information (vectors) used for
the plotting is not available a the same time.
115-
USING THE hold on, hold off, COMMANDS 116
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
Plot of the function, y = 3 x 3 − 26 x + 10 and its first and second
derivatives, for − 2 ≤ x ≤ 4 all in the same plot.

x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b') First graph is created.
hold on
plot(x,yd,'--r')
Two more graphs are created.
plot(x,ydd,':k')
hold off
EXAMPLE OF A FORMATTED 2-D PLOT 106
Plot title
Light Intensity as a Function of Distance
1200 Legend
Theory
y axis Experiment

label 1000

Text
800
Tick-mark
INTENSITY (lux)

Comparison between theory and experiment.

600

400
Data symbol
200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
116-
122
FORMATTING PLOTS

A plot can be formatted to have a required appearance.

With formatting you can:

 Add title to the plot.


 Add labels to axes.
 Change range of the axes.
 Add legend.
 Add text blocks.
 Add grid.
116-
FORMATTING PLOTS 122

There are two methods to format a plot:

1. Formatting commands.
In this method commands, that make changes or additions to
the plot, are entered after the plot() command. This can be
done in the Command Window, or as part of a program in a
script file.

2. Formatting the plot interactively in the Figure Window.


In this method the plot is formatted by clicking on the plot and
using the menu to make changes or add details.
116-
FORMATTING COMMANDS 122

title(‘string’)
Adds the string as a title at the top of the plot.

xlabel(‘string’)
Adds the string as a label to the x-axis.

ylabel(‘string’)
Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])


Sets the minimum and maximum limits of the x- and y-axes.
116-
FORMATTING COMMANDS 122

legend(‘string1’,’string2’,’string3’)
Creates a legend using the strings to label various curves (when
several curves are in one plot). The location of the legend is
specified by the mouse.

text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y relative to
the plot axes.

gtext(‘string’)
Places the string (text) on the plot. When the command
executes the figure window pops and the text location is clicked
with the mouse.
120-
EXAMPLE OF A FORMATTED PLOT 121
Below is a script file of the formatted light intensity plot (2nd slide).
(Some of the formatting options were not covered in the lectures,
but are described in the book)

x=[10:0.1:22]; Creating vector x for plotting the theoretical curve.


y=95000./x.^2; Creating vector y for plotting the theoretical curve.
xd=[10:2:22]; Creating a vector with coordinates of data points.
yd=[950 640 460 340 250 180 140]; Creating a vector with
light intensity from data.
plot(x,y,'-','LineWidth',1.0)
hold on
plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)
hold off
120-
EXAMPLE OF A FORMATTED PLOT 121

Formatting of the light intensity plot (cont.)

xlabel('DISTANCE (cm)')
Labels for the axes.
ylabel('INTENSITY (lux)')
Title for the plot.
title('\fontname{Arial}Light Intensity as a Function of
Distance','FontSize',14)
axis([8 24 0 1200]) Setting limits of the axes.
text(14,700,'Comparison between theory and
Creating text.
experiment.','EdgeColor','r','LineWidth',2)
legend('Theory','Experiment',0) Creating a legend.

The plot that is obtained is shown again in the next slide.


120-
EXAMPLE OF A FORMATTED PLOT 121
121-
FORMATTING A PLOT IN THE FIGURE WINDOW 122

Once a figure window is open, the figure can be formatted interactively.


Use the insert menu to

Use Figure, Click here to start the


Axes, and plot edit mode.
Current Object-
Properties in
the Edit menu
Activity

King Khalid University


College of Computer Science
Department of Computer Engineering
4

Graphical Programming
112-CCE-1

Two-Dimensional Plots Using MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________
Data Submitted: _______________ Marks: …../2mark Instructor Signature: _________

Prepared by

Eng. Abdelmoty M. Ahmed


112CCE– Graphical Programming– Lab Manual -Experiment #4 KKU-CSC-CE

Lab Work - Activities


Activity No.1:-
Plot the function , and its first and second derivatives,
for -2 ≤ x ≤ 4, all in the same plot

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 2 -


112CCE– Graphical Programming– Lab Manual -Experiment #4 KKU-CSC-CE

Activity No.2:-

1)

2)

3)

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 3 -


Experiment
King Khalid University
College of Computer Science
Department of Computer Engineering
5
Graphical Programming
112-CCE-1

Programming in MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Mr. Rahmathullah Mohammed


Mr. Jamshed M Basheer
Introduction
A computer program is a sequence of computer commands.
In a simple program the commands are executed one after the other in the order they are
typed.

5.1 RELATIONAL AND LOGICAL OPERATORS


A relational operator compares two numbers by determining whether a
comparison statement (e.g., 5 < 8) is true or false.
 If the statement is true, it is assigned a value of 1.
 If the statement is false, it is assigned a value of 0.

2
5.1 RELATIONAL AND LOGICAL OPERATORS

Relational operators:

3
5.1 RELATIONAL AND LOGICAL OPERATORS
Relational operators:
When two numbers are compared, the result is 1 (logical true) if the comparison,
according to the relational operator, is true, and 0 (logical false) if the comparison is false.
If two scalars are compared, the result is a scalar 1 or 0. If two arrays are compared (only
arrays of the same size can be compared), the comparison is done element-by-element, and
the result is a logical array of the same size with 1s and 0s according to the outcome of the
comparison at each address.
If a scalar is compared with an array, the scalar is compared with every element of the
array, and the result is a logical array with 1s and 0s according to the outcome of the
comparison of each element.

4
5.1 RELATIONAL AND LOGICAL OPERATORS

5
5.1 RELATIONAL AND LOGICAL OPERATORS

6
5.1 RELATIONAL AND LOGICAL OPERATORS

7
5.1 RELATIONAL AND LOGICAL OPERATORS
When a logical vector is used for addressing another vector, it extracts from that vector the
elements in the positions where the logical vector has 1s. For example:

8
5.1 RELATIONAL AND LOGICAL OPERATORS
Order of precedence:
In a mathematical expression that includes relational and arithmetic operations, the arithmetic
operations (+, –, *, /, \) have precedence over relational operations.

9
5.1 RELATIONAL AND LOGICAL OPERATORS

10
5.1 RELATIONAL AND LOGICAL OPERATORS
Logical operators have numbers as operands. A nonzero number is true, and a zero number is false.

11
5.1 RELATIONAL AND LOGICAL OPERATORS

12
5.1 RELATIONAL AND LOGICAL OPERATORS
Order of precedence:

13
5.1 RELATIONAL AND LOGICAL OPERATORS

14
5.1 RELATIONAL AND LOGICAL OPERATORS

15
5.1 RELATIONAL AND LOGICAL OPERATORS

16
5.1 RELATIONAL AND LOGICAL OPERATORS

17
5.1 RELATIONAL AND LOGICAL OPERATORS

18
5.2 CONDITIONAL STATEMENTS

A conditional statement is a command that allows MATLAB to make a decision of whether


to execute a group of commands that follow the conditional statement, or to skip these
commands.
In a conditional statement a conditional expression is stated:
 If the expression is true, a group of commands that follow the statement are executed.
 If the expression is false, the computer skips the group.

The basic form of a conditional statement is:

19
5.2 CONDITIONAL STATEMENTS

For every if statement there is an end statement.


The if statement is commonly used in three structures, if-end, if-else-end, and if-elseif-
else-end, which are described next.

20
5.2 CONDITIONAL STATEMENTS
5.2.1 The if-end Structure

21
5.2 CONDITIONAL STATEMENTS
Sample Problem 5-2: Calculating worker’s pay
A worker is paid according to his hourly wage up to 40 hours, and 50% more for overtime.
Write a program in a script file that calculates the pay to a worker. The program asks the user
to enter the number of hours and the hourly wage. The program then displays the pay.

22
5.2 CONDITIONAL STATEMENTS
Sample Problem 5-2: Calculating worker’s pay
Application of the program (in the Command Window) for two cases is shown below (the
file was saved as Workerpay):

23
5.2 CONDITIONAL STATEMENTS
5.2.2 The if-else-end Structure:
provides a means for
choosing one group of
commands, out of a
possible two groups,
for execution.

24
5.2 CONDITIONAL STATEMENTS
5.2.3 The if-elseif-else-end Structure
This structure includes two
conditional statements (if
and elseif) that make it
possible to select one out
of three groups of
commands for execution.
Several elseif statements
and associated groups of
commands can be added.
In this way more
conditions can be included.

25
5.2 CONDITIONAL STATEMENTS
Sample Problem 5-3: Water level in water tower
The tank in a water tower has the geometry
shown in the figure (the lower part is a cylinder
and the upper part is an inverted frustum of a
cone). Inside the tank there is a float that indicates
the level of the water. Write a MATLAB program
that determines the volume of the water in the tank
from the position (height h) of the float. The
program asks the user to enter a value of h in m,
and as output displays the volume of the water in
m3.

26
5.2 CONDITIONAL STATEMENTS
Sample Problem 5-3: Water level in water tower

27
Dr. Talal Skaik 2018
5.2 CONDITIONAL STATEMENTS

28
Dr. Talal Skaik 2018
5.2 CONDITIONAL STATEMENTS
The following is the display in the Command Window when the program is used with three
different values of water height.

29
5.3 THE switch-case STATEMENT
The switch-case statement is another method that can be used to direct the flow of a program.
It provides a means for choosing one group of commands for execution out of several possible
groups.
The first line is the switch command, which has the form:

Following the switch command are one or several case commands. Each has a value
(can be a scalar or a string) next to it (value1, value2, etc.) and an associated group of
commands below it.
After the last case command there is an optional otherwise command followed by a
group of commands.
The last line must be an end statement.
30
5.3 THE switch-case STATEMENT

31
5.3 THE switch-case STATEMENT

If there is more than one match, only the first matching case is executed.
If no match is found and the otherwise statement (which is optional) is present, the group
of commands between otherwise and end is executed.
If no match is found and the otherwise statement is not present, none of the command
groups is executed.

Note: In MATLAB only the first matching case is executed. After the group of commands
associated with the first matching case are executed, the program skips to the end statement.
This is different from the C language, where break statements are required.

32
5.3 THE switch-case STATEMENT
Sample Problem 5-4: Converting units of energy
Write a program in a script file that converts a quantity of energy (work) given in units of
either joule, ft-lb, cal, or eV to the equivalent quantity in different units specified by the
user. The program asks the user to enter the quantity of energy, its current units, and the
desired new units. The output is the quantity of energy in the new units.

33
5.3 THE switch-case STATEMENT

Converting
units of
energy

34
5.3 THE switch-case STATEMENT

Converting
units of
energy

35
5.3 THE switch-case STATEMENT

Converting units of energy


As an example, the script file (saved as EnergyConversion) is used next in the Command
Window to make the conversion in part (b) of the problem statement.

36
5.4 LOOPS
A loop is another method to alter the flow of a computer program.
In a loop, the execution of a command, or a group of commands, is repeated several times
consecutively.
Each round of execution is called a pass. In each pass at least one variable, but usually
more than one, or even all the variables that are defined within the loop, are assigned new
values.
MATLAB has two kinds of loops, for-end loops and while-end loops.

37
5.4 LOOPS
5.4.1 for-end Loops
In for-end loops the execution of a command, or a group of commands, is repeated a
predetermined number of times.

38
5.4 LOOPS 5.4.1 for-end Loops for k = f:s:t
The loop index variable can have any variable name (usually i, j, k, m, and n are used,
however, i and j should not be used if MATLAB is used with complex numbers).
In the first pass k = f and the computer executes the commands between the for and end
commands. Then, the program goes back to the for command for the second pass. k obtains a
new value equal to k = f + s, and the commands between the for and end commands are
executed with the new value of k. The process repeats itself until the last pass, where k = t.
Then the program does not go back to the for, but continues with the commands that follow
the end command. For example, if k = 1:2:9, there are five loops, and the corresponding
values of k are 1, 3, 5, 7, and 9.
The increment s can be negative (i.e.; k = 25:–5:10 produces four passes with k = 25, 20, 15,
10).
If the increment value s is omitted, the value is 1 (default) (i.e.; k = 3:7 produces five passes
with k = 3, 4, 5, 6, 7).
39
5.4 LOOPS 5.4.1 for-end Loops for k = f:s:t
The If f = t, the loop is executed once.
If f > t and s > 0, or if f < t and s < 0, the loop is not executed.
If the values of k, s, and t are such that k cannot be equal to t, then if s is positive, the last pass is
the one where k has the largest value that is smaller than t (i.e., k = 8:10:50 produces five passes
with k = 8, 18, 28, 38, 48). If s is negative, the last pass is the one where k has the smallest value
that is larger than t.
In the for command k can also be assigned a specific value (typed as a vector). Example: for k =
[7 9 –1 3 3 5].
The value of k should not be redefined within the loop.
Each for command in a program must have an end command.
The value of the loop index variable (k) is not displayed automatically. It is possible to display
the value in each pass (which is sometimes useful for debugging) by typing k as one of the
commands in the loop.
40
5.4 LOOPS 5.4.1 for-end Loops for k = f:s:t
When the loop ends, the loop index variable (k) has the value that was last assigned to it.
A simple example of a for-end loop (in a script file) is:

41
5.4 LOOPS 5.4.1 for-end Loops
Sample Problem 5-5: Sum of a series

42
5.4 LOOPS 5.4.1 for-end Loops Sample Problem 5-5: Sum of a series

(a)

43
5.4 LOOPS 5.4.1 for-end Loops Sample Problem 5-5: Sum of a series

(b)

44
5.4 LOOPS 5.4.1 for-end Loops Sample Problem 5-5: Sum of a series

(b)

45
5.4.1 for-end Loops Sample Problem 5-6: Modify vector elements

A vector is given by V = [5, 17, –3, 8, 0, –7, 12, 15, 20, –6, 6, 4, –7, 16]. Write a program as a
script file that doubles the elements that are positive and are divisible by 3 or 5, and, raises to the
power of 3 the elements that are negative but greater than –5.

46
5.4.2 while-end Loops

while-end loops are used in situations when looping is needed but the number of passes is
not known in advance.
In while-end loops the number of passes is not specified when the looping process starts.
Instead, the looping process continues until a stated condition is satisfied.

47
5.4.2 while-end Loops

For a while-end loop to execute properly:


The conditional expression in the while command must include at least one variable.
The variables in the conditional expression must have assigned values when MATLAB
executes the while command for the first time.
At least one of the variables in the conditional expression must be assigned a new value in
the commands that are between the while and the end. Otherwise, once the looping starts it
will never stop since the conditional expression will remain true.

48
5.4.2 while-end Loops

49
5.4.2 while-end Loops

Sample Problem 5-7: Taylor series representation of a function

50
5.4.2 while-end Loops Sample Problem 5-7: Taylor series representation of a function

51
5.4.2 while-end Loops Sample Problem 5-7: Taylor series representation of a function

52
5.5 NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS

Loops and conditional statements can be nested within other loops or conditional statements.
This means that a loop and/or a conditional statement can start (and end) within another loop
or conditional statement.

53
5.5 NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS

Sample Problem 6-8: Creating a matrix with a loop

Write a program in a script file that creates an n x m matrix with elements that have the
following values:
The value of each element in the first row is the number of the column.
The value of each element in the first column is the number of the row.
The rest of the elements each has a value equal to the sum of the element above it and the
element to the left.
When executed, the program asks the user to enter values for n and m.
Solution: The program, shown next, has two loops (one nested) and a nested if-elseif-else-
end structure. The elements in the matrix are assigned values row by row. The loop index
variable of the first loop, k, is the address of the row, and the loop index variable of the
second loop, h, is the address of the column.
54
5.5 NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS

55
5.5 NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS

The program is executed in the Command Window to create a 4x5 matrix:

56
5.6 THE break AND continue COMMANDS

The break command:


When inside a loop (for or while), the break command terminates the execution of the loop
(the whole loop, not just the last pass). When the break command appears in a loop,
MATLAB jumps to the end command of the loop and continues with the next command (it
does not go back to the for command of that loop).
If the break command is inside a nested loop, only the nested loop is terminated.
When a break command appears outside a loop in a script or function file, it terminates the
execution of the file.
The break command is usually used within a conditional statement. In loops it provides a
method to terminate the looping process if some condition is met —for example, if the
number of loops exceeds a predetermined value.
57
5.6 THE break AND continue COMMANDS

The continue command:

The continue command can be used inside a loop (for or while) to stop the present pass
and start the next pass in the looping process.
The continue command is usually a part of a conditional statement. When MATLAB
reaches the continue command, it does not execute the remaining commands in the loop, but
skips to the end command of the loop and then starts a new pass.

58
Experiment
King Khalid University
College of Computer Science
Department of Computer Engineering
5
Graphical Programming
112-CCE-1

Programming in MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Mr. Rahmathullah Mohammed


Mr. Jamshed M Basheer
112CPE– Graphical Programming– Lab Manual -Chapter #5 KKU-CSC-CE

Lab Work - Activities


Activity No.1:-

The sample maximum daily temperatures (in F) for Jeddah and Riyadh during the month of August 2021

are given in the vectors below.

TJ = [75 79 86 86 79 81 73 89 91 86 81 82 86 88 89 90 82 84 81 79 73 69 73 79 82 72 66 71 69 66 66]
TR = [69 68 70 73 72 71 69 76 85 87 74 84 76 68 79 75 68 68 73 72 79 68 68 69 71 70 89 95 90 66 69]
Write a program in a script file to answer the following:
(a) Calculate the average temperature for the month in each city.
(b) How many days was the temperature above the average in each city?
(c) How many days, and on which dates in the month, was the temperature in Jeddah lower than the
temperature in Riyadh?
(d) How many days, and on which dates in the month, was the temperature the same in both cities?

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 2 -


112CPE– Graphical Programming– Lab Manual -Chapter #5 KKU-CSC-CE

Activity No.2:-
Write a program in a script file that determines the real roots of a quadratic equation .
Name the file quadroots. When the file runs, it asks the user to enter the values of the constants a, b,
and c. To calculate the roots of the equation the program calculates the discriminant D, given by:
.
 If D > 0, the program displays message “The equation has two roots,” and the roots are displayed
in the next line.
 If D = 0, the program displays message “The equation has one root,” and the root is displayed in
the next line.
 If D < 0, the program displays message “The equation has no real roots.”
Run the script file in the Command Window three times to obtain solutions to the following three
equations:
(a)
(b)
(c)

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 3 -


112CPE– Graphical Programming– Lab Manual -Chapter #5 KKU-CSC-CE
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
Activity No.3:-
Write a program (using a loop) that determines the expression:

Run the program with m = 5, m = 10, and m = 20. Compare the result with π. (Use format long.)

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
………………….…………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…………………….………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 4 -


112CPE– Graphical Programming– Lab Manual -Chapter #5 KKU-CSC-CE
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...

© Computer Engineering Department, Eng. Abdelmoty M. Ahmed Page - 5 -


Experiment
King Khalid University
College of Computer Science
Department of Computer Engineering
6
Graphical Programming
112-CCE-1

Three Dimensional Plots

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Mr. Rahmathullah Mohammed


Mr. Jamshed M Basheer
10.0

Three-dimensional (3-D) plots


useful for presenting related 3-D
points. Common cases are
▪Scalar or vector function of two-
independent variables
▪Scalar or vector data
measurements in 3-D space
▪Movement over time 3-D space

2
10.0

MATLAB has many commands for


making 3-D plots. Will study
▪Line plots
▪Wire plots
▪Surface plots
▪Mesh plots
For more information, click on Help
icon, select MATLAB, then Graphics,
then scroll down and select 2-D and
3-D plots

3
10.1 Line Plots

A three-dimensional line plot is a plot


obtained by connecting points in
3-D space. MATLAB command is

▪x, y, and z must be same size


▪Remaining arguments are same as
in 2-D plots (Section 5.1)
4
10.1 Line Plots

If the spatial coordinates of a set of


points are each functions of the same
independent variable, the coordinates
form a set of parametric equations.
▪Often independent variable is time
(t) and the set shows how a particle
moves through space over time

5
10.1 Line Plots

EXAMPLE
Suppose the spatial coordinates
vary with time as
𝑥𝑥 = 𝑡𝑡 sin(2𝑡𝑡)
𝑦𝑦 = 𝑡𝑡 cos(2𝑡𝑡)
𝑧𝑧 = 0.5𝑡𝑡
Make a line plot for 0 ≤ t ≤ 6π

6
10.1 Line Plots

7
10.2 Mesh and Surface Plots

Mesh and surface plots are 3-D plots


used to graph functions of the form
z = f(x,y)
▪x and y are independent variables, z is a
dependent variable
▪A mesh plot connects values of z with
lines to form the outline of a surface
▪A surface plot connects lines in a mesh
plot with planes to show a solid
representation of the surface

8
10.2 Mesh and Surface Plots

Three steps to making mesh or


surface plot
1. Create grid in the x-y plane that
contains points you're interested in
2. Calculate the value of z at every
point of the grid
3. Make the plot

9
10.2 Mesh and Surface Plots

Creating a grid in the x y plane (Cartesian coordinates):

The grid is the set of points on which


you want to evaluate z. For example

10
10.2 Mesh and Surface Plots

Can define the grid by using two


matrices, X and Y
▪X has x-coordinates of all grid points
▪Y has y-coordinates of all grid points
For grid shown
−1 0 1 2 3
−1 0 1 2 3
𝑋𝑋 =
−1 0 1 2 3
−1 0 1 2 3

4 4 4 4 4
3 3 3 3 3
Y =
2 2 2 2 2
1 1 1 1 1
11
10.2 Mesh and Surface Plots

Note that
▪X is made of identical rows because each row
of grid has the same x-coordinates
▪Y is made of identical columns because each
column of grid has same y-coordinates
To make matrices, use MATLAB
command

12
10.2 Mesh and Surface Plots

13
10.2 Mesh and Surface Plots

Calculating the value of z at each point of the grid:

Calculate value of z at each point by


using elementwise calculations.
▪X and Y must be same dimensions
▪Resulting z will also be same dimension
𝑥𝑥𝑦𝑦 2
For example grid and 𝑧𝑧 = 𝑥𝑥 2 +𝑦𝑦 2
>> Z = X.*Y.^2 ./ (X.^2 + Y.^2)

14
10.2 Mesh and Surface Plots

Making mesh and surface plots:


▪To make mesh plot use mesh(X,Y,Z)
▪To make surface plot use surf(X,Y,Z)

EXAMPLE
𝑥𝑥𝑦𝑦 2
Make mesh and surface plots of 𝑧𝑧 = 𝑥𝑥 2 +𝑦𝑦 2
over domain -1≤ x ≤ 3 and 1 ≤ y ≤ 4

15
10.2 Mesh and Surface Plots

16
10.2 Mesh and Surface Plots

Additional comments on the mesh command:


▪MATLAB colors surface plots with colors
that vary with value of z
▪ Can make color constant by using the Plot Editor
in the Figure Window or by using colormap
command. (See Help on colormap for details)
▪By default, mesh draws a grid. Issue
command grid off to prevent grid from
appearing
▪Can draw box around plot with box on

17
10.2 Mesh and Surface Plots

Can also use mesh(Z) and surf(Z)


▪Command uses row indexes on the x-
axis and column indexes on the y-axis
Table 10-1 in book shows lots of
variations available with mesh and
surf commands
Table 10-2 in book shows some
commands for specialized 3-D plots.
Can get more information from Help
Window or by using help command
18
10.3 Plots With Special Graphics

Polar coordinates grid in the x y plane:


To make 3-D plot of function z = f(r,θ)
1. Make grid of values of θ and r with
meshgrid
2. Compute value of z at each grid point
3. Convert grid with polar coordinates to
grid with Cartesian coordinates using
MATLAB's pol2cart command
4. Make 3-D plot using values of z and the
Cartesian coordinates

19
10.3 Plots With Special Graphics

20
10.4 The view Command

The view command controls direction


from which you view plot. Command is
view(az,el) or view([az el])
▪az – azimuth: angle (in degrees) in x y plane
measured from negative y axis and positive
in counterclockwise direction
▪el – elevation: angle of
elevation (in degrees)
from x y plane. Positive
in direction of positive
z axis
21
10.4 The view Command

Default view angles are az = -37.5o and el = 30o

az = -37.5o and el = 30o az = 20o and el = 35o

22
10.4 The view Command

Can project 3-D curve onto 2-D plane by


specific settings of azimuth and elevation

See Fig. 10-5 through Fig. 10-7 for


examples of projections

23
10.4 The view Command

view can also set a default view


▪view(2) sets default to top view
(projection onto x-y plane with az = 0o, and
el = 90o
▪view(3) sets default to standard 3-D view
(az = –37.5o, and el = 30o)

24
10.4 The view Command

Can also set viewing direction by


selecting a point in space from which to
view plot
▪Command has form view([x y z])
▪ x, y, and z are the coordinates of the point
▪ Viewing direction is direction from specified point
to origin of coordinate system
▪ Viewing direction independent of distance to
origin, e.g., view is same with point [6 6 6] as with
point [10 10 10]
▪ Set top view with [0 0 1]
▪ Set side view of x-z plane from negative y
with [0 –1 0]

25
Experiment
King Khalid University
College of Computer Science
Department of Computer Engineering
6
Graphical Programming
112-CCE-1

3-D Plots

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Mr. Rahmathullah Mohammed


Mr. Jamshed M Basheer
112CPE– Graphical Programming– Lab Manual -Chapter #6 KKU-CS-CE

Lab Work - Activities


Activity No.1:-

The position of a moving particle as a function of time is given by:

Plot the position of the particle for .

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Rahmathullah & Eng. Jamshed Page - 2 -


112CPE– Graphical Programming– Lab Manual -Chapter #6 KKU-CS-CE

Activity No.2:-
Make a 3-D mesh plot of the below function in the domain

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………

© Computer Engineering Department, Eng. Rahmathullah & Eng. Jamshed Page - 3 -


112CPE– Graphical Programming– Lab Manual -Chapter #6 KKU-CS-CE

Activity No.3:-
Make a 3-D surface plot of the function given below, in the domain .

Solution
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………….……………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
………………….…………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
…………………….………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………
……………………………………………………………………………………………………………...

© Computer Engineering Department, Eng. Rahmathullah & Eng. Jamshed Page - 4 -


Experiment
King Khalid University
College of Computer Science
Department of Computer Engineering
7
Graphical Programming
112-CCE-1

GUI Using MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Mr. Rahmathullah Mohammed


Mr. Jamshed M Basheer
GRAPHICAL USER INTERFACE (GUI)
• Graphical user interfaces, or GUIs, are essentially objects that allow users
to have input using graphical interfaces, such as push buttons, sliders, radio
buttons, toggle buttons, pop-up menus, and so forth.
• In MATLAB there are two basic methods for creating GUIs: writing the GUI
program from scratch or using the built-in Graphical User Interface
Development Environment (GUIDE).
• GUIDE allows the user to graphically lay out the GUI and MATLAB generates
the code for it automatically.
• A Figure Window is the parent of any GUI. Just calling the figure function
will bring up a blank Figure Window.
• Assigning the handle of this Figure Window to a variable and then using the
get function will show the default properties.
GRAPHICAL USER INTERFACE (GUI)
• The position vector specifies [left bottom width height]. The first two
numbers, the left and bottom, are the distance that the lower left corner of
the figure box is from the lower left of the monitor screen (first from the
left and then from the bottom). The last two are the width and height of
the figure box itself. All of these are in the default units of pixels.
• The ‘Visible’ property “on” means that the Figure Window can be seen.
• When creating a GUI, however, the normal procedure is to create the
parent Figure Window, but make it invisible. Then, all user interface objects
are added to it and properties are set. When everything has been
completed the GUI is made visible.
• The figure function numbers Figure Windows sequentially 1, 2, and so
forth. The root object, the screen itself, is designated as Figure 0.
Write a MATLAB script for creating a figure
and display its properties?
Write a MATLAB script for creating a figure and
change its color and position?
Design a simple GUI using GUIDE of MATLAB
STEPS TO DESIGN:
1. Open a New GUI from the New icon. GUIDE Quick Start dialog box
will appear.
2. From the GUIDE Quick Start dialog box, select the Blank GUI
(Default) template and Save it as P3SimpleGUI.fig
3. To display the names of the UI components in the component
palette:
• Select File > Preferences > GUIDE.
• Select Show names in component palette.
• Click OK.
4. We can add three push buttons to the UI by selecting the Push
Button tool from the component palette at the left side of the Layout
Editor and drag it into the layout area.
5. We can add Axes to the UI by selecting the Axes tool from the
component palette at the left side of the Layout Editor and drag it into
the layout area.
6. Arrange the components as shown in the following figure.
7. Resize the axes component to approximately 2-by-2 inches
Align the components
8. If several components have the same parent, you can use the
Alignment Tool to align them to one
another. To align the three push buttons:
a. Select all three push buttons by pressing Ctrl and clicking them.
b. Select Tools > Align Objects.
c. Make these settings in the Alignment Tool:
1. Left-aligned in the horizontal direction
2. 20 Pixels spacing between push buttons in the vertical direction
d. Click OK
Label the components
9. To name the three Push buttons as (Load Original, Gray Scale, and
Black and White image)
a) Select View > Property Inspector.
b) In the layout area, click the top push button (A−Z).
c) Select the String property, and then replace the existing value with the
word: Load Image, Gray Image, and Black and white (BW image) for each
Push Button
10. Save the UI layout. When you save a layout, GUIDE creates two
files, a FIG−file and a code file. The FIG−file, with extension .fig, is a
binary file that contains a description of the layout. The code file, with
extension .m, contains MATLAB functions that control the UI behavior.
11. Save and run your program by selecting Tools > Run.
12. Add the following to the .m file
OUTPUT
Design a GUI using GUIDE of MATLAB with
three images in the pop up menu
• STEPS TO DESIGN:
1. Add a panel and then three push buttons on it.
2. Add a static text for “Select an image:”.
3. Add pop up menu and axes.
4. Call each icon.
5. Change the panel HighlightColor to RED 
6. Add tool bar buttons for ZOOM in and out and
rotate using tool bar editor
7. Save the GUI and add the following to the program.
8. Run the MATLAB Code to see the GUI output. Select the image from the
pop-up menu and apply the operations.
Experiment
King Khalid University
College of Computer Science
Department of Computer Engineering
7
Graphical Programming
112-CCE-1

GUI Using MATLAB

Student Information
Name: ____________________________________________________________________________________
ID Number: ________________ Serial Number: ______________ Group Number: ___________

Prepared by

Mr. Rahmathullah Mohammed


Mr. Jamshed M Basheer
112CPE– Graphical Programming– Lab Manual -Chapter # 7 KKU-CS-CE

Lab Work - Activities


Activity No. 1:-
Create a GUI with two textbox to take inputs Number1 and Number2, place two buttons for add and
subtract and Display the result in a textbox as shown below:
Write a MATLAB code to print the result when add or subtract button is pressed.

Activity No. 2:-


Create a GUI with one textbox to take input side of square, place one button to calculate area and
perimeter. Place two textbox to display area and perimeter, Write a MATLAB code to print area and
perimeter when calculate button is pressed.

© Computer Engineering Department, Eng. Rahmathullah & Eng. Jamshed Page - 2 -


112CPE– Graphical Programming– Lab Manual -Chapter # 7 KKU-CS-CE

Activity No. 3:-

Create a GUI to resize the image as shown below:

© Computer Engineering Department, Eng. Rahmathullah & Eng. Jamshed Page - 3 -

You might also like