I have a vector:
vector = [1 2 3;4 5 6; 7 9 0]
vector =
1 2 3
4 5 6
7 9 0
I want to take this and create a unit vector. We can get the magnitude by doing:
mag = sqrt(sum(vector'.^2))'
mag =
3.7417
8.7750
11.4018
When we try to divide each element by the magnitude I get an error:
vector./mag
Error using ./
Matrix dimensions must agree.
Essentially I must divide every vector element in each row by every row in the mag vector. How can I do this?
The other answers give the correct result but you can vectorize the calculation for faster calculation.
ret = bsxfun(@rdivide, vector, mag)
I recommend using the bsxfun, it is a very useful function for matrix calculation.
The problem is that, as the error message says, the dimensions of vector and mag don't match.
You want to divide every element of the first row of vector by mag(1).
What you need is repmat(), which "repeats copies of array".
Writing
repmat(mag,1,3)
returns a 3x3 matrix such that every column is an exact copy of mag:
3.7417 3.7417 3.7417
8.7750 8.7750 8.7750
11.4018 11.4018 11.4018
So you can use the one-liner:
vector./repmat(mag,1,3)
ans =
0.26726 0.53452 0.80178
0.45584 0.56980 0.68376
0.61394 0.78935 0.00000
That way, the first row of vector, i.e., [1 2 3], is divided element-by-element by [3.7417 3.7417 3.7417].
In other words, every element of vector is divided by the correct magnitude.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With