Billie
Billie

Reputation: 9146

Transpose a NxN matrix

I have a NxN matrix and it trying to transpose it by this code:

    for(int i = 0; i < mat_size; ++i) {
        for(int j = 0; j < mat_size; ++j) {
            double tmpJI = get(j, i);
            put(j, i, get(i, j));
            put(i, j, tmpJI);
        }
    }

it doesn't work, what is the problem? thanks in advance.

Upvotes: 2

Views: 898

Answers (5)

jester
jester

Reputation: 3489

This is because the elements that you swap in the lower triangle of the matrix gets swapped again when the iteration reaches the other side of the diagonal. That is the element is swapped twice which results in nothing. Try:

for(int i = 0; i < mat_size; ++i) {
for(int j = 0; j < i; ++j) {
    double tmpJI = get(j, i);
    put(j, i, get(i, j));
    put(i, j, tmpJI);
  }
}

Upvotes: 0

PMF
PMF

Reputation: 17185

You need to swap only if j > i. So the inner loop must start at i+1. For j==i (the center diagonal) no swapping is needed, too.

Your solution doesn't work because you're actually swapping twice (once with j=x and i=y and once with j=y and i=x.

Upvotes: 1

RamonBoza
RamonBoza

Reputation: 9038

Going from 0 to mat_size will get you reorder the whole matrix two times, getting the original one again.

change to :

for(int i = 0; i < mat_size; ++i) {
    for(int j = 0; j < i; ++j) {
        double tmpJI = get(j, i);
        put(j, i, get(i, j));
        put(i, j, tmpJI);
    }
}

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234665

It doesn't work since you're swapping the whole matrix with itself. What you need to do is exchange the upper triangle with the lower one:

for(int j = 0; j < i; ++j) {

is one way.

Upvotes: 10

Daniel
Daniel

Reputation: 36710

For example the (2,5) is swapped for i=2,j=5 and i=5,j=2. Swap twice does nothing.

for(int i = 0; i < mat_size; ++i) {
    for(int j = 0; j < i; ++j) {
        double tmpJI = get(j, i);
        put(j, i, get(i, j));
        put(i, j, tmpJI);
    }
}

Upvotes: 0

Related Questions