简体   繁体   中英

Numpy appending two-dimensional arrays together

I am trying to create a function which exponentiates a 2-D matrix and keeps the result in a 3D array, where the first dimension is indexing the exponent. This is important because the rows of the matrix I am exponentiating represent information about different vertices on a graph. So for example if we have A, A^2, A^3, each is shape (50,50) and I want a matrix D = (3,50,50) so that I can go D[:,1,:] to retrieve all the information about node 1 and be able to do matrix multiplication with that. My code is currently as

def expo(times,A,n):
    temp = A;
    result = csr_matrix.toarray(temp)
    for i in range(0,times):
        temp = np.dot(temp,A)
        if i == 0:
            result = np.array([result,csr_matrix.toarray(temp)]) # this creates a (2,50,50) array
        if i > 0:
            result = np.append(result,csr_matrix.toarray(temp),axis=0) # this does not work
    return result

However, this is not working because in the "i>0" case the temp array is of the shape (50,50) and cannot be appended. I am not sure how to make this work and I am rather confused by the dimensionality in Numpy, eg why thinks are (50,1) sometimes and just (50,) other times. Would anyone be able to help me make this code work and explain generally how these things should be done in Numpy?

Documentation reference

If you want to stack matrices in numpy, you can use the stack function . If you also want the index to correspond to the exponent, you might want to add a unity matrix to the beginning of your output:

MWE

import numpy as np

def expo(A, n):
    result =[np.eye(len(A)), A,]
    for _ in range(n-1):
        result.append(result[-1].dot(A))

    return np.stack(result, axis=0) 
    # If you do not really need the 3D array, 
    # you could also just return the list


result = expo(np.array([[1,-2],[-2,1]]), 3)
print(result)
# [[[  1.   0.]
#   [  0.   1.]]
#
#  [[  1.  -2.]
#   [ -2.   1.]]
#
#  [[  5.  -4.]
#   [ -4.   5.]]
#
#  [[ 13. -14.]
#   [-14.  13.]]]

print(result[1])
# [[ 1. -2.]
#  [-2.  1.]]

Comments

As you can see, we first simply create the list of matrices, and then convert them to an array at the end. I am not sure if you really need the 3D array though, as you could also just index the list that was created, but that depends on your use case, if that is convenient or not.

I guess the axis keyword argument for a lot of numpy functions can be confusing at first, but the documentation usually has good examples that combined with same trial and error, should get you pretty far. For example for numpy.stack , the very first example is indeed exactly what you want to do.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM