I am trying to write a function to transpose matrices.
paramters of that function:
the matrix to transpose
the output matrix which is empty.
The problem is I am able to transpose some matrices but some other fail like the one i am giving in my example. WHy? how could I solve it?
code:
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));
Makes it easier for us. – Fluctuate