ENG College of Engineering Engineering Education Innovation Center 1 Array Accessing and Strings in MATLAB Topics Covered: 1.Array addressing. 2. Character arrays. Creating Arrays / Chapter 2
ENG ARRAY ADDRESSING (VECTOR) The address of an element in a vector is its position in the row (or column), starting at 1. >> v = [ ] v = >> v(4) ans = 23 >> v(7) ans = 81 >> v(1) ans = 35 It is possible to change an element in a vector by entering a value to a specific address directly: >> v(6) = 273 v =
ENG Addressing Specified Elements of a Vector Any combination of elements from a vector can be addressed in any order >> v = [ ] v = >> u = v([ ]) u = v([ ]) is the same as ( [v(4), v(5), v(7), v(3), v(3)] ).
ENG USING A COLON (:) WHEN ADDRESSING VECTORS The colon operator can be used to generate a list of elements to address All the elements of a vector (either a row vector or a column vector) Elements 3 through 7 ( [v(3), v(4), v(5), v(6), v(7)] ). >> v = [ ] v = >> u = v(3:7) u = v(:) v(3 : 7)
ENG ARRAY ADDRESSING (MATRIX) >> m=[ ; ; ] m = >> m(1,1) ans = 3 >> m(2,3) ans = Single elements can be used like variables in computations: >> m(2,3) - m(1,1) ans = 7
ENG USING A COLON (:) WHEN ADDRESSING MATRICES A(:, 3) A(2, :) A(:, 2:5) A(2:4, :) A(1:3, 2:4) A([4 2],:) Elements in all the rows of column 3 Elements in all the columns of row 2 Elements in columns 2 through 5 in all the rows Elements in rows 2 through 4 in all the columns Elements in rows 1 through 3 and in columns 2 through 4 Elements in all the columns of rows 4 then 2
ENG ADDRESSING MATRICES >> A = [ ; ; ; ; ] A = >> B = A(:,3) B = >> C = A(2,:) C = Define a matrix Define a matrix using part of A
ENG ADDRESSING MATRICES >> D = A(:, 2:5) D = >> F = A(1:3,2:4) F = >> E = A(2:4,:) E = A = >> G = A([5 2],5:-2:1) G =
ENG ADDRESSING MATRICES >> A(1:2,1:3) = B([5 5],2:4) A = >> A = zeros (4,5) A = B = >> A(3:4,[1 4 5]) = B(1:2,1:3) A =
ENG Strings are a special case of a vector (row array) where every element is a character. Strings are created by entering the characters between single quotes. String arrays can include letters, digits, other symbols, and spaces Examples of strings: 'ad ef ', '3%fr2', '{edcba :21!' Character Arrays
ENG STRING VARIABLES >> a = 'ERty 8' a = ERty 8 >> B = ['My name is John Smith'] B = My name is John Smith a has 6 elements, and B has 21 elements The elements can be addressed like any other row array >> a(4) ans = y >> B(12) ans = J
ENG STRING VARIABLES >> x = 536 x = 536 >> x = '536' x = 536 The string variable: is not the same as the number variable: If you use a string variable in calculations, you get an answer based on the ascii storage code for those characters (probably not what you wanted)! An important application of strings is in creating input prompts and output messages. This will be shown later when script file I/O (input/output) is discussed