Vector arithmetic
The standard vector operations of adding two vectors and multiplying a vector by a scalar work in MATLAB.
However the straight forward multiplication or division of vectors is not defined.
Addition of two vectors
The vector u has 3 elements 1, 2, 3.
The vector v has 3 elements 10, 11, 12.
The vector w has 3 elements 11, 13, 15.
MATLAB can handle vectors with any number of elements, even hundreds of thousands of elements. However both vectors must have the same number of elements for their sum to be defined.
The vector u has 5 elements 1, 2, 3.
The vector v has 6 elements 10, 11, 12, 13.
??? Error using ==> plus
Matrix dimensions must agree.
A vector times a scalar
Multiplying a vector by a scalar produces another vector of the same size in which each element of the original vector has been multiplied by the scalar.
The vector u has 3 elements 1, 2, 3 from before, so the vector w has elements -2, -4, -6
Adding a scalar to a vector
One operation where MATLAB is different from standard mathematics is that a scalar may be added to any vector producing a new vector with the scalar added to each element of the vector.
The scalar -2 is added to each element of the vector u with elements 1, 2, 3, so the vector w has elements -1, 0, 1
Element by element operations
Sometimes it is very useful to apply arithmetic operations to each element of a vector (or matrix). These element by element operations are
- .* to multiply corresponding elements of two vectors
- ./ to divide corresponding elements of two vectors
- .^ to take powers of each element of a vector
Note that addition (subtraction) of two vectors and multiplication of a vector by a scalar are already defined to apply element by element.
Define the vector u with elements 1, 2, 3, 4, 5
Element by element multiplication .* to get 1, 4, 9, 16, 25
Element by element powers .^ to get 1, 4, 9, 16, 25
Define the vector u with elements -4,...,4
Element by element division ./
The fifth element is 1/0 which in MATLAB gives Inf
Many MATLAB functions, for example exp and sqrt, work with vectors, applying the function to each element of the vector.
Warnings
- When working with vectors it is common practice to use an index i to refer to elements, for example xi. If you redefine i in MATLAB this may affect how you can define complex numbers.
Self-test Exercise
Create a vector u with elements 1 / j3 for j = 2,6,10,...,100. What is the last element of u?
Answer:
- u = 1 ./ [2:4:100].^3
- u(end)
Summary
The standard vector arithmetic operations of adding two vectors of the same size or multiplying a vector by a scalar can be done in MATLAB.
MATLAB also has additional vector operations of adding a scalar to each element of a vector, and elementwise operators .* for multiplication, ./ for division and .^ for powers.