4.3: Vector Arithmetic
- Page ID
As with numbers, you can do arithmetic with vectors. If you add a number to a vector, MATLAB increments each element of the vector:
>> Y = X + 5 Y = 6 7 8
The result is a new vector; the original value of
X has not changed.
If you add two vectors, MATLAB adds the corresponding elements of each vector and creates a new vector that contains the sums:
>> Z = X + Y Z = 7 9 11
But adding vectors only works if the operands are the same size. Otherwise you get an error:
>> W = [1 2] W = 1 2 >> X + W Matrix dimensions must agree.
This error message might be confusing, because we think of
W as vectors, not matrices. But in MATLAB, a vector is a kind of matrix. We’ll come back to matrices later, but in the meantime, you might see the term in error messages and documentation.
If you divide two vectors, you might be surprised by the result:
>> X / Y ans = 0.2953
MATLAB is performing an operation called right division, which is not what we expected. To divide the elements of
X by the elements of
Y, you have to use
./, which is element-wise division:
>> X ./ Y ans = 0.1667 0.2857 0.3750
Multiplication has the same problem. If you use
*, MATLAB does matrix multiplication. With these two vectors, matrix multiplication is not defined, so you get an error:
>> X * Y Error using * Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform element-wise multiplication, use '.*'.
In this case, the error message is pretty helpful. As it suggests, you can use
.* to perform element-wise multiplication:
>> X .* Y ans = 6 14 24
As an exercise, see what happens if you use the exponentiation operator (
^) with a vector.