1

I have read the following related discussions What's the simplest way to extend a numpy array in 2 dimensions?

However, if I want to expend multiple matrices, for example

A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
F = np.append(A,[[B]],0)

However, python says

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 4 dimension(s)

I want to put B "under" the matrix A, and put C "under" the matrix B.
So, F should be a 6X2 matrix.

How to do this? Thanks!

2
  • Since all your arrays have the same shape, you can simply np.concatenate([A,B,C], axis=0). I objected to the use of np.append in your linked answer, and will do so again. Commented Dec 22, 2020 at 18:51
  • What's the shape of np.array([[B]])? Commented Dec 22, 2020 at 18:53

2 Answers 2

2

Try using numpy.concatenate (https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html):

A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
# F = np.append(A,[[B]],0)
F = np.concatenate((A, B, C), axis=1)

Change the axis parameter to 0 to combine the matrices 'vertically':

print(np.concatenate((A, B, C), axis=1))

[[1 2 3 4 7 8]
[3 4 5 6 5 6]]

print(np.concatenate((A, B, C), axis=0))

[[1 2]
[3 4]
[3 4]
[5 6]
[7 8]
[5 6]]

Sign up to request clarification or add additional context in comments.

Comments

2

I believe np.concatenate should do the trick

    A = np.matrix([[1,2],[3,4]])
    B = np.matrix([[3,4],[5,6]])
    C = np.matrix([[7,8],[5,6]])
    ABC = np.concatenate([A,B,C],axis = 0) # axis 0 stacks it one above the other
    
    print("Shape : ",ABC.shape)
    print(ABC)

Output :

    Shape : (6, 2)
    matrix(
    [[1, 2],
    [3, 4],
    [3, 4],
    [5, 6],
    [7, 8],
    [5, 6]])

1 Comment

But why do two concatenate? It's more efficient the do one with [A,B,C].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.