在块矩阵中排列numpy数组

时间:2016-06-29 19:19:26

标签: python numpy

我有3个numpy数组ABC。为简单起见,我们假设它们都是[n, n]形状。我想将它们安排为块矩阵

A    B
B^t  C

其中B^t表示B的转置。当然,我可以通过一系列连接来做到这一点

top_row = np.concatenate([A, B], axis=1)
bottom_row = np.concatenate([B.transpose(), C], axis=1)
result = np.concatenate([top_row, bottom_row], axis=0)

是否有更简单,更易读的方式?

2 个答案:

答案 0 :(得分:5)

从NumPy 1.13开始,有np.block。这可以从嵌套的块列表中构建矩阵,但它也更通用,处理更高维数组和某些不完全网格的情况。与Function GetAutofillDatabaseInformation(docHandle, kwToCheck, autofillTableName, iDataType, aKeywordValues) Dim i, adoParam, tempState, errDesc GetAutofillDatabaseInformation = True If Len(autofillTableName) = 0 Then autofillTableName = Null On Error Resume Next Set adoParam = adoCmd.CreateParameter("@Handle", adBigInt, adParamInput, , docHandle) adoCmd.Parameters.Append(adoParam) Set adoParam = adoCmd.CreateParameter("@KeyTypeNum", adBigInt, adParamInput, , kwToCheck) adoCmd.Parameters.Append(adoParam) Set adoParam = adoCmd.CreateParameter("@KeysetName", adChar, adParamInput, 200, autofillTableName) adoCmd.Parameters.Append(adoParam) Set adoParam = adoCmd.CreateParameter("@Datatype", adInteger, adParamOutput) adoCmd.Parameters.Append(adoParam) adoCmd.CommandType = adCmdStoredProc adoCmd.CommandText = "usp_Check_Autofill_Value_Data" adoCmd.ActiveConnection = adoConn Set adoRs = adoCmd.Execute tempState = adoRs.State errDesc = err.description On Error Goto 0 ReDim aKeywordValues(0) If Len(errDesc) = 0 Then i = 0 Do until adoRs.EOF i = i + 1 ReDim preserve aKeywordValues(i) aKeywordValues(i) = Trim(adoRs(0)) adoRs.MoveNext Loop adoRs.Close iDataType = adoCmd.Parameters("@Datatype") If err.number <> 0 Then sErrMsg = "Cannot retrieve data information: " & err.description GetAutofillDatabaseInformation = False End If Else sErrMsg = "No information retrieved from database for document " & docHandle & ", keyword " & kwToCheck & " and autofill table [" & autofillTableName & "]." GetAutofillDatabaseInformation = False End If End Function 不同,它还会产生一个ndarray。

'answer' => $request->user()->answers()->latest()->first()

对于以前的版本,您可以使用非常适合此类任务的NumPy内置np.bmat,如此 -

bmat

comments by @unutbu中所述,请注意输出将是NumPy矩阵。如果预期的输出是一个数组,我们需要转换它,就像这样 -

np.block([[A, B], [B.T, C]])

np.bmat([[A, B], [B.T, C]])

答案 1 :(得分:0)

剥去一些铃铛和哨子,np.bmat这样做:

def foo(alist):
    rowlist=[]
    for row in alist:
        rowlist.append(np.concatenate(row,axis=1))
    return np.concatenate(rowlist, axis=0)

例如:

In [1026]: A=np.arange(4).reshape(2,2);B=np.arange(2).reshape(2,1);C=np.array([0]).reshape(1,1)

In [1027]: foo([[A,B],[B.T,C]])
Out[1027]: 
array([[0, 1, 0],
       [2, 3, 1],
       [0, 1, 0]])

制作输入矩阵简化了reshape准备工作。