Vectors and Arrays in M-File Environments
One significant capability of environments accounts for much of their popularity among engineers: their ability to do vector and matrix computations. M-file environments can operate on the following types of values:
- Scalar: a scalar is a single value (i.e. a number).
- Vector: a vector is an ordered series of numbers.
- Matrix: a matrix is a rectangular array of numbers.
NOTE:
The ability to do computations on vectors and matrices gives MATLAB its name (MATrix LABoratory). - String: variables may also contain strings of characters.
Vector Basics
There are several ways to create a vector of values. One is to enclose the values in square brackets. For example, the command
[9 7 5 3 1]
creates the vector of values 9, 7, 5, 3, and 1. This vector can be assigned to a variable v
:
>> v = [9 7 5 3 1]
v =
9 7 5 3 1
A second way to create a vector of values is with the sequence notation
start:end
or start:inc:end
. For example, 1:10
creates the vector of integers from 1 to 10:
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
1:0.1:2
creates the vector
>> 1:0.1:2
ans =
1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000
10:-1:1
creates the vector
>> 10:-1:1
ans =
10 9 8 7 6 5 4 3 2 1
Vector elements are accessed using numbers in parentheses. For example if the vector
v
is defined as v = [9 7 5 3 1]
, the second element of v
can be accessed as
>> v(2)
ans = 7
v
can be changed as follows:
>> v(4) = 100
v =
9 7 5 100 1
Element by Element Operations on Vectors
In addition to vector and matrix arithmetic, many operations can be performed on each element of the vector. The following examples use the vector
v = [9 7 5 3 1]
.- Addition: the command
v+val
addsval
to each element ofv
:>> v+5 ans = 14 12 10 8 6
- Subtraction: the command
v-val
subtractsval
from each element ofv
:>> v-5 ans = 4 2 0 -2 -4
- Multiplication: the command
v*val
multiplies each element ofv
byval
:>> v*5 ans = 45 35 25 15 5
- Division: the command
v/val
divides each element ofv
byval
:The command>> v/5 ans = 1.80000 1.40000 1.00000 0.60000 0.20000
val./v
dividesval
by each element ofv
:>> 5./v ans = 0.55556 0.71429 1.00000 1.66667 5.00000
- Exponentiation: the command
v.^val
raises each element ofv
to theval
power:>> v.^2 ans = 81 49 25 9 1
More Information on Vectors and Matrices
An excellent tutorial on how to use MATLAB's vector and array capabilities is at the Mathworks MATLAB tutorial page.
One useful method of accessing entire rows or entire columns of the matrix is not mentioned in the tutorial. Suppose that the matrix
A
is defined as
>> A = [1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20]
A =
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
A
can be obtained by specifying a single ":" as the column index:
>> A(2,:)
ans =
6 7 8 9 10
A
can be obtained by specifying a single ":" as the row index:
>> A(:,3)
ans =
3
8
13
18
0 comments:
Post a Comment