@@ -552,12 +552,13 @@ void mju_transposeSparse(mjtNum* res, const mjtNum* mat, int nr, int nc,
552
552
// clear number of non-zeros for each row of transposed
553
553
mju_zeroInt (res_rownnz , nc );
554
554
555
- // total number of non-zeros of mat
556
- int nnz = rowadr [nr - 1 ] + rownnz [nr - 1 ];
557
-
558
555
// count the number of non-zeros for each row of the transposed matrix
559
- for (int i = 0 ; i < nnz ; i ++ ) {
560
- res_rownnz [colind [i ]]++ ;
556
+ for (int r = 0 ; r < nr ; r ++ ) {
557
+ int start = rowadr [r ];
558
+ int end = start + rownnz [r ];
559
+ for (int j = start ; j < end ; j ++ ) {
560
+ res_rownnz [colind [j ]]++ ;
561
+ }
561
562
}
562
563
563
564
// compute the row addresses for the transposed matrix
@@ -566,18 +567,18 @@ void mju_transposeSparse(mjtNum* res, const mjtNum* mat, int nr, int nc,
566
567
res_rowadr [i ] = res_rowadr [i - 1 ] + res_rownnz [i - 1 ];
567
568
}
568
569
569
- // r holds the current row in mat
570
- int r = 0 ;
571
-
572
570
// iterate through each non-zero entry of mat
573
- for (int i = 0 ; i < nnz ; i ++ ) {
574
- // iterate to get to the current row (skipping rows with all zeros)
575
- while ((i - rowadr [r ]) >= rownnz [r ]) r ++ ;
576
-
577
- // swap rows with columns and increment res_rowadr
578
- int c = res_rowadr [colind [i ]]++ ;
579
- res [c ] = mat [i ];
580
- res_colind [c ] = r ;
571
+ for (int r = 0 ; r < nr ; r ++ ) {
572
+ int start = rowadr [r ];
573
+ int end = start + rownnz [r ];
574
+ for (int i = start ; i < end ; i ++ ) {
575
+ // swap rows with columns and increment res_rowadr
576
+ int c = res_rowadr [colind [i ]]++ ;
577
+ res_colind [c ] = r ;
578
+ if (res ) {
579
+ res [c ] = mat [i ];
580
+ }
581
+ }
581
582
}
582
583
583
584
// shift back row addresses
0 commit comments