1.04k likes | 1.55k Views
Introduction to MATLAB. INGE3016 Algorithms and Computer Programming With MATLAB Dr. Marco A. Arocha oct 25, 2007; june 12, 2012. Some facts:. MATLAB MATrix LABoratory Matrix mathematics >1000 functions. Advantages Ease of use Platform independent Predefined functions Plotting
E N D
Introduction to MATLAB INGE3016 Algorithms and Computer Programming With MATLAB Dr. Marco A. Arocha oct 25, 2007; june 12, 2012
Some facts: • MATLABMATrix LABoratory • Matrix mathematics • >1000 functions
Advantages Ease of use Platform independent Predefined functions Plotting Graphical User Interface Compiler Disadvantages Interpreted language Slower Expensive Some facts
Matrix & Array Operators To associate expressions use “( )”, i.e., regular parentheses. Do no use brackets “[ ].” Do not use “( )” or “.” or “x” to mean multiplication.
Examples >> 2+3-2*4 <E> % note the precedence order ans = -3 The division operators: >> 6/2 <E> % numerator/denominator ans = 3 >> 2\6 <E> % denominator/numerator ans = 3
Rules to construct variable and file names: • uppercase letters: A-Z (26 of them) • lowercase letters: a-z • digits: 0-9 • underscore _ • first must be a letter • any length, first 63 are significant (if more than 63 the rest will be ignored)
Rules to construct variable and file names: • No blank spaces within a name • case sensitive, unless instructed otherwise by the case function (i.e., case off) • This rules must be extended to the construction of MATLAB file names as file names can become variables filename.m Same rules as variable name
All variables are arrays • The unit of data in MATLAB is the array • A MATLAB variable is a region of memory containing an array • Array is a collection of data organized into rows and columns and known by a single name
Common Mistake Please code in MATLAB the following • Correct: y=3*x*exp(x^2)-1 • Incorrect: y=3*x*e^(x^2)-1 • Incorrect: y=3*x*exp^(x^2)-1
Scientific Notation • Math: 1x10-3 • Matlab: 1e-3 (correct) • Matlab: 1*10^-3 ( accepted by MATLAB but not accepted by the instructor; student using this approach denotes lack of knowledge of the scientific notation) • Common Mistakes: • 1xe-3 • 10e-3 • 1e^-3 • 1e*-3 • 1*e-3
Assignment Statement • The Syntax: Variable Name = Expression • The assignment statement operates assigning the value of the right-hand side expression to the left-hand side variable.
Example a=1; b=2; c=a+b; % c=3 Note: a mistake is to write a + b = c which is wrong as the compiler cannot assign the value of c to a variable named a+b.
Example a=1; a=a+1; % the new value of a in the LHS is 2 Think of the last statement as:
Quiz, your first algorithm Write a piece of program that switches the value of a and b a=1; b=3; … … fprintf(‘a=%d, b=%d’, a, b); Your statements Output should be: a = 3, b = 1
Quiz, your first algorithm Write a piece of program that switches the value of a and b a=1; b=3; a=b; b=a; fprintf(‘a=%d, b=%d’, a, b); Student first approach, is it right? Output should be: a = 3, b = 1
Given: a=1; b=3; c=5; Transfer the values of a c b a c b Quiz, apply your knowledge
Multiple Statements >>x=1; y =2; % or >>x=1, y=2; • multiple assignment statements can be placed on a single line separated by semicolons or commas
clear; clc; <ctrl><c> Commands to manage the work session in the Command Window • clear; • remove the values of all variables from memory • clear is short for clear all • clc; • clears the Command Window but the values of the variable remains [also: MATLAB edit menu: EditClear Command Window] • <ctrl><c> • stops program execution and return to editing phase
semicolon (;) command If an assignment statement is typed without the semicolon at the end, the results of the statement are automatically displayed in the command window: >> x = 5*20 % statement without the colon x = 100 Displaying partial results is an excellent way to quickly check your work (debugging), but it slows down the execution of a program. Recommendation: leave off the semicolon while debugging and use it after the program is bugs-free.
The array unitUnder the array unit in MATLAB we can store: • Scalar • 1x1 array • Vectors: 1-D arrays • Column-vector: m x 1 array • Row-vector: 1 x n array • Multidimensional arrays • m x n arrays • Also called matrices • One or more rows by one or more columns
Scalars, Vectors, Matrices • Scalars are array with only one row and one column • a = [3.4] • a = 3.4 • a is a 1x1 array (a scalar) containing the value 3.4 • Brackets are optional in this case and usually we don’t use it for 1x1 array • The only element is a(1) with a value of 3.4 Both are valid
Initializing 1-D arrays (vectors) • Vectors are one-dimension either row-vectors or column-vectors • Values are listed using brackets [ ] • Blank spaces or commas can be used to separate values Row vectors: >> prime=[2 3 5 7 13] prime = 2 3 5 7 13 >> prime=[2, 3, 5, 7, 13] prime = 2 3 5 7 13 Two choices for Array assignment Use either one
Row vectors: >> prime=[2, 3, 5, 7, 11, 13] prime = 2 3 5 7 11 13 • The elements of an array are identified by indices starting with 1 • With arrays pay attention to indices and values, they are not the same • Each value is stored in memory in the order listed as: prime(1)=2 prime(2)=3 prime(3)=5 prime(4)=7 prime(5)=11 prime(6)=13 Array elements’ indices always start in one indices values
Retrieving array elements Each element can be retrieved one by one or all at once: >> prime(1) <E> ans = 2 >> prime(2) <E> ans = 3 … >> prime(6) <E> ans = 13 >> prime <E> prime = 2 3 5 7 11 13
with individual elements: >> prime(1)*prime(2) ans = 6 >> prime(3)^2 ans = 25 >> log(prime(1)) ans = 0.6931 Or with the whole array: >> x=prime+1 x = 3 4 6 8 14 >> z=prime-2 z = 0 1 3 5 11 >> y=x+z y = 3 5 9 13 25 >> m=x.*y m = 9 20 54 104 350 prime(1)=2 prime(2)=3 prime(3)=5 prime(4)=7 prime(5)=13 Manipulating arrays After you have initialized prime all values are in memory and we can perform operations
Clearing array values • We can clear all the values previously entered with the clear function >> clear prime • If we try to retrieve the values of prime after using clear prime, an error message is found >> prime(1) ??? Undefined function or variable 'prime'.
3 2 1 Column vectors: • Rows can be separated by semicolon or new lines >> b = [3; 2; 1] <E> >> b= [3 <E> 2 <E> 1] <E> • b is a 3 x 1 array (or simply a column-vector) b
Transpose operator(‘)transpose a row-vector into a column-vector and vice verse >> x=[1 2 3]’ x = 1 2 3 >> x=[1 ;2; 3]’ x = 1 2 3 • Transpose a column vector into a row vector • Transpose a row vector into a column vector • MATLAB displays row vectors horizontally and column vectors vertically • In the examples, changes are permanent, i.e., x changed form row to column and from column to row not just on the printed output.
Colon Operator (:) The colon operator (:) can generate large row vectors of regularly spaced elements. >> x = [first:incr:last] first = first value last = last value incr = increment, if omitted, the increment is 1 Ex >> x = [0:2:8] x = 0 2 4 6 8 memory: x(1)=0 x(2)=2 x(3)=4 x(4)=6 x(5)=8
Colon Operator, examples >> x = [0:2:6] x = 0 2 4 6 >> u =[10:-2:4] u = 10 8 6 4 >> y = [1:1:4]' % combines the colon and transpose operators y = 1 2 3 4
Que sería la vida sin “:” Tres ejemplos para inicializar x con otros métodos diferentes al operador “colon” y lograr en memoria: x(1)=0 x(2)=2 x(3)=4 x(4)=6 x(5)=8 (1) x = [0 2 4 6 8] (2) j=1; for ii=0:2:8 x(j)=ii; j=j+1; end % j is the index generator % ii is the values generator (3) j=1; x(j)=0; for j=2:1:5 x(j)=x(j-1)+2; end % j generates both: % indices and values
QUIZ • Using the Colon operator, calculate the values of x from 1 up to 3 in increments of 0.1, (Application on the Trapezoidal integration rule)
linspace function: • The linspace (short for linear space) function creates a linearly spaced row vector, but instead you specify the number of values rather than the increment. • Syntax: linspace(first, last, pts.) where: first= first value last= last value pts.= number of points
linspace, example Problem: Want to produce the following values: 5.0 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 6.0 first value x=linspace(5, 6, 11) 11 points last value
linspace, effect in memory • Could you tell what is the effect in memory for the linspace(5,6,11) instruction? • R 1-D array (row-vector) with 11 elements: ... • linspace(5,6,11) is equivalent to x =[5:0.1:6] 5.0 5.1 5.2 5.3 5.9 6.0
Compare colon operator with linspace function a= first value b= last value n= number of points -1 (=panels number, integration rule) h=(b-a)/n = increment x=[a:h:b] % or x=linspace(a,b,n+1) Equivalent instructions Both produce n+1 elements of x Both produce row-vectors
Compare colon operator with linspace function x=[2,4,6,8,10,12,14,16,18,20]; a) Colon Operator • x=[2:2:20]; b) linspace function • x=linspace(2,20,10); x=[a:h:b] x=linspace(a,b,n+1) h=(b-a)/n
Data Types & Variable Declaration • Most common data types (default): • double • char • double means double precision • 15-16 significant-digit variables • automatically created whenever a numerical value is assigned to a variable name.
char variables & strings • Variables of type char consist of : • scalars (one character) or • arrays (many characters), (char arrays are most commonly called strings) • Example: • cheo=‘x’ % one character • pepe = ‘This is a character string’ % many characters • pepe is a 1x26 character array. • Strings are character arrays containing more than one character
Variable initialization Three common ways to initialize a variable in MATLAB: • Assign data to the variable in an assignment statement • Input data into the variable from the keyboard (input function) • Read data from an external file
Initializing Variables with Keyboard input function >> x = input('Enter an input value = ') <E> Output in the Command Window: >> Enter an input value = 5 <E> x = 5 Effect in Memory? x(1)=5 user writes 5 and <E>
Initializing Variables with Keyboard input function >>x = input('Enter an input value = ') Output: >>Enter an input value = [1,2,3] <E> x = 1 2 3 • Effect in Memory? x(1)=1; x(2)=2; x(3)=3 user writes [1,2,3] and <E>
Initializing Variables with Keyboard Input >>x = input('Enter an input value = ')<E> Output in the Command Window: >> Enter an input value = [1 2; 3 4] <E> x = 1 2 3 4 Effect in memory: 2x2 array with elements x(1,1)=1 x(1,2)=2 x(2,1)=3 x(2,2)=4
>> x = input('Enter an input value = ')<E> Output in the Command Window: >>Enter an input value = [1;2;3;4] <E> x = 1 2 3 4 Effect in memory: column vector with elements: x(1)=1 x(2)=2 x(3)=3 x(4)=4 Also could be a 4x1 2-D array with elements: x(1,1)=1 x(2,1)=2 x(3,1)=3 x(4,1)=4 Initializing Variables with Keyboard Input
>>x = input('Enter an input value = ') <E> Output in the Command Window: >>Enter an input value = ‘Albert Einstein’<E> x = Albert Einstein Effect in memory: 15 elements with character values: x(1)=’A’ x(2)=’l’ x(3)=’b’ x(4)=’e’ x(5)=’r’ x(6)=’t’ x(7)=’‘ (i.e., nada) x(8)=’E’ x(9)=’i’ x(10)=’n’ x(11)=’s’ x(12)=’t’ x(13)=’e’ x(14)=‘i’ x(15)=’n’ Initializing Variables with Keyboard Input You write this input
Initializing Variables with Keyboard Input • The data type of the variable is decided during the execution by typing a particular value: an scalar or an array within brackets, or a string within quotes and then <enter>
Initializing Variables with Keyboard Input • ‘s’ (meaning string) as a second input parameter, then the data returned is a character string. Note the difference in syntax with previous instruction: • >>x = input('Enter an input value = ', 's') • Output in the Command Window: >>Enter an input value = Albert Einstein <E> ( NO quotes) x = Albert Einstein
2D Arrays (Matrices) • Matrices are arrays with two or more dimensions • Their size is specified by the number of rows and columns (rows first) • Number of elements =row x column • Reference an array, two forms: • a(2,1) address an individual element, by identifying the row and column • a without parenthesis address the whole array
2D Arrays (matrices) a is a 2 x 3 array Example of operations: >>a(1,2)*a(1,3) ans 6 >>a.*a ans 1 4 9 16 25 36 a(1,1) a(1,2) 1 2 3 a(1,3) a(2,1) a(2,2) a(2,3) 4 5 6 Two syntax methods to initialize: a= [1,2,3; 4,5,6]; a= [1,2,3; 4, 5, 6]; Rows can be separated by semicolon or new lines