Matrix transposition: Difference between revisions

m
→‎{{header|C}}: Remove extra whitespace
m (added another c version)
m (→‎{{header|C}}: Remove extra whitespace)
Line 173:
 
=={{header|C}}==
 
Reserving the proper space for the matrix is left to the caller.
 
<lang c>void transpose_matrix(double *m,
double *d,
Line 189 ⟶ 187:
}
}</lang>
 
Usage example (note that you must specify first the row, then the column):
 
<lang c>int main()
{
Line 221 ⟶ 217:
}
}</lang>
 
Output:
 
<pre>
1.00 2.00 3.00 4.00 5.00
Line 236 ⟶ 230:
5.00 25.00 125.00 625.00
</pre>
Playing more to cC's strengths, the following implementation transposes a matrix of any type and dimensions
in place with only O(1) space. See the [http[wp://www.en.wikipedia.org/wiki/In-place_matrix_transposition |Wikipedia article]] for more information.
transposes a matrix of any type and dimensions
<lang c>void
in place with only O(1) space. See the [http://www.en.wikipedia.org/wiki/In-place_matrix_transposition Wikipedia article]
for more information.
<lang C>
void
*transpose_matrix(matrix,rows,cols,item_size)
void *matrix;
Line 248 ⟶ 239:
size_t item_size;
{
#define ALIGNMENT 16 /* power of 2 >= minimum array boundary alignment; maybe unnecessary but machine dependent */
 
char *cursor;
Line 263 ⟶ 254:
while (block_size)
{
nadir = 1; /* first and last entries are always fixed points so aren't visited */
while (nadir + 1 < ents)
{
memcpy(carry,&(cursor[(lag = nadir) * item_size]),block_size);
while ((orbit = (lag / rows) + cols * (lag % rows)) > nadir) /* follow a complete cycle */
{
memcpy(&(cursor[lag * item_size]),&(cursor[orbit * item_size]),block_size);
Line 274 ⟶ 265:
memcpy(&(cursor[lag * item_size]),carry,block_size);
orbit = nadir++;
while ((orbit < nadir) ? (nadir + 1 < ents) : 0) /* find the next unvisited index by an exhaustive search */
{
orbit = nadir;
Line 286 ⟶ 277:
}
return matrix;
}</lang C>
}
</lang>
No extra storage allocation is required by the caller. Here are
usage examples for an array of doubles and an array of complex numbers.
b<lang c>a = (complexdouble *) transpose_matrix((void *) ba, n, m, sizeof(complexdouble));
<lang c>
ab = (doublecomplex *) transpose_matrix((void *) ab, n, m, sizeof(doublecomplex));</lang>
b = (complex *) transpose_matrix((void *) b, n, m, sizeof(complex));
</lang>
After execution, the memory maps of a and b will be those of m by n arrays instead
of n by m.
 
=={{header|Common Lisp}}==
<lang lisp>(defun transpose (m)
Anonymous user