Skip to content
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

ENH Add Array2::from_diag #673

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/impl_constructors.rs
Expand Up @@ -171,6 +171,30 @@ where
}
eye
}

/// Create a 2D matrix from its diagonal
jturner314 marked this conversation as resolved.
Show resolved Hide resolved
///
/// **Panics** if `diag.len() * diag.len()` would overflow `isize`.
///
/// ```rust
/// use ndarray::{Array2, arr1, arr2};
///
/// # #[cfg(feature = "approx")] {
jturner314 marked this conversation as resolved.
Show resolved Hide resolved
/// 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 @@ -1954,6 +1954,20 @@ fn test_array_clone_same_view() {
assert_eq!(a, b);
}

#[test]
fn test_array2_from_diag() {
jturner314 marked this conversation as resolved.
Show resolved Hide resolved
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