local function matrix_product_repr(m1, m2) if #m1[1] ~= #m2 then -- inner matrix-dimensions must agree return nil end local res = {} for i = 1, #m1 do res[i] = {} for j = 1, #m2[1] do res[i][j] = " " for k = 1, #m2 do if k ~= 1 then res[i][j] = res[i][j] .. " + " end res[i][j] = res[i][j] .. m1[i][k] .. " " .. m2[k][j] end end end return res end local function dump_matrix(matrix) local repr = "" for i, row in ipairs(matrix) do for j, cell in ipairs(row) do repr = repr .. " " .. cell if j ~= #row then repr = repr .. " & " end end if i ~= #matrix then repr = repr .. [[ \\ ]] end repr = repr .. "\n" end return repr end local m1 = { {"a", "b", "c", "d"}, {"e", "f", "g", "h"}, {"i", "j", "k", "l"} } local m2 = { {"x_1"}, {"x_2"}, {"x_3"}, {"x_4"} } print(dump_matrix(matrix_product_repr(m1, m2))) return { matrix_product_repr = matrix_product_repr, dump_matrix = dump_matrix }