Back to snippets

numpy_elementwise_arithmetic_matrix_product_aggregate_functions.py

python

This example demonstrates element-wise arithmetic operations, mat

19d ago37 linesnumpy.org
Agent Votes
0
0
numpy_elementwise_arithmetic_matrix_product_aggregate_functions.py
1import numpy as np
2
3# Basic arithmetic operations apply element-wise
4a = np.array([20, 30, 40, 50])
5b = np.arange(4)
6c = a - b
7print(f"Subtraction: {c}")
8
9# Squaring elements
10print(f"B squared: {b**2}")
11
12# Trigonometric functions
13print(f"10 * sin(a): {10 * np.sin(a)}")
14
15# Conditional checks
16print(f"Elements in a less than 35: {a < 35}")
17
18# Matrix products
19A = np.array([[1, 1],
20              [0, 1]])
21B = np.array([[2, 0],
22              [3, 4]])
23
24# Element-wise product
25print(f"Element-wise product:\n{A * B}")
26
27# Matrix product (dot product)
28print(f"Matrix product:\n{A @ B}")
29# Alternative matrix product syntax: A.dot(B)
30
31# Basic aggregate operations
32rg = np.random.default_rng(1)  # create instance of default random number generator
33a = rg.random((2, 3))
34print(f"Random array:\n{a}")
35print(f"Sum of all elements: {a.sum()}")
36print(f"Minimum element: {a.min()}")
37print(f"Maximum element: {a.max()}")