该函数的参数如下:
- 需要转置的矩阵 - 空的输出矩阵
问题是,我能够转置一些矩阵,但有些矩阵会失败,就像我在示例中提供的那个。为什么?我该如何解决?
代码:
int main (void)
{
//this works well
/* double array[3][2] = {{1,2},{3,4},{5,6}};
height = 3;
width = 2;
*/
//this input doesn't work
double array[2][3] = {{1,2,3},{4,5,6}};
height = 2;
width = 3;
int heightOutput = width; //2
int widthOutput = height; //3
double **output;
output = malloc(widthOutput * sizeof(double *)); //rows from 1
for (i = 0; i < widthOutput; i++)
{
output[i] = malloc(heightOutput * sizeof(double)); //columns
}
transposeMatrix(&array[0][0], height,width, &output[0][0], heightOutput, widthOutput);
printf("\n");
printf("\noutput matrix\n");
for(i=0;i<heightOutput;i++)
{
for(j=0;j<widthOutput;j++)
{
printf("%f\t",output[i][j]);
}
printf("\n");
}
}
void transposeMatrix(double* array2, int height, int width, double * output, int height2, int width2)
{
double workaround[3][3] ={0};
double result;
int i,j;
printf("input matrix:\n");
for(i=0;i<height;i++)
{
for(j=0;j<width;j++)
{
printf("%f\t",(*((array2+i*width)+j)));
}
printf("\n");
}
printf("\n");
for(i=0;i<width2;i++)
{
for(j=0;j<height2;j++)
{
result = (*((array2+i*width)+j));
workaround[i][j] = result;
}
}
for(i=0;i<width2;i++)
{
for(j=0;j<height2;j++)
{
*((output+j*3)+i) = workaround[i][j];
printf("%f\t",(*((output+j*3)+i)));
}
printf("\n");
}
}
result = (*((array2 + i * width) + j));
这会让我们更容易理解。 - Almo