[Tutor] Matrix help

Peter Otten __peter__ at web.de
Thu Mar 22 14:11:11 EDT 2018


Connie Callaghan wrote:

> Hi,
> I was just looking help for a matrix that I am building, it needs to look
> like this 1, 0, 0, ...,0
> A,b,c,0,...,0
> 0,a,b,c,...,0
> 0,0,a,b,c,..0
> 0,0,0,a,b,c,...,0
> 0,0,0,0...0, 1
> 
> It has n rows and columns and the first and last line has to have 1s at
> the corners as shown, and a,b,c going diagonal and 0’s everywhere else, I
> am really struggling and it would be a great help to even be shown how to
> begin,

Assuming you are not using numpy the easiest way is to start with a list of 
lists containing only zeros:

>>> N = 5
>>> my_matrix = [[0] * N for row in range(N)]
>>> my_matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 
0, 0, 0]]

This becomes a bit more readable with pprint:

>>> from pprint import pprint
>>> pprint(my_matrix)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

You can then modify the matrix:

>>> my_matrix[0][0] = my_matrix[-1][-1] = 1
>>> pprint(my_matrix)
[[1, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 1]]

For the other values use a for loop, like

>>> for i in range(1, N):
...     my_matrix[i][i-1] = 42
... 
>>> pprint(my_matrix)
[[1, 0, 0, 0, 0],
 [42, 0, 0, 0, 0],
 [0, 42, 0, 0, 0],
 [0, 0, 42, 0, 0],
 [0, 0, 0, 42, 1]]

Oops, one more 42 than b-s in your example. Looks like you need to adjust 
the range() arguments.



More information about the Tutor mailing list