Chapter 2

Creating Arrays

The array is a fundamental form that MATLAB uses to store and manipulate data. An array is a list of numbers arranged in rows and/or columns. The simplest array (one-dimensional) is a row or a column of numbers. A more complex array (two-dimensional) is a collection of numbers arranged in rows and columns. One use of arrays is to store information and data, as in a table. In science and engineering, one-dimensional arrays frequently represent vectors, and two-dimensional arrays often represent matrices. This chapter shows how to create and address arrays, and Chapter 3 shows how to use arrays in mathematical operations. In addition to arrays made of numbers, arrays in MATLAB can also be a list of characters, which are called strings. Strings are discussed in Section 2.10.

2.1  CREATING A ONE-DIMENSIONAL ARRAY (VECTOR)

A one-dimensional array is a list of numbers arranged in a row or a column. One example is the representation of the position of a point in space in a three-dimensional Cartesian coordinate system. As shown in Figure 2-1, the position of point A is defined by a list of the three numbers 2, 4, and 5, which are the coordinates of the point.

The position of point A can be expressed in terms of a position vector:

rA = 2i + 4j +5k

where i, j, and k are unit vectors in the direction of the x, y, and z axes, respectively. The numbers 2, 4, and 5 can be used to define a row or a column vector.

images

Figure 2-1: Position of a point.

Any list of numbers can be set up as a vector. For example, Table 2-1 contains population growth data that can be used to create two lists of numbers—one of the years and the other of the population values. Each list can be entered as elements in a vector with the numbers placed in a row or in a column.

Table 2-1: Population data

images

In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information that is used for the elements of the vector. When a vector contains specific numbers that are known (like the coordinates of point A), the value of each element is entered directly. Each element can also be a mathematical expression that can include predefined variables, numbers, and functions. Often, the elements of a row vector are a series of numbers with constant spacing. In such cases the vector can be created with MATLAB commands. A vector can also be created as the result of mathematical operations as explained in Chapter 3.

Creating a vector from a known list of numbers:

The vector is created by typing the elements (numbers) inside square brackets [ ].

images

Row vector: To create a row vector type the elements with a space or a comma between the elements inside the square brackets.

Column vector: To create a column vector type the left square bracket [ and then enter the elements with a semicolon between them, or press the Enter key after each element. Type the right square bracket ] after the last element.

Tutorial 2-1 shows how the data from Table 2-1 and the coordinates of point A are used to create row and column vectors.

Tutorial 2-1: Creating vectors from given data.

images

Creating a vector with constant spacing by specifying the first term, the spacing, and the last term:

In a vector with constant spacing, the difference between the elements is the same. For example, in the vector v = 2 4 6 8 10, the spacing between the elements is 2. A vector in which the first term is m, the spacing is q, and the last term is n is created by typing:

images

Some examples are:

images

  • If the numbers m, q, and n are such that the value of n cannot be obtained by adding q’s to m, then (for positive n) the last element in the vector will be the last number that does not exceed n.
  • If only two numbers (the first and the last terms) are typed (the spacing is omitted), then the default for the spacing is 1.

Creating a vector with linear (equal) spacing by specifying the first and last terms, and the number of terms:

A vector with n elements that are linearly (equally) spaced in which the first element is xi and the last element is xf can be created by typing the linspace command (MATLAB determines the correct spacing):

images

When the number of elements is omitted, the default is 100. Some examples are:

images

2.2  CREATING A TWO-DIMENSIONAL ARRAY (MATRIX)

A two-dimensional array, also called a matrix, has numbers in rows and columns. Matrices can be used to store information like the arrangement in a table. Matrices play an important role in linear algebra and are used in science and engineering to describe many physical quantities.

In a square matrix the number of rows and the number of columns is equal. For example, the matrix

images

is square, with three rows and three columns. In general, the number of rows and columns can be different. For example, the matrix:

images

has four rows and six columns. A matrix m × n has m rows and n columns, and m by n is called the size of the matrix.

A matrix is created by assigning the elements of the matrix to a variable. This is done by typing the elements, row by row, inside square brackets [ ]. First type the left bracket [ then type the first row, separating the elements with spaces or commas. To type the next row type a semicolon or press Enter. Type the right bracket ] at the end of the last row.

