I have a matrix transpose function that takes arrays with a possibly different number of rows and columns.
How can I improve performance and code quality?
void matrix_transpose(float *matrix, int rows, int columns)
{
int current_row;
int current_column;
float temp;
float buffer[MATRIX_TRANSPOSE_BUFFER_SIZE];
int buffer_position = 0;
if(rows == columns)
{
for(current_row = 0; current_row < rows; ++current_row)
{
for(current_column = current_row; current_column < columns; ++current_column)
{
temp = *(matrix + current_row * columns + current_column);
*(matrix + current_row * columns + current_column) = *(matrix + current_column * columns + current_row);
*(matrix + current_column * columns + current_row) = temp;
}
}
}
else if(rows * columns < MATRIX_TRANSPOSE_BUFFER_SIZE)
{
for(current_column = 0; current_column < columns; ++current_column)
{
for(current_row = 0; current_row < rows; ++current_row)
{
buffer[buffer_position++] = *(matrix + current_row * columns + current_column);
}
}
buffer_position = 0;
while(buffer_position < rows * columns)
{
*matrix++ = buffer[buffer_position++];
}
}
}
Here's an example call:
float matrix[] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16,
17, 18, 19, 20
};
matrix_transpose(matrix, 5, 4);
memcpy()
as it's usually better optimized than your loop and will make your code more readable. \$\endgroup\$