44
MatLAB 1

MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Embed Size (px)

Citation preview

Page 1: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

MatLAB

1

Page 2: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined as the usual 3.1416. inf is used for infinity and eps is used for the smallest difference between two numbers or 2^(-52) (epsilon). These variables can be assigned other values but it is not recommended.

ans: the value of the last expression that was not assigned to a variable.

NaN or nan: not-a-number. Used to express mathematically undefined values, such as 0/0.

Predefined Variables

Page 3: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

inf is used for infinity,

Infinity results from operations like division by zero and overflow, which lead to results too large to represent as conventional floating-point values.

log(0) produces -Inf. Inf-Inf and Inf/Inf both produce NaN (Not-a-Number).

NOTE!

Page 4: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

The clear and whos CommandsYou can remove a variable from MATLAB's memory by clearing it (clear x). Clearing a predefined variable will restore its default value (clear pi). clear by itself removes all variables.whos reports the names and dimensions of all variables currently in MATLAB's memory. who only reports the variable names.>> whos Name Size Bytes Class x 1x1 8 double arrayGrand total is 1 element using 8 bytes

Page 5: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

who lists in alphabetical order all variables in the currently active workspace.Display information about variables in the current workspace whose names start with the letter a:who a*

whos displays in alphabetical order all variables in the currently active workspace, with information about their sizes and types.>> whos Name Size Bytes Class Attributes

a 1x1 8 double b 1x1 8 double c 1x1 8 double x 1x1 8 double

NOTE!

Page 6: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

So far, we have run MATLAB commands by typing in single command, pressing ENTER, getting MATLAB’s result, and then repeating this process for next command.

It is not practical for calculations involving more than a few commands. We can use the up and down arrow keys to avoid lots of typing, but still it is not practical.

MATLAB Programming

Page 7: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

There is a better solution:

We save all the commands in a file, and then with one command in the command window, we tell MATLAB to run all the commands in the file.

We will use script files to do this. That is called programming.

MATLAB Programming

Page 8: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

A script file is a sequence of MATLAB commands, also called a program.

When a script file runs (is executed), MATLAB performs 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 semicolon at the end), the file displays the output in the command window. Applies to all similar commands.

MATLAB Programming

Page 9: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Using a script file is convenient because it can be edited (corrected and/or changed) and executed many times.

Script files can be typed and edited in any text editor and then pasted into the MATLAB editor.

Script files are also called M-files because the extension .m is used when they are saved.

MATLAB Programming

Page 10: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Use the Editor/Debugger Window to work with script files

Can open window and create file two ways

1. File|New|Script – this means select the File menu, then the New menu item, then the Script menu item

2. In the Command Window, type edit and then press ENTER

MATLAB Programming

Page 11: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Type in the commands line-by-line, pressing ENTER after each one

MATLAB automatically numbers the lines.

Figure 1-6: The Editor/Debugger Window

line number

Creating and saving a script file

Page 12: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Comment lines are lines that start with percent sign (%).

It is common for first few lines to be comments and to briefly explain what commands in file do.

Editor/Debugger Window shows the comment lines in green.

Creating and saving a script file

Page 13: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Before MATLAB can run commands in a file, you must save the file. If you haven’t named file yet, select File|Save As… , type in a name, press Save.

If you’ve already named and saved file, just use File|Save.

If you don’t add an extension (.xxx) to the file name, MATLAB adds “.m” (if you name your file fred, the file will appear as fred.m on your disk).

Rules for file names are same as rules for function names.

Don’t use names of your variables, predefined variables, MATLAB commands, or MATLAB functions.

Creating and saving a script file

Page 14: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

