Anonymous user
Matrix transposition: Difference between revisions
→{{header|C}}
m (→{{header|Ruby}}: Remove phantom category 'matrix.rb'.) |
|||
Line 230:
return 0;
}</lang>
Transpose a matrix of size w x h in place with only O(1) space and without moving any element more than once. See the [[wp:In-place_matrix_transposition|Wikipedia article]] for more information.▼
<lang c>#include <stdio.h>
▲in place with only O(1) space. See the [[wp:In-place_matrix_transposition|Wikipedia article]] for more information.
void transpose(double *m, int w, int h)
{
int start, next, i;
double tmp;
for (start = 1; start < w * h - 2; start++) {
next = start;
do { next = (next % h) * w + next / h; } while (next > start);
if (next < start) continue;
tmp = m[next = start];
do {
i = (next % h) * w + next / h;
m[next] = (i == start) ? tmp : m[i];
next = i;
} while (next > start);
}
}
void show_matrix(double *m, int w, int h)
{
int i, j;
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++)
printf("%2g ", m[i * w + j]);
putchar('\n');
}
}
int main(void)
{
int i;
double m[15];
for (i = 0; i < 15; i++) m[i] = i + 1;
puts("before transpose:");
show_matrix(m, 3, 5);
transpose(m, 3, 5);
puts("\nafter transpose:");
show_matrix(m, 5, 3);
}</lang>output<lang>before transpose:
10 11 12
13 14 15
after transpose:
1 4
2
3 6 9 12 15 </lang>
▲ {
▲ }
▲ {
▲ return matrix;
=={{header|C++}}==
|