ENG College of Engineering Engineering Education Innovation Center 1 Arrays in MATLAB Topics Covered: 1.Creating arrays of numbers vectors matrices Creating Arrays / Chapter 2
ENG Arrays: Vectors and Matrices The array is the fundamental form MATLAB uses to store data Scalars – one row and one column (special case) Vectors Row vector – one row and multiple columns Column vector – multiple rows and one column Matrices – multiple rows and multiple columns
ENG Arrays: Example Arrays are used in many applications. They can represent data: An example is a position vector. The location of point P in a three dimensional space can be represented by the three Cartesian coordinates 2, 4, and 5. Arrays of numbers can represent a vector x y z P (2, 4, 5) rArA O Year Population
ENG The year and population data in the previous slide can be entered as vectors in rows: Year = [ ] Population = [ ] Vectors or in columns:
ENG CREATING A ROW VECTOR IN MATLAB A vector can be created by typing the elements (numbers) inside square brackets [ ] separated by a comma or space(s) Type and press Enter >> pntAH = [2,4,5] pntAH = Computer Response
ENG COLUMN VECTORS >> pop = [127; 130; 136; 145; 158; 178; 211] pop = >> pntAV = [2 4 5] pntAV = Two methods: Separate elements by semicolon or “enter key”.
ENG CREATING A VECTOR WITH CONSTANT SPACING A vector in which the first term is m, the spacing is q and the last term is n can be created by typing [m : q : n]. >> x = [1 : 2 : 13] or x = 1 : 2 : 13 x = >> x = [1.5 : 0.1 : 2.1] x = If spacing (q) is omitted the default is 1 >> x = [-3 : 7] x =
ENG An alternate method Sometimes you know the number of terms and not the spacing – for this case, the function linspace is useful –Specify first term: step size: last term –linspace (first term, last term, number of terms)
ENG TWO DIMENSIONAL ARRAY - MATRIX The number of rows and columns may be the same or different Two rows and four columns (2 x 4) A (m x n), or “m by n”, matrix has m rows and n columns. (m x n) is called the size of the matrix
ENG CREATING A MATRIX IN MATLAB A Matrix is created by typing the elements (numbers) row by row inside square brackets [ ]. Two methods are shown, with and without the semicolon >> a = [ ; ; ] a = >> b = [ ] b = Type and press Enter Computer Response Type and press Enter After each row and after the ] Computer Response
ENG >> a = 7 a = 7 >> E = 3 E = 3 >> d = [5 a+E 4 E^2] d = >> g = [a a^2 13; a*E 1 a^E] g = ARRAY EXAMPLES 43
ENG THE TRANSPOSE OPERATION The transpose operation ' (single quote) For a vector: Converts a row vector to a column vector, or vice versa. For a matrix: Interchanges the rows and columns
ENG Vector transpose >> a = [3 8 1] a = >> b = a' b = >> c = 1:2:5 c = >> d = c' d = 1 3 5
ENG MATRIX TRANSPOSE Matrix example: >> c = [ ; ; ] c = >> d = c' d =