Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return matrix on C

Here is my code below.

#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>

void rot(int angle);
static double R[3][3]={0};

int main(void) {
    int angle = 30;
    rot(angle);
    int i, j = 0;

   for (i = 0; i < 3;i++) {
      for (j = 0; j < 3; j++) {
        printf("%lf\n", R[i][j]);
    }
}
return 0;
}

void rot(int angle) {
    double cang = cos(angle*M_PI / 180);
    double sang = sin(angle*M_PI / 180);

    R[0][0] = cang;
    R[1][1] = cang;
    R[1][0] = -sang;
    R[0][1] = sang;
}

For now, function rot do not return any value itself. But since R is static double, I was able to print out the R changed by rot function. I want to change function rot to return R[3][3](two dimension array). So I want to use rot function on main like

double R1=rot(30);
double R2=rot(60);

is there any way to make it possible?

like image 727
hee Yune Avatar asked Sep 16 '17 06:09

hee Yune


1 Answers

The duplicate isn't necessarily good for this. As these R² matrices need to be easily copyable, the best way to represent them is to put them in a struct:

typedef struct Matrix3x3 {
    double v[3][3];
} Matrix3x3;

Then it is trivial to get them as return values:

Matrix3x3 rot(int angle) {
    Matrix3x3 m = {0};
    double cang = cos(angle*M_PI / 180);
    double sang = sin(angle*M_PI / 180);

    m.v[0][0] = cang;
    m.v[1][1] = cang;
    m.v[1][0] = -sang;
    m.v[0][1] = sang;
    return m;
}

Unlike arrays, a struct that contains an array is easy to copy too:

Matrix3x3 x = y;