Chapter 1 Starting with MATLAB

52
Chapter 1 Starting with MATLAB Computer Programming ECIV 2303 Civil Engineering Department Prof. Mohammed Arafa

Transcript of Chapter 1 Starting with MATLAB

Page 1: Chapter 1 Starting with MATLAB

Chapter 1Starting with MATLAB

Computer ProgrammingECIV 2303

Civil Engineering DepartmentProf. Mohammed Arafa

Page 2: Chapter 1 Starting with MATLAB

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.

Page 3: Chapter 1 Starting with MATLAB

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.

Page 4: Chapter 1 Starting with MATLAB

➢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:

Page 5: Chapter 1 Starting with 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

Page 6: Chapter 1 Starting with 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

Page 7: Chapter 1 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

) 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

Page 8: Chapter 1 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

Page 9: Chapter 1 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

Page 10: Chapter 1 Starting with MATLAB

Starting MATLAB, MATLAB Windows (R20013a)C

urr

ent

Fold

erW

ind

ow

Workspace Window

Store allVariables

Command History Window

Command Window

Page 11: Chapter 1 Starting with MATLAB

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

Page 12: Chapter 1 Starting with MATLAB

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

Page 13: Chapter 1 Starting with MATLAB

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

MATLAB windows

Page 14: Chapter 1 Starting with MATLAB

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

MATLAB windows

Page 15: Chapter 1 Starting with MATLAB

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

Page 16: Chapter 1 Starting with MATLAB

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

Page 17: Chapter 1 Starting with MATLAB

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

Page 18: Chapter 1 Starting with MATLAB

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

Page 19: Chapter 1 Starting with MATLAB

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 20: Chapter 1 Starting with MATLAB

➢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

Page 21: Chapter 1 Starting with MATLAB

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

Page 22: Chapter 1 Starting with MATLAB

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

Page 23: Chapter 1 Starting with MATLAB

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

Page 24: Chapter 1 Starting with MATLAB

Symbols for Arithmetic Operations

Page 25: Chapter 1 Starting with MATLAB

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

Page 26: Chapter 1 Starting with MATLAB

Order in which MATLAB does arithmetic

Page 27: Chapter 1 Starting with MATLAB

Order in which MATLAB does arithmetic

Page 28: Chapter 1 Starting with MATLAB

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

Page 29: Chapter 1 Starting with MATLAB

Display Format

Page 30: Chapter 1 Starting with MATLAB

Display Format

Page 31: Chapter 1 Starting with MATLAB

Elementary Math built-in Functions

Page 32: Chapter 1 Starting with MATLAB

Elementary Math built-in Functions

Page 33: Chapter 1 Starting with MATLAB

Elementary Math built-in Functions

Page 34: Chapter 1 Starting with MATLAB

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).

Page 35: Chapter 1 Starting with MATLAB

Elementary Math built-in Functions

Page 36: Chapter 1 Starting with MATLAB

Elementary Math built-in Functions

Page 37: Chapter 1 Starting with MATLAB

Variable_ name = A numerical value, or a computableexpression

The Assignment Operator

Page 38: Chapter 1 Starting with MATLAB

The Assignment Operator

Page 39: Chapter 1 Starting with MATLAB

The Assignment Operator

Page 40: Chapter 1 Starting with MATLAB

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.

Page 41: Chapter 1 Starting with MATLAB

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

Page 42: Chapter 1 Starting with MATLAB

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.

Page 43: Chapter 1 Starting with MATLAB

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.

Page 44: Chapter 1 Starting with MATLAB

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

Page 45: Chapter 1 Starting with MATLAB

Example 1

Page 46: Chapter 1 Starting with MATLAB

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.

Page 47: Chapter 1 Starting with MATLAB

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.

Page 48: Chapter 1 Starting with MATLAB

Geometry and trigonometry

Example 2

Page 49: Chapter 1 Starting with MATLAB

Example 2

Page 50: Chapter 1 Starting with MATLAB

The Law of Cosines

Example 2

Page 51: Chapter 1 Starting with MATLAB

Example 2

Page 52: Chapter 1 Starting with MATLAB

Example 2