images

The elements that are entered can be numbers or mathematical expressions that may include numbers, predefined variables, and functions. All the rows must have the same number of elements. If an element is zero, it has to be entered as such. MATLAB displays an error message if an attempt is made to define an incomplete matrix. Examples of matrices defined in different ways are shown in Tutorial 2-2.

Tutorial 2-2: Creating matrices.

images

Rows of a matrix can also be entered as vectors using the notation for creating vectors with constant spacing, or the linspace command. For example:

images

In this example the first two rows were entered as vectors using the notation of constant spacing, the third row was entered using the linspace command, and in the last row the elements were entered individually.

2.2.1  The zeros, ones and, eye Commands

The zeros(m,n), ones(m,n), and eye(n) commands can be used to create matrices that have elements with special values. The zeros(m,n) and the ones(m,n) commands create a matrix with m rows and n columns in which all elements are the numbers 0 and 1, respectively. The eye(n) command creates a square matrix with n rows and n columns in which the diagonal elements are equal to 1 and the rest of the elements are 0. This matrix is called the identity matrix. Examples are:

images

Matrices can also be created as a result of mathematical operations with vectors and matrices. This topic is covered in Chapter 3.

2.3  NOTES ABOUT VARIABLES IN MATLAB

  • All variables in MATLAB are arrays. A scalar is an array with one element, a vector is an array with one row or one column of elements, and a matrix is an array with elements in rows and columns.
  • The variable (scalar, vector, or matrix) is defined by the input when the variable is assigned. There is no need to define the size of the array (single element for a scalar, a row or a column of elements for a vector, or a two-dimensional array of elements for a matrix) before the elements are assigned.
  • Once a variable exists—as a scalar, vector, or matrix—it can be changed to any other size, or type, of variable. For example, a scalar can be changed to a vector or a matrix; a vector can be changed to a scalar, a vector of different length, or a matrix; and a matrix can be changed to have a different size, or be reduced to a vector or a scalar. These changes are made by adding or deleting elements. This subject is covered in Sections 2.7 and 2.8.

2.4  THE TRANSPOSE OPERATOR

The transpose operator, when applied to a vector, switches a row (column) vector to a column (row) vector. When applied to a matrix, it switches the rows (columns) to columns (rows). The transpose operator is applied by typing a single quote following the variable to be transposed. Examples are:

images

2.5  ARRAY ADDRESSING

Elements in an array (either vector or matrix) can be addressed individually or in subgroups. This is useful when there is a need to redefine only some of the elements, when specific elements are to be used in calculations, or when a subgroup of the elements is used to define a new variable.

2.5.1  Vector

The address of an element in a vector is its position in the row (or column). For a vector named ve, ve(k) refers to the element in position k. The first position is 1. For example, if the vector ve has nine elements:

ve = 35 46 78 23 5 14 81 3 55

then

ve(4) = 23, ve(7) = 81, and ve(1) = 35.

A single vector element, v(k), can be used just as a variable. For example, it is possible to change the value of only one element of a vector by assigning a new value to a specific address. This is done by typing: v(k) = value. A single element can also be used as a variable in a mathematical expression. Examples are:

images

2.5.2  Matrix

The address of an element in a matrix is its position, defined by the row number and the column number where it is located. For a matrix assigned to a variable ma, ma(k,p) refers to the element in row k and column p.

images

then ma(1,1) = 3 and ma(2,3) = 10.

As with vectors, it is possible to change the value of just one element of a matrix by assigning a new value to that element. Also, single elements can be used like variables in mathematical expressions and functions. Some examples are:

images

2.6  USING A COLON : IN ADDRESSING ARRAYS

A colon can be used to address a range of elements in a vector or a matrix.

For a vector:

va(:) Refers to all the elements of the vector va (either a row or a column vector).

va(m:n) Refers to elements m through n of the vector va.

Example:

images

For a matrix:

A(:,n) Refers to the elements in all the rows of column n of the matrix A.
A(n,:) Refers to the elements in all the columns of row n of the matrix A.
A(:,m:n) Refers to the elements in all the rows between columns m and n of the matrix A.
A(m:n,:) Refers to the elements in all the columns between rows m and n of the matrix A.
A(m:n,p:q) Refers to the elements in rows m through n and columns p through q of the matrix A.

