How to create an empty matrix with numpy in python ?

Published: July 24, 2020

Tags: Python; Numpy;

Examples of how to create an empty matrix with numpy in python:

Create an empty matrix using the numpy function empty()

To create for example an empty matrix of 10 columns and 0 row, a solution is to use the numpy function empty() function:

````import numpy as np`

`A = np.empty((0,10))`
```

Then

````print(A)`
```

gives

````[]`
```

and if we check the matrix dimensions using shape:

````print(A.shape)`
```

we get:

````(0,10)`
```

Note: by default the matrix type is float64:

```` print(A.dtype)`
```

returns

````float64`
```

Fill an empty matrix with a for loop

It is then possible for example to create an empty matrix and to update it using the function numpy.concatenate

````import numpy as np`

`A = np.empty((0,10))`

`for i in range(14):`

`    new_row = np.random.randint(100, size=(1, 10))`

`    A = np.concatenate((A,new_row))`

`print(A)`
```

returns

````[[35. 70. 33. 58. 18. 78. 14. 44. 17.  5.]`
` [42. 27.  8. 79. 19.  8. 88.  4. 40. 84.]`
` [51. 96.  2. 66. 46. 10. 78. 98. 12. 85.]`
` [17. 36. 11.  6. 84. 81. 99. 20. 12. 14.]`
` [72. 14. 47.  8. 18. 22. 77. 99. 30. 99.]`
` [44. 11.  1. 70. 26. 20. 74. 61. 95. 60.]`
` [60. 20. 80. 32. 71. 22. 61. 31. 41. 27.]`
` [35. 96. 65. 80. 85. 40. 27.  3. 44.  9.]`
` [11. 83. 22. 95. 43. 96. 95. 26. 58. 35.]`
` [25. 95. 80. 20. 52. 32. 36. 92. 42. 69.]`
` [37. 49. 31. 51. 39. 72.  8. 61. 91. 26.]`
` [74. 66. 24. 17.  4. 75. 67. 61. 62. 70.]`
` [21. 71. 59. 51. 85. 60. 36. 39. 17. 82.]`
` [ 7. 25. 27. 57. 99.  3.  5. 32. 64. 97.]]`
```