OKPEDIA PYTHON MATRIX

How to make a matrix of ones in python

To make an array of ones in the python language you can use the ones() function of the numpy library.

ones(n)

The parameter n indicates the number of elements and the structure of the array (vector, matrix with two or more dimensions).

  • n = one-dimensional array
  • n,m = two-dimensional array with n rows and columns (matrix)
  • n,m,t = three-dimensional array (tensor)

The ones() function creates an array with all elements equal to the real number 1.

Note. By default the function creates floating point elements (float).

Examples

Example 1 (vector)

Create a vector with five elements equal to 1.

>>> import numpy as np
>>> y=np.ones(5)

The ones() function generates the following vector

>>> y
array([1., 1., 1., 1., 1.])

They are floating point float 1 values.

Example 2 (vector with integers)

Use the dtype attribute to define the data type of the array

>>> import numpy as np
>>> y=np.ones(5, dtype=int)

The ones() function generates a vector in integer format.

>>> y
array([1, 1, 1, 1, 1])

You can also define another data type (bool, float, complex).

Example 3 (matrix)

Create a 2x3 matrix

>>> import numpy as np
>>> y=np.ones([2,3])

The function creates a two-dimensional 2x3 matrix

array([[1., 1., 1.],
[1., 1., 1.]])

The object consists of two lists.

Each list is a row of the matrix.

https://how.okpedia.org/en/python/how-to-make-a-matrix-of-ones-in-python


Report an error or share a suggestion to enhance this page


Matrix in Python


FacebookTwitterLinkedinLinkedin