1

I have a matrix that looks like:

x=[[a,b,c,d,e,f],
   [g,h,i,j,k,l],
   [m,n,o,p,q,r]]

with a,b,c numbers. I am however only interested in the numbers at the lower left half and would like to creat a lower triangular matrix that goes by steps of two positions and thus looks like this:

x2=[[a,b,0,0,0,0],
    [g,h,i,j,0,0],
    [m,n,o,p,q,r]]

I could of course multiply x with:

x3=[[1,1,0,0,0,0],
    [1,1,1,1,0,0],
    [1,1,1,1,1,1]]

But is there a way to do this without manually creating x3?

And would it be possible to create a script where the steps are bigger then 2 zeros at a time?

Jellyse
  • 839
  • 7
  • 22

1 Answers1

1

Taking the example matrix x3 that you provided in the example, you could go and do something like this:

x3=[[1,1,1,1,1,1],
    [1,1,1,1,1,1],
    [1,1,1,1,1,1]]


for i in range(len(x3)):
    step = (i+1) * 2
    for j in range(step, len(x3[i])):
        x3[i][j] = 0

for i in x3:
    print(i)

Output:

[1, 1, 0, 0, 0, 0]
[1, 1, 1, 1, 0, 0]
[1, 1, 1, 1, 1, 1]

Or in case you prefer an one-liner:

x3 = [[0 if j>(i+1)*2 else x3[i][j] for j in range(0, len(x3[i]))] for i in range(len(x3))]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29