simple transposition returns zero elements!

Hello , I can't understand why this is returning 2 of 4 elements of the transposed matrix ATrans as zeros!

for example:
A[0][0] = 0.182384
A[0][1] = 0.546355

A[1][0] = 0.237687
A[1][1] = 0.936557

AΤrans[0][0] = 0.237687
AΤrans[0][1] = 0.000000

AΤrans[1][0] = 0.000000
AΤrans[1][1] = 0.936557
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>


int main(int argc, const char* argv[]) {
    
    srand(time(NULL));
    
    float **A , **ATrans;
    
    int r = 2 , c = 2;
    
    A = (float **) malloc( r * sizeof(float*) );
    for ( int i = 0; i < r; i++ )
        A[i] = (float *) malloc(  c * sizeof(float) );
        
	
	ATrans = (float **) malloc( r * sizeof(float*) );
    for ( int i = 0; i < r; i++ )
        ATrans[i] = (float *) malloc( c * sizeof(float) );
        
	  
    //create random matrix A  
    for (int i = 0; i < r ; i++) {
        for (int j = 0; j < c; j++) {
            
            A[i][j] = ( (float) rand() / RAND_MAX );        
            }
            
         }
    
    for (int i = 0; i < r; i++) {
    	printf("\n");
    	for (int j = 0; j < c; j++) {
    		printf("\nA[%d][%d] = %f",i,j,A[i][j]);
    	}
    }
    
    //create the transposed 
    for (int i = 0; i < r; i++) {
        for (int j = 0; j <  c; j++) {
            
            ATrans[j][j] = A[i][j];
                    }
        }         
             
               
     for (int i = 0; i < c; i++) {
    	printf("\n");
    	for (int j = 0; j < r; j++) {
    		printf("\nAΤrans[%d][%d] = %f",i,j,ATrans[i][j]);
    	}
    }
    
    printf("\n");
    		
   
    for (int i = 0; i < r; i++) {
        free( A[i] );
        free( ATrans[i] );
        }
    free( A );        
    free( ATrans );
               
 
  return 0; 
   
 }

Comments

  • This line
    ATrans[j][j] = A[i][j];
    
    has [j][j] where it should have [j]
  • No , this line is correct , since I want to take the transposed of A.

    The problem is eventually with the matrices allocation.

    If I use for example:
    A = (float *) malloc ( r * c * sizeof (float*))
    

    and
    A[ i*c + j ]
    

    the program works fine!

    So , the problem is at the allocation in this way.
  • I'm pretty sure if you only ever set values into ATrans[j][j] then only the values on the main diagonal of the matrix will be set. After all j == j.
    Unless there is some other code that you haven't shown that you are using to change values somewhere else in ATrans?

    I agree though, you do have to also transpose the row and column sizes.
  • :|

    I didn't show it! You are right ! I have
    Atrans[j][j]
    
    instead of
    [j][i]
    
    .
    How this happened??:)
Sign In or Register to comment.