Is this the correct C++ code to rotate a point in 4D?

Inhahe

New member
Joined
May 23, 2020
Messages
8
Is this the correct C++ code to rotate a point in four dimensions? It's based on http://www.mosismath.com/RotationMatrix/RotationMatrix.html.
C++:
double* rotate(double x, double y, double z, double w, int plane_p, int plane_q, double angle)
{
    double result[4];
    double vector[4] = { x, y, z, w };
    double matrix[4][4];
    for (int p = 0; p < 4; p++) for (int q = 0; q < 4; q++) matrix[p][q] = 0;
    for (int pq = 0; pq < 4; pq++) matrix[pq][pq] = 1;
    matrix[plane_p][plane_p] = cos(angle);
    matrix[plane_q][plane_q] = cos(angle);
    matrix[plane_p][plane_q] = sin(angle);
    matrix[plane_q][plane_p] = -sin(angle);
    for (int r_i = 0; r_i < 4; r_i++)
    {
        double r = 0;
        for (int q = 0; q < 4; q++) r += vector[r_i] * matrix[r_i][q];
        result[r_i] = r;
    }
    return result;
}
It seems that, after rotating by random angles on all six combinations of planes, whenever w is 0, the resultant w, result[3], is also 0. I don't think that's correct?
 
Oh, I discovered an error in the matrix multiplication. r += vector[r_i] * matrix[r_i][q] should have been
r += vector[q] * matrix[r_i][q]. Can you check it and see if there any other errors? Thanks..
 
You're also returning the address of "result" which is a local variable. The memory associated with that won't be valid after leaving the function.
 
You're also returning the address of "result" which is a local variable. The memory associated with that won't be valid after leaving the function.
Oh, thanks. I got that method for returning an array from a webpage. They had the array defined as static, and I didn't do that because I thought it was unnecessary. If I define it as static, that will work, right?

But if I define it as static, will that pose a problem if I make my program multithreaded in the future? Is there a better way to return an array?
 
Last edited:
You could pass the array into the function...
Code:
void rotate(double x, double y, double z, double w, int plane_p, int plane_q, double angle, double result[4])
{ ... }

...
double result[4];
rotate(..., result);

Perhaps consider using a vector/ matrix library. "opencv" seems quite popular, but I'm sure there are many alternatives! However it can be nice to write your own routines too.

EDIT: Your concerns about threading and static variables are correct
 
Top