The use of the colon symbol in addressing elements of matrices is demonstrated in Tutorial 2-3.

Tutorial 2-3: Using a colon in addressing arrays.

images

In Tutorial 2-3 new vectors and matrices are created from existing ones by using a range of elements, or a range of rows and columns (using :). It is possible, however, to select only specific elements, or specific rows and columns of existing variables to create new variables. This is done by typing the selected elements or rows or columns inside brackets, as shown below:

images

2.7  ADDING ELEMENTS TO EXISTING VARIABLES

A variable that exists as a vector, or a matrix, can be changed by adding elements to it (remember that a scalar is a vector with one element). A vector (a matrix with a single row or column) can be changed to have more elements, or it can be changed to be a two-dimensional matrix. Rows and/or columns can also be added to an existing matrix to obtain a matrix of different size. The addition of elements can be done by simply assigning values to the additional elements, or by appending existing variables.

Adding elements to a vector:

Elements can be added to an existing vector by assigning values to the new elements. For example, if a vector has 4 elements, the vector can be made longer by assigning values to elements 5, 6, and so on. If a vector has n elements and a new value is assigned to an element with an address of n + 2 or larger, MATLAB assigns zeros to the elements that are between the last original element and the new element. Examples:

images

Elements can also be added to a vector by appending existing vectors. Two examples are:

images

Adding elements to a matrix:

Rows and/or columns can be added to an existing matrix by assigning values to the new rows or columns. This can be done by assigning new values, or by appending existing variables. This must be done carefully since the size of the added rows or columns must fit the existing matrix. Examples are:

images

If a matrix has a size of m × n and a new value is assigned to an element with an address beyond the size of the matrix, MATLAB increases the size of the matrix to include the new element. Zeros are assigned to the other elements that are added. Examples:

images

2.8  DELETING ELEMENTS

An element, or a range of elements, of an existing variable can be deleted by reassigning nothing to these elements. This is done by using square brackets with nothing typed in between them. By deleting elements, a vector can be made shorter and a matrix can be made smaller. Examples are:

images

2.9  BUILT-IN FUNCTIONS FOR HANDLING ARRAYS

MATLAB has many built-in functions for managing and handling arrays. Some of these are listed below:

Table 2-2: Built-in functions for handling arrays

images

Additional built-in functions for manipulation of arrays are described in the Help Window. In this window, select “MATLAB,” then in the Contents “Functions,” and then “By Category.”

images

Sample Problem 2-1:   Create a matrix

Using the ones and zeros commands, create a 4 × 5 matrix in which the first two rows are 0s and the next two rows are 1s.

Solution

images

A different solution to the problem is:

images

images

Sample Problem 2-2:   Create a matrix

Create a 6 × 6 matrix in which the middle two rows and the middle two columns are 1s and the rest of the entries are 0s.

Solution

images

images

Sample Problem 2-3:   Matrix manipulation

Given are a 5 × 6 matrix A, a 3 × 6 matrix B, and a 9-element vector v.

images

Create the three arrays in the Command Window, and then, by writing one command, replace the last four columns of the first and third rows of A with the first four columns of the first two rows of B, the last four columns of the fourth row of A with the elements 5 through 8 of v, and the last four columns of the fifth row of A with columns 3 through 5 of the third row of B.

Solution

images

images

2.10  STRINGS AND STRINGS AS VARIABLES

  • A string is an array of characters. It is created by typing the characters within single quotes.
  • Strings can include letters, digits, other symbols, and spaces.
  • Examples of strings: 'ad ef ', '3%fr2', '{edcba:21!', 'MATLAB'.
  • A string that contains a single quote is created by typing two single quotes within the string.
  • When a string is being typed in, the color of the text on the screen changes to maroon when the first single quote is typed. When the single quote at the end of the string is typed, the color of the string changes to purple.

Strings have several different uses in MATLAB. They are used in output commands to display text messages (Chapter 4), in formatting commands of plots (Chapter 5), and as input arguments of some functions (Chapter 7). More details are given in these chapters when strings are used for these purposes.

  • When strings are being used in formatting plots (labels to axes, title, and text notes), characters within the string can be formatted to have a specified font, size, position (uppercase, lowercase), color, etc. See Chapter 5 for details.