To execute a script file means to run all of the commands in it. You can execute a file by pressing the Run icon (a green arrow) or by typing the file name in the command window and pressing ENTER (if you don't see anything, try moving the command window out of the way).

MATLAB will execute file if it is in MATLAB’s current folder or if the file’s folder is in the search path (explained next).

To reopen an existing file to make changes just use the edit command. If the file is named fred.m, just enter edit fred.

Executing a script file

Page 15: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

The current folder is the folder that MATLAB checks first when looking for your script file.

Can see current folder in desktop toolbar in Command Window (Figure 1-8).

Can also display current folder by issuing MATLAB command pwd.

Page 16: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

You can change the current folder in Current Folder Window (see Figure 1-10).

Get Current Folder Window from Desktop|Current Folder.

Page 17: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

You can change the current folder from command line using cd command, space, new folder name in single quote marks, ENTER, i.e.,

>> cd 'new folder'

For example,

>> cd 'F:\slides\Chapter 1'

Current Folder

Page 18: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Manipulating MATLAB

Vector, Matrices

18

Page 19: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Command Window• The Command Window in the center is the main

panel where you interact with MATLAB. • You key (or type) and <Enter> commands after

the prompt >>; MATLAB executes the commands and displays results (if requested).

• Some commonly used tools and commands:– (up arrow) returns last command input, can be

repeated– clc – clears the screen– whos – shows list of variables– clear – clears variables

19

Page 20: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Evaluation of MATLAB

– Type>> 5+7 <Enter>

into the Command Window>> clc <Enter>>> whos <Enter>

20

Page 21: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Command History Window

• The Command History Window logs all of the commands you enter in MATLAB.

• It should have logged 5+7.

Use the Command History Window to reenter 5+7 in the command window (use copy-and- paste or double click on 5+7).

• This is useful to retrieve past commands.• Use “Shift” key to select multiple lines.

21

Page 22: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Write a Simple Program • Consider computing the volume of a cone:

Volume = (pi.*r.^2.*h)./3radius = 3 inchesheight = 12 inches

• In the command window key in:>> clear; clc <Enter>>> r = 3 <Enter>>> h = 12 <Enter>>> v = (pi.*r.^2.*h)./3 <Enter>>> whos <Enter>

22

Page 23: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Editor & M-Files

• An M-file in MATLAB is analogous to a txt-file in Microsoft Notepad.

• An M-file is created in MATLAB text editor.• M-files:

– You can save your programs (i.e., list of executable commands) as M-files.

– You can reopen and modify your program.– They are useful for “debugging” (correcting

errors) as you develop your programs (your technical computing tools).

23

Page 24: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Art of well written code

• A well-written program is like literature; it contains comments explaining:– what your program requires as input.– what the variables in the program represent.– what your program computes and displays.

• It is useful for you to add a set of header comments that include the name of the program, your name (as the programmer), and the date the program was created or modified.

24

Page 25: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

This is cone.m in the editor

%% Tool to compute the volume of a cone.% A simple sample for a first lecture. % A simple code for cps118

ra = 3; % radius of the coneh = 12; % height of the conev = (pi*r^2*h)./3 % Volume of the cone

25

Page 26: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Execute an M-file• Now execute (or run) the program by pushing

F5, or by typing on the command line >> cone <Enter>– or by clicking the run button. (Note that the run button looks

like a page with a green triangle in it. It can be found on the toolbar of the edit window.)

• If you entered the code as written on the previous slide you will get an error!

• What went wrong?• Repair your program (Change ra = 3 to r = 3.), save it,

and run it again.

26

Page 27: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Variables and Arrays

• What are variables?– You name the variables (as the programmer) and

assign them numerical values.– You execute the assignment command to place

the variable in the workspace memory (memory is part of hardware used for storing information).

– You are allowed to use the variable in algebraic expressions, etc. once it is assigned.

27

Page 28: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

An array is MATLAB's basic data structure.

• Can have any number of dimensions. Most common are:

vector - one dimension (a single row or column)

matrix - two or more dimensions

• Arrays can have numbers or letters.

(Arrays)

28

Page 29: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

In MATLAB, a variable is stored as an array of numbers. When appropriate, it is interpreted as a scalar, vector or matrix.

The size of an array is specified by the number of rows and the number of columns in the array, with the number of rows indicated first.

Variables as ArraysVariables as Arrays

scalar1 × 1

vectorn × 1 or 1 × n

matrixn × m

29

Page 30: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Manipulating MATLAB

Vector, Matrices

30

Page 31: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Variables and Arrays

• What are variables?– You name the variables (as the programmer) and

assign them numerical values.– You execute the assignment command to place

the variable in the workspace memory (memory is part of hardware used for storing information).

– You are allowed to use the variable in algebraic expressions, etc. once it is assigned.

31

Page 32: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

An array is MATLAB's basic data structure.

• Can have any number of dimensions. Most common are:

–vector - one dimension (a single row or column)

–matrix - two or more dimensions

• Arrays can have numbers or letters.

(Arrays)

32

Page 33: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

In MATLAB, a variable is stored as an array of numbers. When appropriate, it is interpreted as a scalar, vector or matrix.

The size of an array is specified by the number of rows and the number of columns in the array, with the number of rows indicated first.

Variables as ArraysVariables as Arrays

scalar1 × 1

vectorn × 1 or 1 × n

matrixn × m

33

Page 34: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

• Scalars are 1×1 arrays.• They contain a single value, for example:

• X=3• Height=5.34• Width=10.09

Scalars

34

Page 35: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

Vectors

• A vector is a list of numbers expressed as a 1 dimensional array.

• A vector can be n×1 or 1×n.• Columns are separated by commas (or spaces):• x = [1, 2, 3] or x = [1 2 3]

• Rows are separated by semicolons:• y= [1; 2; 3]

35

Page 36: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

To create a row vector from known numbers, type variable name, then equal sign, then inside square brackets, numbers separated by spaces.

variable_name = [ n1, n2, n3 ]

>> yr = [1984 1986 1988 1990 1992 1994 1996]

yr =

1984 1986 1988 1990 1992 1994 1996

Note MATLAB displays row vector horizontally

Commas optional

(Creating a row vector)

36

Page 37: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

To create a column vector from known numbers

• Method 1 - same as row vector but put semicolon after all but last number

variable_name = [ n1; n2; n3 ]

>> yr = [1984; 1986; 1988 ]

yr =

1984

1986

1988

Note: MATLAB displays column vector vertically

(Creating a Column Vector)

37

Page 38: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

• Method 2 - same as row vector but put apostrophe (') after closing bracket.

– Apostrophe interchanges rows and columns. Will come back on this later.

variable_name = [ n1 n2 n3 ]'

>> yr = [1984 1986 1988 ]'

yr =

1984

1986

1988

(Creating a column vector)

38

Page 39: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

To create a vector with specified constant spacing between elements

variable_name = m:q:n

• m is the first number

• n is the last number

• q is the difference between consecutive numbers

v = m:q:n

meansv = [ m m+q m+2q m+3q ... n ]

(Constant spacing vectors)

39

Page 40: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

If q is omitted, the spacing is 1

v = m:n

meansv = [ m m+1 m+2 m+3 ... n ]

>> x = 1:2:13x = 1 3 5 7 9 11 13>> y = 1.5:0.1:2.1y = 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.1000

Non-integer spacing

(Constant spacing vectors)

40

Page 41: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

>> z = -3:7

z = -3 -2 -1 0 1 2 3 4 5 6 7

>> xa = 21:-3:6

xa = 21 18 15 12 9 6

>> fred = 7:-2:15

fred = Empty matrix: 1-by-0

Negative spacing

(Constant spacing vectors)

Impossible spacing

41

Page 42: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

1. How would you use linspace to set up spacings for planting seedlets in a garden row (30 seedlets, each row 2 meters long).

2. How about planning a 4285km road trip on 21 days. How long each leg would be?

(Quick linspace Exercises)

42

Page 43: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

To create a vector with specified number of terms between first and last

v = linspace( xi, xf, n )

• xi is first number

• xf is last number

• n is the number of terms (obviously must be a positivenumber) (= 100 if omitted)

(Fixed length vectors)

43

Page 44: MatLAB 1. There are a few predefined variables in MATLAB that you will use often. Both i and j are defined to be the square root of -1 and pi is defined

>> va = linspace( 0, 8, 6 )

va = 0 1.6000 3.2000 4.8000 6.4000 8.0000

>> va = linspace( 30, 10, 11 )

va=30 28 26 24 22 20 18 16 14 12 10

m:q:n lets you directly specify spacing. linspace() lets you directly specify number of terms.

Six elements

Decreasing elements

T I P

44