<< Chapter < Page | Chapter >> Page > |
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:
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
The command
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
The command
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
The fourth element of
v
can be changed as follows:
>> v(4) = 100
v =9 7 5 100 1
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]
.
v+val
adds
val
to each element of
v
:
>> v+5
ans =14 12 10 8 6
v-val
subtracts
val
from each element of
v
:
>> v-5
ans =4 2 0 -2 -4
v*val
multiplies each element of
v
by
val
:
>> v*5
ans =45 35 25 15 5
v/val
divides each element of
v
by
val
:
>> v/5
ans =1.80000 1.40000 1.00000 0.60000 0.20000
The command
val./v
divides
val
by each element of
v
:
>> 5./v
ans =0.55556 0.71429 1.00000 1.66667 5.00000
v.^val
raises each element of
v
to the
val
power:
>> v.^2
ans =81 49 25 9 1
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 1011 12 13 14 15
16 17 18 19 20]A =1 2 3 4 5
6 7 8 9 1011 12 13 14 15
16 17 18 19 20
An entire row of
A
can be obtained by specifying a single ":" as the column index:
>> A(2,:)
ans =6 7 8 9 10
Similarly, an entire column of
A
can be obtained by specifying a single ":" as the row index:
>> A(:,3)
ans =3
813
18
Notification Switch
Would you like to follow the 'Freshman engineering problem solving with matlab' conversation and receive update notifications?