Skip to content

Commit

Permalink
Add Array2::from_diag (#673)
Browse files Browse the repository at this point in the history
* ENH Add Array2::from_diag

* Lint

* Address review comments

* Add example and panic conditions

* Remove cfg(feature = "approx")

* Add missing closing code fence
  • Loading branch information
rth authored and jturner314 committed Aug 2, 2019
1 parent 07702a1 commit 5ad1afa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/impl_constructors.rs
Expand Up @@ -171,6 +171,29 @@ where
}
eye
}

/// Create a 2D matrix from its diagonal
///
/// **Panics** if `diag.len() * diag.len()` would overflow `isize`.
///
/// ```rust
/// use ndarray::{Array2, arr1, arr2};
///
/// let diag = arr1(&[1, 2]);
/// let array = Array2::from_diag(&diag);
/// assert_eq!(array, arr2(&[[1, 0], [0, 2]]));
/// ```
pub fn from_diag<S2>(diag: &ArrayBase<S2, Ix1>) -> Self
where
A: Clone + Zero,
S: DataMut,
S2: Data<Elem = A>,
{
let n = diag.len();
let mut arr = Self::zeros((n, n));
arr.diag_mut().assign(&diag);
arr
}
}

#[cfg(not(debug_assertions))]
Expand Down
14 changes: 14 additions & 0 deletions tests/array.rs
Expand Up @@ -1950,6 +1950,20 @@ fn test_array_clone_same_view() {
assert_eq!(a, b);
}

#[test]
fn test_array2_from_diag() {
let diag = arr1(&[0, 1, 2]);
let x = Array2::from_diag(&diag);
let x_exp = arr2(&[[0, 0, 0], [0, 1, 0], [0, 0, 2]]);
assert_eq!(x, x_exp);

// check 0 length array
let diag = Array1::<f64>::zeros(0);
let x = Array2::from_diag(&diag);
assert_eq!(x.ndim(), 2);
assert_eq!(x.shape(), [0, 0]);
}

#[test]
fn array_macros() {
// array
Expand Down

0 comments on commit 5ad1afa

Please sign in to comment.