Skip to content

ENH Add Array2::from_diag #673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/impl_constructors.rs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
Expand Up @@ -1954,6 +1954,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