0% found this document useful (0 votes)
46 views

Arrays: Vectors and Matrices: Initializing Vectors: Explicit Lists

This document discusses arrays, vectors, and matrices in MATLAB. It covers: 1) Vectors are 1D arrays that can be initialized explicitly using lists with commas or spaces between elements. Matrices are 2D arrays initialized using semicolons to separate rows. 2) Vectors can also be initialized using the colon operator to specify a range of values or increments. The linspace function creates equally spaced values. 3) Elements of arrays can be accessed using subscripts, which can be scalar numbers or vectors. Basic arithmetic operations can also be performed element-wise on arrays. 4) MATLAB has different data types including double precision (default), integers, and single precision that must be converted to

Uploaded by

Piyush Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Arrays: Vectors and Matrices: Initializing Vectors: Explicit Lists

This document discusses arrays, vectors, and matrices in MATLAB. It covers: 1) Vectors are 1D arrays that can be initialized explicitly using lists with commas or spaces between elements. Matrices are 2D arrays initialized using semicolons to separate rows. 2) Vectors can also be initialized using the colon operator to specify a range of values or increments. The linspace function creates equally spaced values. 3) Elements of arrays can be accessed using subscripts, which can be scalar numbers or vectors. Basic arithmetic operations can also be performed element-wise on arrays. 4) MATLAB has different data types including double precision (default), integers, and single precision that must be converted to

Uploaded by

Piyush Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Arrays: vectors and matrices

As mentioned earlier, the name MATLAB stands for MATrix LABoratory because MATLAB has been designed to work with matrices. A matrix is a rectangular object (e.g. a table) consisting of rows and columns. We will postpone most of the details of proper matrices and how MATLAB works with them until Chapter 6. A vector is a special type of matrix, having only one row, or one column. Vectors are also called lists or arrays in other programming languages. If you havent come across vectors officially yet, dont worryjust think of them as lists of numbers. MATLAB handles vectors and matrices in the same way, but since vectors are easier to think about than matrices, we will look at them first. This will enhance your understanding and appreciation of many other aspects of MATLAB. As mentioned above, MATLAB refers to scalars, vectors and matrices generally as arrays. We will also use the term array generally, with vector and matrix referring to their one-dimensional (1-D) and two-dimensional (2-D) forms.

Initializing vectors: explicit lists


To get going, try the following short exercises on the command line. 1. Enter a statement like x = [1 3 0 -1 5] Can you see that you have created a vector (list) with five elements? (Make sure to leave out the semicolon so that you can see the list. Also, make sure you hit Enter to execute the command.) 2. Enter the command disp(x) to see how MATLAB displays a vector. 3. Enter the command whos (or look in the Workspace browser). Under the heading Size you will see that x is 1-by-5, which means 1 row and 5 columns. You will also see that the total number of elements is 5. 4. You can put commas instead of spaces between vector elements if you like. Try this: a = [5,6,7] 5. Dont forget the commas (or spaces) between elements, otherwise you could end up with something quite different, e.g. x = [130-15] 6. You can use one vector in a list for another one, e.g. type in the following: a = [1 2 3]; b = [4 5]; c = [a -b]; Can you work out what c will look like before displaying it? 7. And what about this? a = [1 3 7]; a = [a 0 -1]; 8. Enter the following x = [ ] and then note in the Workspace browser that the size of x is given as 0-by-0 because x is empty. This means x is defined, and can be used where an array is appropriate without causing an error; however, it has no size or value. Making x empty is not the same as saying x = 0 (in the latter case x has size 1-by-1), or clear x (which removes x from the workspace, making it undefined). An empty array may be used to remove elements from an array (see Section 2.2.5 below). These are all examples of the explicit list method of initializing vectors. Remember the following important rules: Elements in the list must be enclosed in square not round brackets. Elements in the list must be separated either by spaces or by commas.

Initializing vectors: the colon operator


A vector can also be generated (initialized) with the colon operator, as we have seen already in the previous chapter. Enter the following statements: x = 1:10 (elements are the integers 1, 2, , 10); x = 1:0.5:4 (elements are the values 1, 1.5, , 4 in increments of 0.5note that if the colons separate three values, the middle value is the increment); x = 10:-1:1 (elements are the integers 10, 9, , 1, since the increment is negative); x = 1:2:6 (elements are 1, 3, 5; note that when the increment is positive but not equal to 1, the last element is not allowed to exceed the value after the second colon); x = 0:-2:-5 (elements are 0,2,4; note that when the increment is negative but not equal to 1, the last element is not allowed to be less than the value after the second colon); x = 1:0 (a complicated way of generating an empty vector!).

