pytutorial/numpy/new_matrix
David Rotermund b298ae53fd
Update README.md
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com>
2023-12-13 16:38:44 +01:00
..
README.md Update README.md 2023-12-13 16:38:44 +01:00

New matrices

{:.no_toc}

* TOC {:toc}

The goal

Making a new matrix...

Questions to David Rotermund

Using import numpy as np is the standard.

Simple example -- new np.zeros()

Define the size of your new matrix with a tuple, e.g.

M = numpy.zeros((DIM_0, DIM_1, DIM_2, ))

1d

import numpy as np

M = np.zeros((2))
print(M)

Output:

[0. 0.]

2d

import numpy as np

M = np.zeros((2, 3))
print(M)

Output:

[[0. 0. 0.]
 [0. 0. 0.]]

3d

import numpy as np

M = np.zeros((2, 3, 4))
print(M)

Output:

[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]

Simple example -- recycle np.zeros_like()

If you have a matrix with the same size you want then you can use zeros_like. This will also copy other properties like the data type.

as a prototype use

N = numpy.zeros_like(M)

import numpy as np

M = np.zeros((2, 3, 4))

N = np.zeros_like(M)
print(N)

Output:

[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]

 [[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]

Remember unpacking

{: .topic-optional} This is an optional topic!

import numpy as np

d = (3, 4)
M = np.zeros((2, *d))

print(M)

From shape or value

empty(shape[, dtype, order, like]) Return a new array of given shape and type, without initializing entries.
empty_like(prototype[, dtype, order, subok, ...]) Return a new array with the same shape and type as a given array.
eye(N[, M, k, dtype, order, like]) Return a 2-D array with ones on the diagonal and zeros elsewhere.
identity(n[, dtype, like]) Return the identity array.
ones(shape[, dtype, order, like]) Return a new array of given shape and type, filled with ones.
ones_like(a[, dtype, order, subok, shape]) Return an array of ones with the same shape and type as a given array.
zeros(shape[, dtype, order, like]) Return a new array of given shape and type, filled with zeros.
zeros_like(a[, dtype, order, subok, shape]) Return an array of zeros with the same shape and type as a given array.
full(shape, fill_value[, dtype, order, like]) Return a new array of given shape and type, filled with fill_value.
full_like(a, fill_value[, dtype, order, ...]) Return a full array with the same shape and type as a given array.