1

Suppose I have a matrix

mat = np.empty((0, 3, 5))

and I have a another matrix of shape (3, 5), how can I add that matrix to mat[0]?

I've tried different combinations of stack, vstack, hstack, concatenate and insert and they don't seem to work

James
  • 32,991
  • 4
  • 47
  • 70
bananamuffin
  • 301
  • 1
  • 5
  • 10
  • Add a new axis to the second one and concatenate : `np.concatenate((arr1, arr2[None]),axis=0)`. Or with `vstack` : `np.vstack((arr1, arr2[None]))`. – Divakar Dec 06 '17 at 19:43
  • You have an array with a zero sized dimension. How exactly do you want it to behave? – James Dec 06 '17 at 19:44
  • What shape do you want the output matrix to be? – Coolness Dec 06 '17 at 20:01
  • Another current question like this: https://stackoverflow.com/questions/47681110/inserting-values-to-an-empty-multidim-numpy-array. – hpaulj Dec 06 '17 at 20:20

2 Answers2

0

I suggest you to do this to create your matrix. :)

Your matrix is empty in your current state. Like [].

import numpy as np

rows = 5
cols = 3
mat = np.array([[0] * cols] * rows)
mat_2 = np.empty((0, 3, 5))

print mat
print mat_2
# out for mat:
[[0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]
 [0 0 0]]
# out for mat_2:
[]

To make my answer final, as I stated in comments, just add the two matrices you want to add like m1 + m2.

rows = 5
cols = 3
mat = np.array([[1] * cols] * rows)
mat_2 = np.array([[2] * cols] * rows)

print mat + mat_2
# out :
[[3 3 3]
 [3 3 3]
 [3 3 3]
 [3 3 3]
 [3 3 3]]
IMCoins
  • 3,149
  • 1
  • 10
  • 25
  • While he wrote `how can I add that matrix to mat[0]`, the subject line is about `stacking`. Evidently he's trying to start with the array equivalent of an empty list, `[]`, and do an `append`, probably repeatedly. It's `add` as in `concatenate` or `join`, not `sum`. – hpaulj Dec 06 '17 at 21:25
0

I understand that you want to insert a 3x5 matrix to an empty array. Then np.append can do that. Just specify the right axis.

import numpy as np

mat = np.empty((0,3,5))

mat3x5 = np.matrix('1,1,1,1,2;3,1,2,3,1;2,3,1,2,3')

mat3x5 = np.expand_dims(mat3x5, 0)

result = np.append(mat, mat3x5, axis=0)
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75