linspace
The function linspace can be used to initialize a vector of equally spaced values, e.g. linspace(0, pi/2, 10) creates a vector of 10 equally spaced points from 0 to /2 (inclusive).

Transposing vectors
All of the vectors examined so far are row vectors. Each has one row and several columns. To generate the column vectors that are often needed in mathematics, you need to transpose such vectors, i.e. you need to interchange their rows and columns. This is done with the single quote, or apostrophe (), which is the nearest MATLAB can get to the mathematical dash () that is often used to indicate the transpose. Enter x = 1:5 and then enter x to display the transpose of x. Note that x itself remains a row vector. Or you can create a column vector directly: y = [1 4 8 0 -1]

Subscripts
We can refer to particular elements of a vector by means of subscripts. 1. Enter r = rand(1,7) This gives a row vector of seven random numbers. 2. Now enter r(3) This will display the third element of r. The number 3 is the subscript. 3. Now enter r(2:4) This should give the second, third and fourth elements. 4. What about r(1:2:7)? 5. And r([1 7 2 6])? 6. use an empty vector to remove elements from a vector, e.g. r([1 7 2]) = [ ] will remove elements 1, 7 and 2. To summarize: A subscript is indicated inside round brackets (also called parentheses). A subscript may be a scalar or a vector. In MATLAB subscripts always start at 1. Fractional subscripts are always rounded down, e.g. x(1.9) refers to element x(1).

Matrices
A matrix may be thought of as a table consisting of rows and columns. You create a matrix just as you do a vector, except that a semicolon is used to indicate the end of a row, e.g. the statement a = [1 2 3; 4 5 6] results in a = 1 2 3 4 5 6 A matrix may be transposed, e.g. with a initialized as above, the statement a results in a = 1 4 2 5 3 6 A matrix can be constructed from column vectors of the same length. The statements x = 0:30:180; table = [x sin(x*pi/180)] result in table = 0 0 30.0000 0.5000 60.0000 0.8660 90.0000 1.0000 120.0000 0.8660 150.0000 0.5000 180.0000 0.0000

Numbers
Numbers can be represented in MATLAB in the usual decimal form (fixed point), with an optional decimal point, e.g. 1.2345 -123 .0001 A number may also be represented in scientific notation, e.g. 1.2345109 may be represented in MATLAB as 1.2345e9. This is also called floating point notation. The number has two parts: the mantissa, which may have an optional decimal point (1.2345 in this example) and the exponent (9), which must be an integer (signed or unsigned). Mantissa and exponent must be separated by the letter e (or E). The mantissa is multiplied by the power of 10 indicated by the exponent. Note that the following is not scientific notation: 1.2345*109. It is actually an expression involving two arithmetic operations (* and ) and therefore more time consuming. Use scientific notation if the numbers are very small or very large, since theres less chance of making a mistake, e.g. represent 0.000000001 as 1e-9. On computers using standard floating point arithmetic, numbers are represented to approximately 16 significant decimal digits. The relative accuracy of numbers is given by the function eps, which is defined as the distance between 1.0 and the next largest floating point number. Enter eps to see its value on your computer. The range of numbers is roughly }10308 to }10308. Precise values for your computer are returned by the MATLAB functions realmin and realmax.

Data types
MATLAB has 14 fundamental data types (or classes). The default numeric data type is doubleprecision; all MATLAB computations are done in double-precision. More information on data types can be found in the Help index. MATLAB also supports signed and unsigned integer types and single-precision floating point, by means of functions such as int8, uint8, single, etc.

Arithmetic operations between two scalarsHowever, before mathematical operations can be performed on such data types they must first be converted to double-precision using the double function.
Operation Algebraic form MATLAB Addition a+b a + b Subtraction ab a - b Multiplication ab a * b Right division a/b a / b Left division b/a a \ b Power ab a b

