Search code examples
pythonmatrixtriangular

Python/Maths: Convert a matrix into a lower triangular matrix


I defined the matrix a. Then I wrote an algorithm which turns the matrix a into a lower triangular matrix (I provided the programme below)

The algorithm does work because if I do "print(" ")" at the end of the algorithm I do receive a lower triangular matrix But when I do "print(a)" directly afterwards (so after the algorithm for the lower triangular matrix) I still receive the previous matrix a... and then it is not a lower triangular matrix. So I would like the matrix a to "permanently" be a lower triangular matrix, and not just whenever I use this algorithm (with the "print(" ")" at the end)

How can I sort of "change" the matrix a in a way that it stays a lower triangular matrix? I hope I expressed myself well.

Here is my python code:

import numpy as np 
s = 5

#s is the number of columns and rows respectively#

a = np.array([[None]*s]*s)

print(a)
#I receive a matrix with 5 columns/rows respectively#


#Calculates number of rows and columns present in given matrix#  
rows = len(a);  
cols = len(a[0]);  
   
if(rows != cols):  
    print("Matrix should be a square matrix");  
else:  
    #Performs required operation to convert given matrix into lower triangular matrix  
    print("Lower triangular matrix: ");  
    for i in range(0, rows):  
        for j in range(0, cols):  
            if(j > i):  
                print("0"),  
            else:  
                print(a[i][j]),  
      
        print(" ");  

#so far it works perfectly fine. If I use this algorithm I do receive a lower triangular matrix#

print(a)
    
#my wish was that now that I do print(a) again that it would print the matrix a but as a lower triangular matrix. because of the previous algorithm. but I get the same matrix as I did when I did "print(A)" for the first time.#type here

Solution

  • Keep in mind that printing and assigning values to variables are different actions:

    • print shows a message on the screen but does not change the value of any variable.
    • Assignment, such as x = 2 or a[i][j] = 0 changes the value that is stored in that place in memory.

    If you want to change the matrix, then you need to use the assignment operator to change the values. In practice you just need to add a[i][j] = 0 in the correct place.

    if(j > i):
        a[i][j] = 0 # <-- add this line
        print("0"),  
    

    Now the elements in the upper right part will be set to zero.