Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superdiagonal non-square matrix in numpy?

Using numpy, I want to create a superdiagonal matrix that is only almost square. It has extra zeros to the right or left of the square part. The code snippet below give me the desired result, but it is a little tricky to read, and the matrix type seems to me common enough that there should be an idiomatic way to construct it.

What is the simplest way to construct 'padded eyes' as below, in numpy?

import numpy as np
size = 5
pad_width = 3
left_padded_eye = np.block([np.zeros((size,pad_width)),np.eye(size)])
right_padded_eye = np.block([np.eye(size),np.zeros((size,pad_width))])
like image 716
LudvigH Avatar asked Sep 11 '26 16:09

LudvigH


1 Answers

np.eye can do that directly

>>> size = 5
>>> pad_width = 3
>>> np.eye(size, size+pad_width, pad_width)
array([[0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1.]])
>>> np.eye(size, size+pad_width)
array([[1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0.]])
like image 101
Paul Panzer Avatar answered Sep 14 '26 05:09

Paul Panzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!