Skip to content

Commit e31b41b

Browse files
AlpineVibrationsmp
andauthored
add min_all and max_all to tensor (#86)
Co-authored-by: mp <pro@macbookpro>
1 parent 2c9f2fc commit e31b41b

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

candle-core/src/tensor.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1749,6 +1749,42 @@ impl Tensor {
17491749
&self.op
17501750
}
17511751

1752+
/// Computes the max of all the elements in this tensor and returns a tensor holding this
1753+
/// scalar with zero dimensions.
1754+
///
1755+
/// ```rust
1756+
/// use candle_core::{Tensor, Device};
1757+
/// let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
1758+
/// let tensor = tensor.max_all()?;
1759+
/// assert_eq!(tensor.to_scalar::<f32>()?, 5.);
1760+
/// # Ok::<(), candle_core::Error>(())
1761+
/// ```
1762+
pub fn max_all(&self) -> Result<Tensor> {
1763+
if self.rank() == 0 {
1764+
Ok(self.clone())
1765+
} else {
1766+
self.flatten_all()?.max(0)
1767+
}
1768+
}
1769+
1770+
/// Computes the min of all the elements in this tensor and returns a tensor holding this
1771+
/// scalar with zero dimensions.
1772+
///
1773+
/// ```rust
1774+
/// use candle_core::{Tensor, Device};
1775+
/// let tensor = Tensor::new(&[[0f32, 1.], [2., 3.], [4., 5.]], &Device::Cpu)?;
1776+
/// let tensor = tensor.min_all()?;
1777+
/// assert_eq!(tensor.to_scalar::<f32>()?, 0.);
1778+
/// # Ok::<(), candle_core::Error>(())
1779+
/// ```
1780+
pub fn min_all(&self) -> Result<Tensor> {
1781+
if self.rank() == 0 {
1782+
Ok(self.clone())
1783+
} else {
1784+
self.flatten_all()?.min(0)
1785+
}
1786+
}
1787+
17521788
/// Computes the sum of all the elements in this tensor and returns a tensor holding this
17531789
/// scalar with zero dimensions.
17541790
///

0 commit comments

Comments
 (0)