A NumPy array is a data structure that can be used to store single or multi-dimensional arrays or matrices. Those arrays can later be used for advanced mathematical operations like matrix operations. As we discussed in one of our previous articles, a NumPy array can be created from a Python list. In Python, we can also use linspace to create a NumPy array. In this article, we will discuss how to create a NumPy array using linspace in Python.
In Python, we can use the numpy.linspace(start, stop, number, endpoint) to create a one-dimensional ndarray. The elements in the ndarray starts from “start”, ends at “stop”. The numbers are equally spaced and the number of numbers thus generated is indicated by “number.” The endpoint=True parameter indicates that we are including the endpoint denoted by stop.
For example,
import numpy array1 = numpy.linspace(1, 10, 10, endpoint=True) print(array1) print(array1.shape)
The above example creates a one-dimensional NumPy array with 10 elements. The elements start from 1 and end at 10. The numbers are equally spaced and the number of numbers thus generated is 10. So, the output will be like the following:
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] (10,)
Please note that the output of array1.shape is (10,). It means the array is one-dimensional and it has 10 elements across its dimension, i.e. row.
Now, let’s say we want to create a two-dimensional array using the same elements. The array should now have 5 rows and 2 columns. We can now use the reshape() function along with the linspace() function to create the two-dimensional array.
import numpy array2 = numpy.linspace(1, 10, 10, endpoint=True).reshape(5, 2) print(array2) print(array2.shape)
The output will be like the following:
[[ 1. 2.] [ 3. 4.] [ 5. 6.] [ 7. 8.] [ 9. 10.]] (5, 2)
From the output of array2.shape we can see that the array has 5 rows and 2 columns in each row.
Now, let’s say we want to create a three-dimensional array …
0 Comments