Arithmetic operators
The evaluation of expressions is achieved by means of arithmetic operators. The arithmetic operations on two scalar constants or variables are shown in Table 2.1. Operators operate on operands (a and b in the table). Left division seems a little curious: divide the right operand by the left operand. For scalar operands the expressions 1/3 and 3\1 have the same numerical value (a colleague of mine speaks the latter as 3 under 1). However, matrix left division has an entirely different meaning, as we shall see later Precedence of arithmetic operations
Precedence Operator 1 Parentheses 2 Power, 3 Multiplication and division, 4 Addition and subtraction, (round brackets) left to right left to right left to right

The colon operator


The colon operator has a lower precedence than + as the following shows: 1+1:5 The addition is carried out first, and then a vector with elements 2, , 5 is initialized. Arithmetic operators that operate element by element on arrays.
Operator Description .* Multiplication ./ Right division .\ Left division . Power

You may be surprised at the following: 1+[1:5] Were you? The value 1 is added to each element of the vector 1:5. In this context, the addition is called an array operation, because it operates on each element of the vector (array). Array operations are discussed below. See Appendix B for a complete list of MATLAB operators and their precedences.

The transpose operator


The transpose operator has the highest precedence. Try 1:5 The 5 is transposed first (into itself since it is a scalar!), and then a row vector is formed. Use square brackets if you want to transpose the whole vector: [1:5]

Arithmetic operations on arrays


Enter the following statements at the command line: a = [2 4 8]; b = [3 2 2]; a .* b a ./ b MATLAB has four further arithmetic operators, as shown in Table 2.3. These operators work on corresponding elements of arrays with equal dimensions. The operations are sometimes called array operations, or element-by-element operations because the operations are performed element by element. For example, a .* b results in the following vector (sometimes called the array product): [a(1)*b(1) a(2)*b(2) a(3)*b(3)] i.e. [6 8 10]. You will have seen that a ./ bgives element-by-element division. Now try [2 3 4] . [4 3 1]. The ith element of the first vector is raised to the power of the ith element of the second vector. The period (dot) is necessary for the array operations of multiplication, division and exponentiation, because these operations are defined differently for matrices; the operations are then called matrix operations . With a and b as defined above, try a + b and a - b. For addition and subtraction, array operations and matrix operations are the same, so we dont need the period to distinguish between them. When array operations are applied to two vectors, both vectors must be the same size! Array operations also apply to operations between a scalar and a non-scalar. Check this with 3 .* a and a . 2. This property is called scalar expansion. Multiplication and division operations between scalars and non-scalars can be written with or without the period, i.e. if a is a vector, 3 .* a is the same as 3 * a. A common application of element-by-element multiplication is in finding the scalar product (also called the dot product) of two vectors x and y, which is defined as x y =_ E xiyi . The MATLAB function sum(z) finds the sum of the elements of the vector z, so the statement sum(a .* b) will find the scalar product of a and b (30 for a and b defined above).

Expressions
An expression is a formula consisting of variables, numbers, operators, and function names. An expression is evaluated when you enter it at the MATLAB prompt, e.g. evaluate 2 as follows: 2 * pi MATLABs response is: ans = 6.2832 Note that MATLAB uses the function ans (which stands for answer) to return the last expression to be evaluated but not assigned to a variable. If an expression is terminated with a semicolon (;) its value is not displayed, although it is still returned by ans.

Statements
MATLAB statements are frequently of the form variable = expression e.g. s = u * t - g / 2 * t . 2; This is an example of an assignment statement, because the value of the expression on the right is assigned to the variable (s) on the left. Assignment always works in this direction. Note that the object on the left-hand side of the assignment must be a variable name. A common mistake is to get the statement the wrong way round, like a + b = c Basically any line that you enter in the Command Window or in a program, which MATLAB accepts, is a statement, so a statement could be an assignment, a command, or simply an expression, e.g. x = 29; % assignment clear % command pi/2 % expression This naming convention is in keeping with most other programming languages and serves to emphasize the different types of statements that are found in programming. However, the MATLAB documentation tends to refer to all of these as functions. As we have seen, a semicolon at the end of an assignment or expression suppresses any output. This is useful for suppressing irritating output of intermediate results (or large matrices). A statement which is too long to fit onto one line may be continued to the next line with an ellipsis of at least three dots, e.g. x = 3 * 4 - 8 .... / 2 2; Statements on the same line may be separated by commas (output not suppressed) or semicolons (output suppressed), e.g. a = 2; b = 3, c = 4; Note that the commas and semicolons are not technically part of the statements; they are separators. Statements may involve array operations, in which case the variable on the left-hand side may become a vector or matrix.

You might also like