Diagonal stacking in numpy?

2024/4/15 1:56:58

So numpy has some convenience functions for combining several arrays into one, e.g. hstack and vstack. I'm wondering if there's something similar but for stacking the component arrays diagonally?

Say I have N arrays of shape (n_i, m_i), and I want to combine them into a single array of size (sum_{1,N}n_i, sum_{1,N}m_i) such that the component arrays form blocks on the diagonal of the result array.

And yes, I know how to solve it manually, e.g. with the approach described in How to "embed" a small numpy array into a predefined block of a large numpy array? . Just wondering if there's an easier way.

Ah, How can I transform blocks into a blockdiagonal matrix (NumPy) mentions that scipy.linalg.block_diag() is the solution, except that the version of scipy installed on my workstation is so old it doesn't have it. Any other ideas?


It does seem block_diag does exactly what you want. So if for some reason you can't update scipy, then here is the source from v0.8.0 if you wish to simply define it!

import numpy as npdef block_diag(*arrs):"""Create a block diagonal matrix from the provided arrays.Given the inputs `A`, `B` and `C`, the output will have thesearrays arranged on the diagonal::[[A, 0, 0],[0, B, 0],[0, 0, C]]If all the input arrays are square, the output is known as ablock diagonal matrix.Parameters----------A, B, C, ... : array-like, up to 2DInput arrays.  A 1D array or array-like sequence with length n istreated as a 2D array with shape (1,n).Returns-------D : ndarrayArray with `A`, `B`, `C`, ... on the diagonal.  `D` has thesame dtype as `A`.References----------.. [1] Wikipedia, "Block matrix",http://en.wikipedia.org/wiki/Block_diagonal_matrixExamples-------->>> A = [[1, 0],...      [0, 1]]>>> B = [[3, 4, 5],...      [6, 7, 8]]>>> C = [[7]]>>> print(block_diag(A, B, C))[[1 0 0 0 0 0][0 1 0 0 0 0][0 0 3 4 5 0][0 0 6 7 8 0][0 0 0 0 0 7]]>>> block_diag(1.0, [2, 3], [[4, 5], [6, 7]])array([[ 1.,  0.,  0.,  0.,  0.],[ 0.,  2.,  3.,  0.,  0.],[ 0.,  0.,  0.,  4.,  5.],[ 0.,  0.,  0.,  6.,  7.]])"""if arrs == ():arrs = ([],)arrs = [np.atleast_2d(a) for a in arrs]bad_args = [k for k in range(len(arrs)) if arrs[k].ndim > 2]if bad_args:raise ValueError("arguments in the following positions have dimension ""greater than 2: %s" % bad_args) shapes = np.array([a.shape for a in arrs])out = np.zeros(np.sum(shapes, axis=0), dtype=arrs[0].dtype)r, c = 0, 0for i, (rr, cc) in enumerate(shapes):out[r:r + rr, c:c + cc] = arrs[i]r += rrc += ccreturn out

Related Q&A

Rules Engine in C or Python [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Draw arrows between 3 points

I am trying to draw arrows between three points in matplotlib.Lets assume we have 3 arbitrary points (A1,A2,A3) in 2d and we want to draw arrows from A1 to A2 and from A2 to A3.Some code to make it cle…

Make an animated wave with drawPolyline in PySide/PyQt

Im trying to animate a polyline (it have to act like a wave). Ive tried this way:from PySide.QtCore import * from PySide.QtGui import * import sys, timeclass Test(QMainWindow):def __init__(self, parent…

dateutil.tz package apparently missing when using Pandas?

My python 2.7 code is as follows:import pandas as pd from pandas import DataFrameDF_rando = DataFrame([1,2,3])...and then when I execute, I get a strange error regarding dateutil.tz./Library/Frameworks…

Importing SPSS dataset into Python

Is there any way to import SPSS dataset into Python, preferably NumPy recarray format? I have looked around but could not find any answer.Joon

Given a set of points defined in (X, Y, Z) coordinates, interpolate Z-value at arbitrary (X, Y)

Given a set of points in (X, Y, Z) coordinates that are points on a surface, I would like to be able to interpolate Z-values at arbitrary (X, Y) coordinates. Ive found some success using mlab.griddata …

Python multiprocessing speed

I wrote this bit of code to test out Pythons multiprocessing on my computer:from multiprocessing import Poolvar = range(5000000) def test_func(i):return i+1if __name__ == __main__:p = Pool()var = p.map…

Using os.forkpty() to create a pseudo-terminal to ssh to a remote server and communicate with it

Im trying to write a python script that can ssh into remote server and can execute simple commands like ls,cd from the python client. However, Im not able to read the output from the pseudo-terminal af…

Calculating the sum of a series?

This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:sum = 0 k = 1 while k <= 0.0001:if k % 2 == 1:sum = sum + 1.0/kelse:sum = sum - 1.…

get all the partitions of the set python with itertools

How to get all partitions of a set? For example, I have array [1, 2, 3]. I need to get [[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]]. Now, I wrote this code:def neclusters(S…