Strings can also be assigned to variables by simply typing the string on the right side of the assignment operator, as shown in the examples below:

>> a='FRty 8'
a =
FRty 8
>> B='My name is John Smith'
B =
My name is John Smith
>>

When a variable is defined as a string, the characters of the string are stored in an array just as numbers are. Each character, including a space, is an element in the array. This means that a one-line string is a row vector in which the number of elements is equal to the number of characters. The elements of the vectors are addressed by position. For example, in the vector B that was defined above the 4th element is the letter n, the 12th element is J, and so on.

>> B(4)
ans =
n
>> B(12)
ans =
J

As with a vector that contains numbers, it is also possible to change specific elements by addressing them directly. For example, in the vector B above the name John can be changed to Bill by:

images

Strings can also be placed in a matrix. As with numbers, this is done by typing a semicolon; (or pressing the Enter key) at the end of each row. Each row must be typed as a string, which means that it must be enclosed in single quotes. In addition, as with a numerical matrix, all rows must have the same number of elements. This requirement can cause problems when the intention is to create rows with specific wording. Rows can be made to have the same number of elements by adding spaces.

MATLAB has a built-in function named char that creates an array with rows having the same number of characters from an input of rows not all of the same length. MATLAB makes the length of all the rows equal to that of the longest row by adding spaces at the end of the short lines. In the char function, the rows are entered as strings separated by a comma according to the following format:

images

For example:

images

A variable can be defined as either a number or a string made up of the same digits. For example, as shown below, x is defined to be the number 536, and y is defined to be a string made up of the digits 536.

>> x=536
x =
   536
>> y='536'
y =
536
>>

The two variables are not the same even though they appear identical on the screen. Note that the characters 536 in the line below the x= are indented, while the characters 536 in the line below the y= are not indented. The variable x can be used in mathematical expressions, whereas the variable y cannot.

2.11  PROBLEMS

1.   Create a row vector that has the following elements: 8, 10/4, 12 × 1.4, 51, tan 85°, images, and 0.15.

2.   Create a row vector that has the following elements: images, ln35/0.43, images, 129, and cos2 (π/20).

3.   Create a column vector that has the following elements: 25.5, images, 6!, 2.74, 0.0375, and π/5.

4.   Create a column vector that has the following elements: images, sin235°, 6.1, ln292, 0.00552, ln229, and 133.

5.   Define the variables x = 0.85, y = 12.5, and then use them to create a column vector that has the following elements: y, yx, ln(y/x), x × y, and x + y.

6.   Define the variables a = 3.5, b = −6.4, and then use them to create a row vector that has the following elements: a, a2, a/b, a · b, and images.

7.   Create a row vector in which the first element is 1 and the last element is 43, with an increment of 6 between the elements (1, 7, 13, …, 43).

8.   Create a row vector with 11 equally spaced elements in which the first element is 96 and the last element is 2.

9.   Create a column vector in which the first element is 26, the elements decrease with increments of −3.6, and the last element is −10. (A column vector can be created by the transpose of a row vector.)

10. Create a column vector with 9 equally spaced elements in which the first element is −34 and the last element is −7. (A column vector can be created by the transpose of a row vector.)

11. Using the colon symbol, create a row vector (assign it to a variable named Fives) with five elements that are all 5.

12. Using the linspace command, create a row vector (assign it to a variable named Nines) with nine elements that are all 9.

13. Use a single command to create a row vector (assign it to a variable named a) with 6 elements such that the last element is 4.7 and the rest of the elements are 0s. Do not type the vector elements explicitly.

14. Use a single command to create a row vector (assign it to a variable named b) with 8 elements such that the last three element are 3.8 and the rest of the elements are 0s. Do not type the vector elements explicitly.

15. Use a single command to create a row vector (assign it to a variable named b) with 11 elements such that

b =
  0      2      4      6      8      10      12      9      6      3      0

Do not type the vector explicitly.

16. Create two row vectors: a=2:3:17 and b=3:4:15. Then, by only using the name of the vectors (a and b), create a row vector c that is made from the elements of a followed by the elements of b.

