NSCS 344, Week 6: Matlab concepts

Table of Contents

Taking the transpose of a matrix or vector

Taking the transpose of a matrix or vector means turning the rows into columns and the columns into rows. In Matlab we do this using a ' next to the vector or matrix we want to take the transpose of. For example, if we define a row vector like this ...
V = [1 2 3]
V = 1×3
1 2 3
Taking the transpose gives us a column vector like this
ans = 3×1
1 2 3
Likewise for a matrix
M = [1 2 3;
4 5 6]
M = 2×3
1 2 3 4 5 6
ans = 3×2
1 4 2 5 3 6

Vectorizing things in Matlab

Often you yourself with a vector or matrix and you want to perform some operation on all of the elements. For example, perhaps you want to multiply them all by five. You could do this using a for loop like this ...
V = [1 2 3];
for i = 1:length(V)
Vtimes5(i) = 5 * V(i);
Vtimes5 = 1×3
5 10 15
But a quicker way is simply to write
Vtimes5 = 5 * V
Vtimes5 = 1×3
5 10 15
Which applies the 5 * operation to every element. This is an example of vectorizing your code in Matlab, where you take advantage of Matlab's ability to perform operations on vector very quickly. Indeed the code above runs about twice as fast when it's vectorized than when it's implemented through the for loop.
More complex examples arise when you want to combine two vectors. For example if you want to multiply two vectors together in an elementwise fashion, you could do it with a for loop like this
V1 = [1 2 3];
V2 = [4 5 6];
for i = 1:length(V1)
V1timesV2(i) = V1(i) * V2(i);
V1timesV2 = 1×3
4 10 18
Or you could do the exact same thing faster using elementwise multiplication through the .* command
V1timesV2 = V1.*V2
V1timesV2 = 1×3
4 10 18
You can also do other operations in an elementwise fashion. e.g. raising something to the power of another ...
V1toThePowerOfV2 = V1.^V2
V1toThePowerOfV2 = 1×3
1 32 729
One thing to beware of is missing the period in an elementwise command. For example with multiplication ...
throws an error because it's trying to do the matrix multiplication of V1 and V2, which can't be done because the sizes are wrong. You can however take the matrix multiplication of V1 and V2 if you take the transpose of one of them. Depending which one you take the transpose of you will either get a 3 x 3 matrix ...
ans = 3×3
4 5 6 8 10 12 12 15 18
or a 1 x 1 number
V1 * V2'
ans = 32
Why? Because of how matrix multiplication works ... in the first example we are writing
In the second example we are writing
Vectorizing things smartly can massively improve the speed of your code. I've had examples of things running in hours that run in seconds after vectorization.
But vectorizing is also definitely an art, and it can make your code less easy to understand. A general guide is to always start with the for loop version of what you are trying to do and only vectorize after that simple version works so you can compare the vectorized answer with the "correct" answer you got from the for loop.