NSCS 344, Week 6: Matlab concepts
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 ...
Taking the transpose gives us a column vector like this
Likewise for a matrix
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 ...
But a quicker way is simply to write
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
V1timesV2(i) = V1(i) * V2(i);
Or you could do the exact same thing faster using elementwise multiplication through the .* command
You can also do other operations in an elementwise fashion. e.g. raising something to the power of another ...
V1toThePowerOfV2 = V1.^V2
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 ...
or a 1 x 1 number
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.