17. Create two column vectors: a=[2:3:17]’ and b=[3:4:15]’. Then, by only using the name of the vectors (a and b), create a column vector c that is made from the elements of a followed by the elements of b.

18. Create a vector (name it vtA) that has 10 elements of which the first is 8, the increment is 7, and the last element is 71. Then, assign elements of vtA to a new vector (call it vtB) such that vtB has 7 elements. The first 4 elements are the first 4 elements of the vector vtA, and the last 3 are the last 3 elements of the vector vtA. Do not type the elements of vtA vector explicitly.

19. Create a vector (name it vctC) that has 12 elements of which the first is 5, the increment is 4 and the last element is 49. Then, by assigning elements of vctC to new vectors, create the following two vectors:

(a) A vector (name it Codd) that contains all the elements with odd index of vctC; i.e., Codd = 5 13 21 ... 45.

(b) A vector (name it Ceven) that contains all the elements with even index of vct; i.e., Ceven = 9 17 25 ... 49.

In both parts use vectors of odd and even numbers for the index of Codd and Ceven, respectively. Do not type the elements of the vectors explicitly.

20. Create a vector (name it vctD) that has 9 elements of which the first is 0, the increment is 3 and the last element is 27. Then create a vector (name it vct-Dop) that consist of the elements of vctD in reverse order. Do it by assigning elements of vctD to vctDop. (Do not type the elements of vctDop vector explicitly.)

21. Create the following matrix by using vector notation for creating vectors with constant spacing and/or the linspace command. Do not type individual elements explicitly.

images

22. Create the following matrix by using vector notation for creating vectors with the linspace command. Do not type individual elements explicitly.

images

23. Create the following matrix by typing one command. Do not type individual elements explicitly.

images

24. Create the following matrix by typing one command. Do not type individual elements explicitly.

images

25. Create the following matrix by typing one command. Do not type individual elements explicitly.

images

26. Create the following matrix by typing one command. Do not type individual elements explicitly.

images

27. Create three row vectors:

a = [3 −1 5 11 −4 2],   b = [7 −9 2 13 1 −2],   c = [−2 4 −7 8 0 9]

(a) Use the three vectors in a MATLAB command to create a 3 × 6 matrix in which the rows are the vectors a, b, c, and c.

(b) Use the three vectors in a MATLAB command to create a 6 × 3 matrix in which the columns are the vectors b, c, and a.

28. Create three row vectors:

a = [3 −1 5 11 −4 2], b = [7 −9 2 13 1 −2], c = [−2 4 −7 8 0 9]

(a) Use the three vectors in a MATLAB command to create a 3 × 4 matrix such that the first, second, and third rows consist of the last four elements of the vectors a, b, and c, respectively.

(b) Use the three vectors in a MATLAB command to create a 3 × 3 matrix such that the first, second, and third columns consist of the first three elements of the vectors a, b, and c, respectively.

29. Create two row vectors:

       a = [3 9 −0.5 3.6 1.5 −0.8 4], b = 12 −0.8 6 2 5 3 −7.4]

(a) Use the two vectors in a MATLAB command to create a 3 × 4 matrix such that the first row consists of elements 3 through 6 of vector a, the second row consists of elements 4 through 7 of vector a, and the third row consists of elements 2 through 5 of vector b.

(b) Use the two vectors in a MATLAB command to create a 6 × 2 matrix such that the first column consists of elements 2 through 7 of vector a, and the second column consists of elements 1 through 3 and 5 through 7 of vector b.

30. By hand (pencil and paper) write what will be displayed if the following commands are executed by MATLAB. Check your answers by executing the commands with MATLAB. (Parts (b), (c), (d), and (e) use the vector that was defined in part (a).)

(a) a=1:4:17

(b) b=[a(1:3) a]

(c) c=[a;a]’

(d) d=[a’ a’]’

(e) e=[[a; a; a; a; a] a’]

31. The following vector is defined in MATLAB:

v = [6 11 −4 5 8 1 −0.2 −7 19 5]

By hand (pencil and paper) write what will be displayed if the following commands are executed by MATLAB. Check your answers by executing the commands with MATLAB.

