Download presentation
Presentation is loading. Please wait.
1
Computational Methods
CSE 551 Computational Methods 2018/2019 Fall Chapter 2 MATLAB Basics
2
Outline Introduction MATLAB as a Calculator Variables and Assignment Statement Arrays Subarrays Special Values Displaying Output Data Data Files Arrays and Matrix Operations Build-in MATLAB Functions Debugging MATLAB Programs
3
Introduction MATLAB (short for MATrix LABoratory) special-purpose computer program optimized to perform engineering and scientific calculations. started to perform matrix mathematics over the years - a flexible computing system The The MATLAB program implements the MATLAB programming language a very extensive library of predefined functions to make technical programming tasks easier and more efficient
4
References Chapman S. J., MATLAB Programming for Engineers, 5th ed., CENGAGE Learning Attaway S., MATLAB:A Practical Introduction to Programming and Problem Solving, 4th ed., ELSEVIER BH
5
Advantages and Disadvantages of MATLAB
Ease of Use Platform Independence Predefined Functions Device-Independent Plotting Graphical User Interface MATLAB Compiler: divice independent p-code Disadvantages: an interpreated language cost
6
The MATLAB Environment
several types of windows: Command Windows: commands may be entered; Figure Windows: display plots and graphs Edit Windows: permit a user to create and modify MATLAB programs.
7
The default MATLAB desktop
The default MATLAB desktop. The exact appearance of the desktop may differ slightly on different types of computers.
8
Tools within MATLAB Dasktop
The major tools within or accessible from the MATLAB desktop are The Command Window The Command History Window The Start Button The Documents Window, including the Editor/Debugger and the Array Editor Figure Windows Workspace Browser Help Browser Path Browser
9
MATLAB as a Calculator MATLAB can be used as a calculator to perform mathematical calculations typed directly into the Command Window using the symbols +, –, *, /, and ^ (exponentiation) e.g., to calculate the volume of a cylinder of radius r and length l The area of the circle at the base of the cylinder is given by A = r 2 and the total volume of the cylinder: V = Al If the radius is 0.1 m and the length is 0.5 m,
10
» A = pi * 0.1^2 A = 0.0314 » V = A * 0.5 V = 0.0157 Note that pi is predefined to be the value
11
Variables and Assignment Statement
variable - store a value assignment statement variablename = expression >> mynum = 6 mynum = 6 >>
12
suppressing the output
Putting a semicolon at the end of a statement suppresses the output. >> res = 9 – 2; >> it just doesn’t show that result. Instead, another prompt appears immediately. However, at this point in the Workspace Window the variables mynum and res can be seen
13
Default variable ans MATLAB uses a default variable named ans if an expression is typed at the prompt and not assigned to a variable e.g., the result of the expression 6+3 is stored in the variable ans: >> 6 + 3 ans = 9 This default variable is reused any time just an expression is typed at the prompt.
14
Variable Names variables – identifiers Rules for identgifier names: 1 - must begin with a letter After that can contain letters, digits, and the underscore character (e.g., value_1), but it cannot have a space 2 - There is a limit to the length of the name; the built-in function namelengthmax tells how many characters this is 3 – MATLAB is case sensitive
15
Variable Names (cont.) 4 - reserved words that cannot be used as variable name 5 - Names of built-in functions can, but should not, be used as variable names 6 – Conventions i – use underscore: exchange_rate ii – Java, C++ convension: exchangeRate
16
Arrays fundamental unit of data – array collection of data values organized into rows and columns and known by a single name Individual data values within an array may be accessed
17
Vectors ands Matices Individual data values within an array accessed by name of the array followed by subscripts in parentheses (row,column) scalars – arrays - one row and one column Arrays - vectors or matrices. “vector” - an array with only one dimension “matrix” - an array with two or more dimensions. The size of an array - # of rows and # of columns # of rows mentioned first
18
Examples
20
Vectors Individual array elements are addressed by the array name followed by the row and column of the element for row or column vectors - only one subscript is required e.g., in the preceding arrays a(2,1) is 3 and c(2) = 2. A MATLAB variable - region of memory containing an array refered by a user-specified name contents of the array may be used or modified
21
Common Types common types of MATLAB variables - double and char. double - scalars or arrays of 64-bit double-precision floating-point numbers can hold real, imaginary, or complex values. in the range to with 15 to 16 significant decimal digits of accuracy. double - the principal numerical data type.
22
imaginary number - appending the letter i or j to a number 10i and –4j
double Type variable type double automatically created whenever a numerical value is assigned to a variable name real, imaginary, or complex var = 10.5 imaginary number - appending the letter i or j to a number 10i and –4j var = 4i complex value var = i
23
char Type Variables of type char consist of scalars or arrays of 16-bit values, each representing a single character. Arrays of this type are used to hold character strings. e.g., comment will be a character array. comment = 'This is a character string'
24
Strongly and Weakly typed languages
In a strongly typed language, the type of every variable must be explicitly declared before it is used. MATLAB - weakly typed language Variables may be created at any time by simply assigning values to them, the type of data assigned to the variable determines the type of variable
25
MATLAB variables are automatically created when they are initialized. :
1. Assign data to the variable in an assignment statement. 2. Input data into the variable from the keyboard. 3. Read data from a file.
26
assign it one or more values assignment statement. var = expression;
scalar constant an array combination of constants, other variables, and mathematical operations var = 40i; var2 = var/5; x = 1; y = 2; array = [ ];
27
variables can be initialized with arrays of data.
constructed using brackets ([]) and semicolons. All of the elements of an array are listed in row order. the values in each row are listed from left to right, with the topmost row first and the bottommost row last. Individual values within a row - separated by blank spaces or commas the rows - separated by semicolons or new lines.
28
Clearing Variables
29
The number of elements in every row must be the same
the number of elements in every column must be the same. An expression such as [1 2 3; 4 5]; is illegal
30
The expressions used to initialize arrays can include algebraic operations and all of or portions of previously defined arrays e.g., a = [0 1+7]; b = [a(2) 7 a]; will define an array a [0 8] b [ ].
31
not all of the elements in an array must be defined when it is created.
If a specific array element is defined and one or more of the elements before it are not then the earlier elements will automatically be created and initialized to zero e.g., c(2,3) = 5; will produce the matrix c =
32
an array can be extended by specifying a value for an element beyond the currently defined size.
suppose that array d [1 2] the statement d(4) = 4; will produce the array d [ ]
33
Initilizing with Shortcut Expressions
for large arrays: the colon operator. specifies a whole series of values The general form of a colon operator is first:incr:last first: first value in the series incr: stepping increment last: last value in the series. If the increment is one, it may be omitted generate an array containing the values first, first+incr, first+2*incr, first+3*incr, and so forth as long as the values are less than or equal to last. The list stops when the next value in the series is greater than the value of last.
34
An Example the expression 1:2:10 - shortcut for a 1 x 5 row vector containing the values 1, 3, 5, 7, and 9. The next value in the series would be 11, which is greater than 10, so the series terminates at 9. » x = 1:2:10 x =
35
Shortcut expressions can be combined with the transpose operator (')
to initialize column vectors and more complex matrices. The transpose operator swaps the row and columns of any array that it is applied to. Thus the expression f = [1:4]'; generates a 4-element row vector [ ] then transposes it into the 4-element column vector f.
36
Example the expressions g = 1:4; h = [g' g']; will produce the matrix h
37
Initilizing with Build-in Functions
zeros function - create an all-zero array of any size. single scalar argument - a square array two scalar arguments – first: # of rows, second: # of columns size function returns two values: # of rows and columns in an array combined with the zeros function ones function - arrays containing all ones eye function - arrays containing identity matrices
38
Examples a = zeros(2); b = zeros(2,3); c = [1 2; 3 4]; d = zeros(size(c)); These statements generate the following arrays:
39
list of common MATLAB functions for initializing variables.
40
Initilizing Variables with Keybord Input
input function displays a prompt string in the Command Window and then waits for the user to type in a response. my_val = input('Enter an input value:'); If enters a single number - be typed in If enters an array – enclosed in brackets If only the return key is entered - an empty matrix
41
Multidimensional Arrays
One dimensional arrays - series of values laid out row or column – single subscript - select individual array elements MATLAB - arrays with as many dimensions as necessary one subscript for each dimension,
43
Example » c(:,:,1)=[1 2 3; 4 5 6]; » c(:,:,2)=[7 8 9; 10 11 12];
» whos c Name Size Bytes Class Attributes c 2x3x2 96 double » c c(:,:,1) = 1 2 3 4 5 6 c(:,:,2) = 7 8 9
44
Storing Arrays in Memory
A two-dimensional array m rows, n columns m x n successive locations in the computer’s memory MATLAB always allocates array elements in column major order. allocates the first column in memory then the second, then the third, and so on., e.g., element a(1,2) - fifth element allocated in memory single-subscript addressing low-level I/O functions
45
Data values for array a. (b) Layout of values in memory for array a.
46
Storing Arrays with More Then TWo Dimensions
This same allocation scheme applies to arrays with more than two dimensions. The first array subscript is incremented most rapidly, the second subscript is incremented less rapidly, and so on, and the last subscript in incremented most slowly. e.g., in a 2 x 2 x 2 array, the elements would be allocated in the following order: (1,1,1), (2,1,1), (1,2,1), (2,2,1), (1,1,2), (2,1,2), (1,2,2), (2,2,2)
47
Accessing Multidimensional Arrays with One Dimension
MATLAB permit treat a multidimensional array - a one-dimensional array length = # of elements in the multidimensional array. If a MDA addressed with a single dimension, then the elements accessed: in the order in which they were allocated in memory.
48
Example a :4 x 3 » a = [1 2 3; 4 5 6; 7 8 9; ] a = value of a(5) is 2 - value of element a(1,2), a(1,2) allocated fifth in memory.
49
Subarrays possible to select and use
subsets of MATLAB arrays as if separate arrays To select a portion of an array just include a list of all of the elements to be selected in the parentheses after the array name. e.g., array arr1: arr1 = [ ]; arr1(3): 3.3 arr1([1 4]): array [ ] arr1(1:2:5): array [ ].
50
Examples For a two-dimensional array a colon can be used in a subscript to select all of the values of that subscript. e.g., arr2 = [1 2 3; ; 3 4 5]; arr2(1,:): [1 2 3] arr2(:,1:2:3):
51
The end Function end functrion:creating array subscripts. in an array subscript - end returns the highest value taken on by that subscript e.g., arr3: arr3 = [ ]; arr3(5:end): [ ] array(end): value 8.
52
The value returned by end - the highest value of a given subscript.
Example The value returned by end - the highest value of a given subscript. If end appears in different subscripts, it can return different values e.g., arr4: arr4 = [ ; ; ]; arr4(2:end,2:end): the first end returned the value 3 the second end returned the value 4
53
Using Subarrays on the Left-Hand Side of an Assignment Statement
It is possible to use subarrays on the left-hand side of an assignment statement to update only some of the values in an array, as long as the shape ( # of rows and columns) of the values being assigned matches the shape of the subarray. If the shapes do not match, an error will occur.
54
Example » arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12] arr4 = 1 2 3 4 5 6 7 8
following assignment statement is legal, since the expressions on both sides of the equal sign have the same shape : » arr4(1:2,[1 4]) = [20 21; 22 23] the array elements (1,1), (1,4), (2,1), and (2,4) were updated
55
Example (cont.) In contrast, the following expression is illegal because the two sides do not have the same shape. » arr5(1:2,1:2) = [3 4] ??? In an assignment A(matrix,matrix) = B, the number of rows in B and the number of elements in the A row index matrix must be the same.
56
Difference Between Arrays and Subarrays
major difference in MATLAB between assigning values to a subarray and assigning values to an array. If values are assigned to a subarray, only those values are updated while all other values in the array remain unchanged. if values are assigned to an array, the entire contents of thearray are deleted and replaced by the new values.
57
Example arr4 » arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12] arr4 = 1 2 3 4
the following assignment statement replaces the specified elements of arr4: » arr4(1:2,[1 4]) = [20 21; 22 23] the following assignment statement replaces the entire contents of arr4 with a array: » arr4 = [20 21; 22 23] 20 21 22 23:
58
Assigning a Scaler to a Subarray
A scalar value on the right-hand side of an assignment statement always matches the shape specified on the left-hand side. The scalar value - copied into every element specified on the left-hand side of the statement. e.g., arr4 : arr4 = [ ; ; ]; one is assigned to four elements of the array. » arr4(1:2,1:2) = 1 arr4 =
59
Special Values predefined special values.
may be used at any time in MATLAB without initializing them first stored in ordinary variables, so they can be overwritten or modified e.g.,: circ1 = 2 * pi * 10 pi = 3; circ2 = 2 * pi * 10 In the first statement, pi has its default value of , so circ1: 62.8 The second statement redefines pi as 3, so in the third statement circ2 is 60
60
Predefined Special Values
61
Displaying Output Data
several ways to display output data: simplest way: leave the semicolon off of the end of a statement and it will be echoed to the Command Window a few other ways to display data: Changing the Default Format The disp Function The fprintf Function
62
Changing the Default Format
When data is echoed in the Command Window, integer values displayed as integers character values as strings other values are printed using a default format default format four digits after the decimal point it may be displayed in scientific notation with an exponent if the number is too large or too small
63
Example x = y = z = output: x = y = 1.0011e+003 z = 1.0011e-004
64
Changing Default Format
default format - changed two ways: from the main MATLAB Window menu: by selecting the “File / Preferences” menu option. pop up the preferences window the format can be selected from the Command Window item in the preferences list. using the format command
65
changes the default format
format Command changes the default format to display more significant digits of data to force the display to be in scientific notation; to display data to two decimal digits to eliminate extra line feeds to get more data visible in the Command Window at a single time.
66
Output Display Formats
67
The disp Function disp function: accepts
an array argument and displays the value of the array in the Command Window array type – char: the character string contained in the array is printed out. often combined with the functions num2str (convert a number to a string) int2str (convert an integer to a string) e.g., the following MATLAB statements will display “The value of pi ” first statement creates a string array containing the message second statement displays the message. str = ['The value of pi = ' num2str(pi)]; disp (str);
68
Formated Output with the fprintf Function
fprintf function: more flexible way to display data displays one or more values together with related text the programmer can control the way that the displayed value appears general form - print to the Command Window: fprintf(format,data) where format: a character string describing the way the data is to be printed containing text to be printed plus special characters describing the format of the data data: one or more scalars or arrays to be printed
69
fprintf('The value of pi is %f \n',pi) prints out
An Example fprintf('The value of pi is %f \n',pi) prints out The value of pi is followed by a line feed %f - conversion characters a value in the data list should be printed out in floating-point format at that location in the format string. \n - escape characters a line feed should be issued A
70
fprintf('The value of pi is %6.2f \n',pi) print out:
specify width of the field - a number will be displayed # of decimal places to display specifying the width and precision after the % sign and before the f. e.g., fprintf('The value of pi is %6.2f \n',pi) print out: The value of pi is 3.14 followed by a line feed The conversion characters %6.2f the first data item in the function - in floating-point format in a field six characters wide including two digits after the decimal point.
71
Limitation of fprintf Function
displays only the real portion of a complex value use the disp function e.g., following statements calculate a complex value x and display it using both fprintf and disp. x = 2 * ( 1 - 2*i )^3; str = ['disp: x = ' num2str(x)]; disp(str); fprintf('fprintf: x = %8.4f\n',x); output: disp: x = -22+4i fprintf: x =
72
Common Special Characters in fprintf Format Strings
73
Data Files many ways to load and save data files in MATLAB the simplest ones to use load and save commands
74
saves data from the current MATLAB workspace into a disk file
The save Command saves data from the current MATLAB workspace into a disk file The most common form: save filename var1 var2 var3 filename: name of the file where the variables are saved var1, var2, etc: variables to be saved in the file By default, the file name extension “mat,” – MAT-files If no variables are specified the entire contents of the workspace are saved
75
MATLAB saves MAT-files in a special compact format that preserves
many details, including the name and type of each variable, the size of each array, and all data values A MAT-file created on any platform (PC, Mac, Unix, or Linux) can be read on any other platform, so MAT-files are a good way to exchange data between computers if both computers run MATLAB. Unfortunately, the MAT-file is in a format that cannot be read by other programs. If data must be shared with other programs, then the -ascii option should be specified, and the data values will be written to the file as ASCII character strings separated by spaces. However, the special information such as variable names and types are lost when the data is saved in ASCII format, and the resulting data file will be much larger
76
Example For example, suppose the array x is defined as
the command: “save -ascii x.dat x” will produce a file named x.dat containing the following data: e e e+000 e e e+000 This data is in a format that can be read by spreadsheets or by programs written in other computer languages, so it makes it easy to share data between MATLAB programs and other applications.
77
MATLAB doesn’t care what file extension is used for ASCII files
MATLAB doesn’t care what file extension is used for ASCII files. However, it is better for the user if a consistent naming convention is used, and an extension of “dat” is a common choice for ASCII files.
78
The load Command loads data from a disk file into the current MATLworkspace most common form: load filename for MAT-file: all of the variables in the file will be restored, with the names and types If a list of variables is included only those variables will be restored If filename has no extent or extent is .mat – treat the file as a MAT-file
79
can load data created by other programs in
comma- or spaceseparated ASCII format If the filename extension - other than .mat treat the file - ASCII file The contents of an ASCII file - converted into a MATLAB array - same name as the file (without the file extension) e.g., an ASCII data file named x.dat - load x.dat create a array - x - in the current workspace, containing these data values.
80
forced to treat a file as a MAT-file load –mat x.dat
by specifying the –mat option load –mat x.dat treat file x.dat as a MAT-file even though its file extent is not .mat. can be forced to treat a file as an ASCII file by specifying the –ascii option.
81
Scaler and Array Operations
an assignment statement: variable_name = expression; the equal sign - the assignment operator scaler operations array and matrix operations
82
Scaler Operations expression - any valid combination of scalars, array elements, parentheses, and arithmetic operators 2 ^ ((8+2)/5) is evaluated as = 2 ^ (10/5) = 2 ^ 2 = 4
83
Arithmetic Operations Between Two Scalars
84
Array and Matrix Operations
two types of operations between arrays: array operations and matrix operations. Array operations: performed between arrays on an element-by-element basis. on corresponding elements in the two arrays e.g., # of rows and columns in both arrays must be the same. If not, MATLAB will generate an error message.
85
Array operations - between an array and a scalar. e.g.,
value of the scalar is applied to every element of the array. e.g.,
86
Matrix Operations follow the normal rules of linear algebra, matrix multiplication: c = a x b: # of columns in matrix a must be equal to # of rows in matrix b.
87
a special symbol - distinguish array operations from matrix operations
a period before the symbol to indicate an array operation e.g., .* square matrices. of the same size - both array multiplication and matrix multiplication - legal give totally different answers
88
Example What is the result of each of the following expressions? (a) a + b (e) a + c (b) a .* b (f ) a + d (c) a * b (g) a .* d (d) a * c (h) a * d
89
Solution
90
Solution (cont.)
91
Common Array and Matrix Operations
92
Common Array and Matrix Operations (cont.)
93
Matrix Left Division Pperator
matrix left division operation A 3 x 3 set of simultaneous linear equations: expressed as can be solved for x = A-1b
94
Hierarchy of Operations
To make the evaluation of expressions unambiguous a series of rules governing the hierarchy or order in which operations are evaluated generally follow the normal rules of algebra.
95
Hierarchy of Arithmetic Operations
96
Built-in MATLAB Functions
In mathematics, a function is an expression that accepts one or more input values and calculates a single result from them Optional Results: MATLAB functions can return more than one result. e.g., function max. normally returns the maximum value of an input vector, it can also return a second argument: location in the input vector where the maximum value was found
97
An Example maxval = max ([1 –5 6 –3]) returns maxval = 6 if two variables are provided to store results in, returns both the maximum value and the location of the maximum value. [maxval index] = max ([1 –5 6 –3]) maxval = 6 , index = 3
98
Using MATLAB Functions with Array Inputs
Many MATLAB functions - one or more scalar inputs produce a scalar output y = sin(x) stores the result in y If receive an array of input values calculate an array of output values on an element-by-element basis if x = [ 0 pi/2 pi 3*pi/2 2*pi] the result: y = [0 1 0 –1 0].
99
Common MATLAB Functions
many MATLAB functions work correctly for both real and complex inputs sqrt(-2) MATLAB imaginary answer: ans = i
103
Debugging MATLAB Programs
Three types of error: syntax error run-time error logical error
104
Syntax Errors errors in the MATLAB statements
spelling errors or punctuation errors detected by the MATLAB compiler x = (y + 3) / 2); in an M-file - test.m when executed: » test ??? x = (y + 3) / 2) | Missing operator, comma, or semi-colon. Error in ==> d:\book\matlab\chap1\test.m On line 2 ==>
105
cause the program to return Inf or NaN
Run Time Errors occurs when an illegal mathematical operation is attempted during program execution e.g., attempting to divide by 0 cause the program to return Inf or NaN then used in further calculations The results of a program that contains calculations using Inf or NaN are usually invalid
106
Logical Errors occur when the program compiles and runs successfully but produces the wrong answer
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.