How to resolve the algorithm Reduced row echelon form step by step in the Lua programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Reduced row echelon form step by step in the Lua programming language

Table of Contents

Problem Statement

Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: For testing purposes, the RREF of this matrix: is:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Reduced row echelon form step by step in the Lua programming language

Source code in the lua programming language

function ToReducedRowEchelonForm ( M )
    local lead = 1
    local n_rows, n_cols = #M, #M[1]

    for r = 1, n_rows do
        if n_cols <= lead then break end
        
        local i = r
        while M[i][lead] == 0 do
            i = i + 1
            if n_rows == i then
                i = r
                lead = lead + 1
                if n_cols == lead then break end                
            end
        end 
        M[i], M[r] = M[r], M[i]

        local m = M[r][lead]
        for k = 1, n_cols do
            M[r][k] = M[r][k] / m
        end
        for i = 1, n_rows do
            if i ~= r then
                local m = M[i][lead]
                for k = 1, n_cols do
                    M[i][k] = M[i][k] - m * M[r][k]
                end
            end
        end  
        lead = lead + 1     
    end
end

M = { { 1, 2, -1, -4 }, 
      { 2, 3, -1, -11 }, 
      { -2, 0, -3, 22 } }
      
res = ToReducedRowEchelonForm( M )

for i = 1, #M do
    for j = 1, #M[1] do
        io.write( M[i][j], "  " )
    end
    io.write( "\n" )
end


  

You may also check:How to resolve the algorithm General FizzBuzz step by step in the Phix programming language
You may also check:How to resolve the algorithm Validate International Securities Identification Number step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Colorful numbers step by step in the jq programming language
You may also check:How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Sidef programming language
You may also check:How to resolve the algorithm Add a variable to a class instance at runtime step by step in the Julia programming language