Just for fun and for comparison, I implemented a lualatex solution.
In this solution I use lua to transform the matrix from its textual form as a sequence of 0 and 1 into another string containing a lot of tikz commands which draw the figure.
The lua based solution seems to be slower than the pure tikz solutions, but perhaps this is due to the lualatex startup. The execution of the lua functions is very fast, but the compilation of the resulting tikz code is apparently the bottleneck. Probably my lua code could generate a more efficient tikz code.
To compile my example you'll require:
- A working lualatex
- A copy of the file
matrix2tikz.lua
(below)
- The document
sample.tex
(below)
sample.tex
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\directlua{dofile("matrix2tikz.lua")}
\newcommand{\bitmapmatrix}[2][10]{%
\begin{scope}[bitmapmatrix]
\directlua{matrix2tikz("#2",#1)}%
\end{scope}
}
\tikzset{
bitmapmatrix/.style = {line width = 2sp},
pixel on/.style = {red},
pixel off/.style = {white},
pixel err/.style = {pink}
}
\def\mydata{
10110101010
10010101010
01010111010
11110010100
01100011001
11101010111
10101010111
}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[node distance=2mm]
\bitmapmatrix[5]{\mydata}
\node[below=of matrix] {This is a test};
\end{tikzpicture}
\end{document}
matrix2tikz.lua
local function matrix_to_tikz(tab , size)
local width = size
if (size == nil) then size=10 end
local pixel_width = size / #tab[1]
local height = pixel_width * #tab
local pixel_cmd = string.format("\\filldraw[%%s] (%%f, %%f) +(-%f, %f) → rectangle +(%f, -%f);",
pixel_width/2, pixel_width/2, pixel_width/2, pixel_width/2)
local str_tab = {}
for y=1,#tab do
row = {}
for x=1,#tab[y] do
if tab[y][x] == 1 then
style = "pixel on"
elseif tab[y][x] == 0 then
style = "pixel off"
else
style = "pixel err"
end
row[x] = string.format(pixel_cmd, style, x*pixel_width, -y*pixel_width)
end
str_tab[y] = table.concat(row, "\n")
end
local extra = {}
extra[1] = string.format("\\coordinate (aux1) at (%f,-%f);", pixel_width/2, → height+pixel_width/2)
extra[2] = string.format("\\coordinate (aux2) at (%f, %f);", width+ → pixel_width/2, -pixel_width/2)
extra[3] = "\\node[inner sep=0pt, fit=(aux1) (aux2)] (matrix) {};"
str_tab[#tab+1] = table.concat(extra, "\n")
return table.concat(str_tab,"\n")
end
function justWords(str)
local t = {}
local function helper(word) table.insert(t, word) return "" end
if not str:gsub("%w+", helper):find"%S" then return t end
end
local function text_to_matrix(txt)
local m = {}
local l = justWords(txt)
for i=1,#l do
if (l[i]~= nil and #l[i]>1) then
j = 1; row = {}
for c in l[i]:gmatch(".") do
row[j] = tonumber(c)
j = j + 1
end
m[i] = row
end
end
return m
end
function matrix2tikz(data, size)
local t = text_to_matrix(data)
local s = matrix_to_tikz(t, size)
tex.print(s)
end
Compiling
Put both in the same folder and run lualatex sample.tex
. This is the result: