Matrix transposition: Difference between revisions

→‎{{header|C}}: proper casting; improve tag
(Add Seed7 example)
(→‎{{header|C}}: proper casting; improve tag)
Line 204:
 
=={{header|C}}==
Transpose a 2D double array.
Reserving the proper space for the matrix is left to the caller.
<lang c>void#include transpose_matrix(double *m,<stdio.h>
 
double *d,
void transpose(void *dest, void *src, int rowssrc_h, int columnssrc_w)
{
int i, j;
double (*d)[src_h] = dest, (*s)[src_w] = src;
for(i = 0; i < rows; i++)
for (i = 0; i < src_h; i++)
{
for for(j = 0; j < columnssrc_w; j++)
d[j][i] = s[i][j];
{
}
d[j*rows+i] = m[i*columns+j];
 
}
<lang c>int main()
}
}</lang>
Usage example (note that you must specify first the row, then the column):
<lang c>int main()
{
int i, j;
double a[43][5] = {{ 0, 1.00, 2.00, 3.00, 4.00, 5.00},
{ 5, 1.006, 7, 4.008, 9.00, 16.00, 25.00},
{ 1.00, 0, 8.000, 27.000, 64.00,125.0042},};
double b[5][43];
{ 1.00, 16.00, 81.00,256.00,625.00}};
transpose(b, a, 3, 5);
 
double b[5][4];
for (i = 0; i < rows5; i++)
for (j = 0; j <4 3; j++)
transpose_matrix(&a[0][0], &b[0][0], 4, 5);
printf("%g%c", b[i][j], j == 2 ? '\n' : ' ');
for(j=0;j<4;j++)
return 0;
{
for(i=0;i<5;i++)
{
printf("%6.2lf ", a[j][i]);
}
printf("\n");
}
printf("--\n");
for(j=0;j<5;j++)
{
for(i=0;i<4;i++)
{
printf("%6.2lf ", b[j][i]);
}
printf("\n");
}
}</lang>
{{improve|C|Unnecessarily complicated, probably lost all benefit from the algorithm. Can use cleaner coding (and malloc(item_size) does not violate O(1))}}
Output:
<pre>
1.00 2.00 3.00 4.00 5.00
1.00 4.00 9.00 16.00 25.00
1.00 8.00 27.00 64.00 125.00
1.00 16.00 81.00 256.00 625.00
--
1.00 1.00 1.00 1.00
2.00 4.00 8.00 16.00
3.00 9.00 27.00 81.00
4.00 16.00 64.00 256.00
5.00 25.00 125.00 625.00
</pre>
Playing more to C's strengths, the following implementation transposes a matrix of any type and dimensions
in place with only O(1) space. See the [[wp:In-place_matrix_transposition|Wikipedia article]] for more information.
Anonymous user