I wish I'd known MATLAB had... complex numbers!
If you do any geometry in matlab, you'll find complex numbers really handy.
- The great advantage is, if you have 10x10 points, normally you'd need to store them either as
- X = 10x10 matrix of X-coordinates, Y = 10x10 matrix of Y-coordinates
Or as: - M = cat(3,X,Y), which is a 10x10x2 matrix of coordinates; the first slice is the X's and the second slice is Y's.
The second is irritating because proper matrix operations don't work in 3 dimensions. Also you have to "squeeze" to extract coordinates e.g. M=SQUEEZE(M(:,:,1)). Also, if you are using many dimensions, you have to remember which dimension is the X/Y dimension.
- The complex solution is easy and aesthetically pleasing!
Z=X+1j*Y which is a 10x10 matrix of complex numbers. - To quickly calculate the distances of each of the points in a matrix, to another point P=x+iy,
distance = abs(Z-P) - and similarly for the angles, use the argument function, angle(Z-P) (in most other languages this function is called "arg".
- The real beauty is if you wanted to rotate all the points in the matrix by 45 degrees around the point P=x+iy, simply do
(Z-P)*exp(1j*pi/4)+P - which translates by -P, rotates by pi/4, and adds back P. Now imagine doing that with X and Y coordinates!
- If you use i and j in for loops, don't worry! For complex numbers always use 1i or 1j.
- important functions are REAL, IMAG, ABS, ANGLE
No comments:
Post a Comment