(a) a=v(3:8)   (b) b=v([1,3,2:7,4,6])   (c) c=v([9,1,5,4])’

32. The following vector is defined in MATLAB:

v = [6 11 −4 5 8 1 −0.2 −7 19 5]

By hand (pencil and paper) write what will be displayed if the following commands are executed by MATLAB. Check your answers by executing the commands with MATLAB.

(a) a=[v([1:3 7:−1:5]);v([10,1,4:6,2])]

(b) b=[v([9,2:4,1])' v([5 3 10 2 7])' v([10:−2:4,10])']

33. Create the following matrix A.

images

By writing one command and using the colon to address range of elements (do not type individual elements explicitly), use the matrix A to:

(a) Create a six-element row vector named ha that contains the elements of the second row of A.

(b) Create a three-element column vector named hb that contains the elements of the sixth column of A.

(c) Create a five-element row vector named hc that contains the first two elements of the third row of A and the last three element of the first row of A.

34. Create the following vector A.

A = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18]

Then using the MATLAB’s built-in reshape function create the following matrix B from the vector A:

images

By writing one command and using the colon to address range of elements (do not type individual elements explicitly), use the matrix B to:

(a) Create a nine-element column vector named Ba that contains the elements of the first, third, and fifth columns of B.

(b) Create a seven-element row vector named Bb that contains elements 2 through 5 of the second row of B and the elements of the third column of B.

(c) Create a six-element row vector named Bc that contains elements 3 through 5 of the first row, and elements 2 through 4 of the third row of B.

35. Create the following vector C.

C = [1.5 2 2.5 3 3.5 4 4.5 5 9.6 9.1 8.6 8.1 7.6 7.1 6.6 6.1]

Then use MATLAB’s built-in reshape function and the transpose operation to create the following matrix D from the vector C:

images

By writing one command and using the colon to address a range of elements (do not type individual elements explicitly), use the matrix D to:

(a) Create a eight-element column vector named Da that contains the elements of the first and third rows of D.

(b) Create an eight-element raw vector named Db that contains the elements of the second and the fourth columns of D.

(c) Create a eight-element row vector named Dc that contains the first two elements of the first row, the last three elements of the second column, and the first three elements of the fourth row of D.

36. Create the following matrix E:

images

(a) Create a 2 × 3 matrix F from the second and third rows, and the third through the fifth columns of matrix E.

(b) Create a 4 × 4 matrix G from all rows and the third through sixth columns of matrix E.

37. Create the following matrix H:

images

(a) Create a 2 × 5 matrix G such that its first row includes the first three elements and the last two elements of the first row of H, and the second row of G includes the last five elements of the third row of H.

(b) Create a 4 × 3 matrix K such that the first, second, third, and fourth rows are the second, third, fifth and seventh columns of matrix H.

38. The following matrix is defined in MATLAB:

images

By hand (pencil and paper) write what will be displayed if the following commands are executed by MATLAB. Check your answers by executing the commands with MATLAB.

a) A=M([1,3],[1,5,6])

b) B=M(:,[4,4:6])

c) C=M([1,2],:)

d) D=M([2,3],[2,3])

39. The following matrix is defined in MATLAB:

images

By hand (pencil and paper) write what will be displayed if the following commands are executed by MATLAB. Check your answers by executing the commands with MATLAB.

(a) A=[N(1,1:4)’,N(2,2:5)’]

(b) B=[N(:,3)' N(3,:)]

(c) C(3:4,5:6)=N(2:3,4:5)

40. By hand (pencil and paper) write what will be displayed if the following commands are executed by MATLAB. Check your answers by executing the commands with MATLAB.

v=1:2:23
M=reshape(v,3,4)
M(2,:)=[]
M(:,3)=[]
N=ones(size(M))

41. Using the zeros, ones, and eye commands, create the following arrays by typing one command:

images

42. Using the zeros, ones, and eye commands create the following arrays by typing one command:

images

43. Use the eye, ones, and zeros commands to create the following arrays:

images

Using the variables A, B, and C, write a command that creates the following matrix D:

images

44. Create a 2 × 3 matrix A in which all the elements are 1. Then reassign A to itself (several times) such that A will become:

images

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.66