(Continued from here )
I am trying to use column major order to a 2d matrix which I am using as 1d.
int N=3,R=2;
for (int i=0;i<N;i++){
for (int j=0;j<R;j++){
//printf("\nX[%d]=%d\t",i+j*N,res[i+j*N]); //column major
// printf("\nX[%d]=%d\t",i*R+j,res[i*R+j]); //row major
}
printf("\n");
}
but the column major doesn not work as it should.
Can you tell me why these 2 things don't work?
1) I have 2 matrices ,I multiply them and I can printf as row major or column major (everything is fine until now).
Now,if I store the result matrix (which I received from multiplication) :
...
//store as column major
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
res[i+j*rows]=res[i*cols+j];
}
}
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
printf("\nB[%d]=%d\t",i+j*rows,res[i+j*rows]);
//printf("\nB[%d]=%d\t",i*cols+j,res[i*cols+j]);
}
}
then neither printf shows the right results.
2) Can you tell me why this doesn't show the right results for column major but only for row major?
int main(int argc, const char* argv[]) {
int rows=3;
int cols=2;
int *A=(int*)malloc(rows*rows*sizeof(int));
int *B=(int*)malloc(rows*cols*sizeof(int));
int *result=(int*)malloc(rows*cols*sizeof(int));
A[0]=1;
A[1]=2;
A[2]=3;
A[3]=4;
A[4]=5;
A[5]=6;
A[6]=7;
A[7]=8;
A[8]=9;
B[0]=5;
B[1]=6;
B[2]=7;
B[3]=8;
B[4]=4;
B[5]=5;
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
result[i*cols+j]=0;
for (int k=0;k<rows;k++){
result[i*cols+j]+=A[i*rows+k]*B[k*cols+j];
}
}
}
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
printf("\nB[%d]=%d\t",i+j*rows,result[i+j*rows]); //column major
//printf("\nB[%d]=%d\t",i*cols+j,result[i*cols+j]); //row major
}
printf("\n");
}
return 0;
}