How to resolve the algorithm Matrix transposition step by step in the Lua programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Matrix transposition step by step in the Lua programming language

Table of Contents

Problem Statement

Transpose an arbitrarily sized rectangular Matrix.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Matrix transposition step by step in the Lua programming language

Source code in the lua programming language

function Transpose( m )
    local res = {}
    
    for i = 1, #m[1] do
        res[i] = {}
        for j = 1, #m do
            res[i][j] = m[j][i]
        end
    end
    
    return res
end

-- a test for Transpose(m)
mat = { { 1, 2, 3 }, { 4, 5, 6 } }
erg = Transpose( mat )
for i = 1, #erg do
    for j = 1, #erg[1] do
        io.write( erg[i][j] )
        io.write( "  " )
    end
    io.write( "\n" )
end


function map(f, a)
  local b = {}
  for k,v in ipairs(a) do b[k] = f(v) end
  return b
end

function mapn(f, ...)
  local c = {}
  local k = 1
  local aarg = {...}
  local n = #aarg
  while true do
    local a = map(function(b) return b[k] end, aarg)
    if #a < n then return c end
    c[k] = f(unpack(a))
    k = k + 1
  end
end

function apply(f1, f2, a)
 return f1(f2, unpack(a))
end

xy = {{1,2,3,4},{1,2,3,4},{1,2,3,4}}
yx = apply(mapn, function(...) return {...} end, xy)
print(table.concat(map(function(a) return table.concat(a,",") end, xy), "\n"),"\n")
print(table.concat(map(function(a) return table.concat(a,",") end, yx), "\n"))


  

You may also check:How to resolve the algorithm Long year step by step in the Swift programming language
You may also check:How to resolve the algorithm Comments step by step in the Lilypond programming language
You may also check:How to resolve the algorithm Determine if a string is numeric step by step in the Gambas programming language
You may also check:How to resolve the algorithm Terminal control/Inverse video step by step in the Tcl programming language
You may also check:How to resolve the algorithm Colour pinstripe/Display step by step in the Java programming language