Chapter 1 Starting with MATLAB
Transcript of Chapter 1 Starting with MATLAB
Chapter 1Starting with MATLAB
Computer ProgrammingECIV 2303
Civil Engineering DepartmentProf. Mohammed Arafa
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.
Text Book
➢MATLAB: An Introduction with Applications, by Amos Gilat, 6th Ed., 2017:
This book is intended for students who are using MATLAB for the first time
and have little or no experience in computer programming.
➢Möler, 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 .
➢ Course used Matlab Versions: R2015a or later
History 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.
Strengths 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 text-analysis in order to
associate groups of characters with the syntactic units of the
underlying grammar).
Weaknesses of 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
) in the Resources➢ Help icon – the question-mark icon (Section of the desktop toolbar
) in the Environment Section of the desktop➢ Layout icon – ( toolbar
Starting with MATLAB
This chapter describes:➢ MATLAB windows➢ Command Window in detail➢ How to do basic arithmetic➢ Create basic variables➢ Introductory script files
Starting with MATLAB
Starting MATLAB, MATLAB Windows (R20019a)C
urr
ent
Fold
erW
ind
ow
Command Window
Wo
rksp
ace
Win
do
wSt
ore
all
Var
iab
les
Starting MATLAB, MATLAB Windows (R20013a)C
urr
ent
Fold
erW
ind
ow
Workspace Window
Store allVariables
Command History Window
Command Window
Window Purpose
Command WindowMain window, enters variables, runs programs.
Figure WindowContains output from graphiccommands.
Editor WindowCreates and debugs script and function files.
Help Window Provides help information.
Command History WindowLogs commands entered in theCommand Window.
Workspace WindowProvides information about the variables that are stored.
Current Folder Window Shows the files in the current folder.
MATLAB windows
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.
MATLAB windows
Editor Window: Use Editor Window to write and debug MATLABscripts. Open with edit command.
MATLAB windows
Help Window: Get Help Window by clicking on Help icon (question mark) in tool strip
MATLAB windows
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.
MATLAB windows
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
MATLAB windows
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
MATLAB windows
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 (,)
or semicolon (;) between command
➢Clear, 𝑥=15 + 5 ∗ cos pi/3
➢If command too long to fit on line, can continue to next line by
typing ellipsis (3 periods, i.e., … ) and then pressing ENTER
MATLAB windows
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.
MATLAB windows
➢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.
MATLAB windows
To quickly execute a previous command but with minorchanges.
1. Recall command with up- and down-arrow keys.
2. Use left- and right-arrow keys to move to characters to bealtered.
3. Use BACKSPACE or DELETE to remove old character, then type new character.
4. Press ENTER to execute modified command.
MATLAB windows
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
MATLAB windows
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
MATLAB windows
Symbols for Arithmetic Operations
Order in which MATLAB does Arithmetic
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
Order in which MATLAB does arithmetic
Order in which MATLAB does arithmetic
The display of numbers can be controlled 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 (called short)
➢Format only affects display of numbers. MATLAB always
computes and saves numbers in full precision
Display Format
Display Format
Display Format
Elementary Math built-in Functions
Elementary Math built-in Functions
Elementary Math built-in Functions
Elementary Math built-in Functions
The inverse trigonometric functions are asin(x), acos(x), atan(x), acot(x) for the angle in radians; and asind(x), acosd(x), atand(x), acotd(x) for the angle in degrees. The hyperbolic trigonometric functions are sinh(x), cosh(x), tanh(x), and coth(x).
Elementary Math built-in Functions
Elementary Math built-in Functions
Variable_ name = A numerical value, or a computableexpression
The Assignment Operator
The Assignment Operator
The Assignment Operator
Rules About Variable Names
✓ Must begin with a letter.
✓ Can be up to 63 characters long.
✓ Can contain letters, digits, and the underscore character.
✓ Cannot contain punctuation characters (e.g., period, comma,
semicolon).
✓ MATLAB is case-sensitive: it distinguishes between
uppercase and lowercase letters. For example, AA, Aa, aA, and
aa are the names of four different variables.
✓ No spaces are allowed between characters (use the underscore
where a space is desired).
✓ Avoid using the name of a built-in function for a variable (i.e.,
avoid using cos, sin, exp, sqrt, etc.). Once a function name is
used to for a variable name, the function cannot be used.
Predefined Variables and Keywords
✓ There are 20 words, called keywords, that are reserved by
MATLAB for various purposes and cannot be used as variable
names.
✓ These words are: { break, case, catch, classdef, continue, else,
elseif, end, for, function, global, if, otherwise, parfor,
persistent, return, spmd, switch, try, while }
✓ When typed, these words appear in blue. An error message is
displayed if the user tries to use a keyword as a variable name
Predefined Variables and Keywords
A number of frequently used variables are already defined when
MATLAB is started. Some of them are are:
✓ ans : If the user does not assign the value of an expression
to a variable, MATLAB automatically stores the result in ans.
✓ pi : The number .
✓ inf : Used for infinity.
✓ i : Defined as −1, which is: 0 + 1.0000i.
✓ j Same as i.
✓ eps: The smallest difference between two numbers. Equal
to 2^(–52), which is approximately 2.2204e–016.
✓ NaN : Stands for Not-a-Number. Used when MATLAB
cannot determine a valid numeric value. Example: 0/0.
Predefined Variables and Keywords
✓ The predefined variables can be redefined to have any other
value.
✓ The variables pi, eps, and inf, are usually not redefined since
they are frequently used in many applications.
✓ Other predefined variables, such as i and j, are sometime
redefined (commonly in association with loops) when complex
numbers are not involved in the application.
Useful Commands for Managing Variables
OutcomeCommand
Removes all variables from the memory.clear
Removes only variables x, y, and z from the
memory.
clear x y z
Displays a list of the variables currently in
the memory
who
Displays a list of the variables currently in
the memory and their sizes together with
information about their bytes and class
whos
Example 1
Script Files
✓ A script file is a sequence of MATLAB commands, also called a
program.
✓ When a script file runs (is executed), MATLAB executes the
commands in the order they are written, just as if they were
typed in the Command Window.
✓ When a script file has a command that generates an output
(e.g., assignment of a value to a variable without a semicolon
at the end), the output is displayed in the Command Window.
✓ Using a script file is convenient because it can be edited
(corrected or otherwise changed) and executed many times.
✓ Script files are also called M-files because the extension .m is
used when they are saved.
Script Files
✓ The rules for naming a script file follow the rules of naming a variable
(must begin with a letter, can include digits and underscore, no spaces, and
up to 63 characters long).
✓ The names of user-defined variables, predefined variables, and MATLAB
commands or functions should not be used as names of script files.
Geometry and trigonometry
Example 2
Example 2
The Law of Cosines
Example 2
Example 2
Example 2