I am having trouble visualizing scalars, vectors and matrices as how they are written in a math/physics class to how they would be represented in plain Python and numpy
and their corresponding notions of dimensions, axes and shapes.
5
>>> b = np.array(5)
>>> np.ndim(b)
0
I have 0 dimensions for 5
but what are the axes
here? There are functions for ndim
and shape
but not axes.
we say that we have 2 dimensions in physics/math class because it represents a 2D vector but it looks like numpy
uses a different notion of this.
Why is it that ndim
gives 1
and shape
gives what the dimension is?
>>> c = np.array([1,-3])
>>> c
array([ 1, -3])
>>> c.ndim
1
>>> c.shape
(2,)
np.ndim
gives 1
then?
I have looked at this tutorial on axes but haven't been able to get how the axes then apply here.
How would you represent the vector above in Python and numpy
? Would this be [1, -3]
in Python or [[1], [-3]]
? How about in numpy
? Would it be np.array([1, -3])
or np.array([[1], [-3]])
? Which I tend to write, for my eyes' sake, as
np.array([
[1],
[-3]
])
numpy
? The documentation states that we need to use np.array
s instead. It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.
A scalar is not an array, so it has 0 dimensions.
np.array([1,-3])
is a 1D array, so c.shape
returns a tuple with only one element (2,)
, just the first dimension and it's telling you there is only 1 dimension and 2 elements in that dimension.
You are correct np.array([[1], [-3]])
is the vector you have in 2. c.shape
gives (2,1)
meaning there are 2 rows and 1 column. c.ndim
gives 2
since there are 2 dimensions x and y. It's a 2D/planar array
For 3., you would create it as np.array([[1,2,3], [4,5,6], [7,8,9]])
. shape
returns (3,3)
meaning 3 rows and 3 columns. ndim
returns 2 because it's still a 2D/planar array.
A ndarray
has a shape
, a tuple. ndim
is the length of that tuple, and may be 0. The array has ndim
axes (sometimes called dimensions).
np.array(5)
has shape ()
, 0 ndim
and no axes.
np.array([1,2,3,4])
has (4,) shape, and 1 axis. It can be reshaped to (4,1), or (1,4) or (2,2) or even (2,1,2) or (1,4,1).
Your A
can be created with
A = np.arange(1,10).reshape(3,3)
That's a 9 element 1d array reshaped to (3,3)
numpy
arrays have a print display, with [] marking dimensional nesting. A.tolist()
produces a list with 3 elements, each a 3 element list.
Rows, columns, planes are useful ways of talking about arrays, but are not a formal part of their definition.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.