From e2c21c4ae21dc9c8c9291f0453dbb37a521734a0 Mon Sep 17 00:00:00 2001 From: Tim Kuehn Date: Wed, 12 Aug 2015 16:52:55 -0700 Subject: [PATCH] Fix transpose_mut for square matrices. And add a test for it. --- src/structs/dmat.rs | 9 ++++----- tests/mat.rs | 19 +++++++++++++++++-- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/structs/dmat.rs b/src/structs/dmat.rs index 9a2bc2ca..d2c86acd 100644 --- a/src/structs/dmat.rs +++ b/src/structs/dmat.rs @@ -2,7 +2,7 @@ #![allow(missing_docs)] // we hide doc to not have to document the $trhs double dispatch trait. -use std::{cmp, mem}; +use std::cmp; use std::iter::repeat; use std::ops::{Add, Sub, Mul, Div, Index, IndexMut}; use std::fmt::{Debug, Display, Formatter, Result}; @@ -480,16 +480,15 @@ impl Transpose for DMat { #[inline] fn transpose_mut(&mut self) { if self.nrows == self.ncols { - for i in 1..self.nrows { - for j in 0..self.ncols - 1 { + let n = self.nrows; + for i in 0..n - 1 { + for j in i + 1..n { let off_i_j = self.offset(i, j); let off_j_i = self.offset(j, i); self.mij[..].swap(off_i_j, off_j_i); } } - - mem::swap(&mut self.nrows, &mut self.ncols); } else { // FIXME: implement a better algorithm which does that in-place. diff --git a/tests/mat.rs b/tests/mat.rs index f4c70f83..234beba1 100644 --- a/tests/mat.rs +++ b/tests/mat.rs @@ -3,7 +3,7 @@ extern crate rand; use rand::random; use na::{Vec1, Vec3, Mat1, Mat2, Mat3, Mat4, Mat5, Mat6, Rot2, Rot3, Persp3, PerspMat3, Ortho3, - OrthoMat3, DMat, DVec, Row, Col, BaseFloat, Diag}; + OrthoMat3, DMat, DVec, Row, Col, BaseFloat, Diag, Transpose, RowSlice}; macro_rules! test_inv_mat_impl( ($t: ty) => ( @@ -688,4 +688,19 @@ fn test_cholesky_mat5() { #[test] fn test_cholesky_mat6() { test_cholesky_impl!(Mat6); -} \ No newline at end of file +} + +#[test] +fn test_transpose_square_mat() { + let col_major_mat = &[0, 1, 2, 3, + 0, 1, 2, 3, + 0, 1, 2, 3, + 0, 1, 2, 3]; + let num_rows = 4; + let num_cols = 4; + let mut mat = DMat::from_col_vec(num_rows, num_cols, col_major_mat); + mat.transpose_mut(); + for i in 0..num_rows { + assert_eq!(&[0, 1, 2, 3], mat.row_slice(i, 0, num_cols).as_slice()); + } +}