ravi
ravi

Reputation: 6328

Convert table to matrix in Lua

I want to perform matrix related operations such as multiplication, transpose and inversion of a matrix. I could find out matrix support in Lua here

I have a table which I want to convert to matrix. The table has following structure-

for i=1,myTableSize[1],1 do
    str=''
    for j=1,myTableSize[2],1 do
        if #str~=0 then
            str=str..', '
        end
        str=str..string.format("%.1e",myTable[(j-1)*myTableSize[1]+i])
    end
    print(str)
end

I am looking for something like myMatrix=matrix(myTable) or myMatrix=matrix.init(myTable), which is compatible with Lua Matrix.

- Thanks

Upvotes: 0

Views: 632

Answers (1)

ldurniat
ldurniat

Reputation: 1702

Try (not tested)

local function tableToMatrix(table, rows cols)
  local myMatrix = matrix:new(rows, cols) -- function returns matrix of size rows x cols
  for i=1, rows do 
    for j=1, cols do
      matrix.setelement(myMatrix, i, j, table[(i - 1) * cols + j] )
    end
  end

  return matrix
end

Upvotes: 1

Related Questions