I have a TikZ-matrix. And I want to highlight the rows
1, 3, 6, 10, 15, 21, 28,... =n*(n+1)/2
For small examples, I could do it this way:
highlight/.style={ row #1/.style={....} },
highlight/.list={1,3,6,10,15}
But my question is: Think about a quite bigger number of rows (say 1000) - how can I automate that by using the calculation "n*(n+1)/2
"?
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[
highlight/.style={ row #1/.style={nodes={fill=pink}} },
]
\matrix[matrix of nodes,
highlight/.list={1,3,6,10,15}
](m){
1 \\
2 \\
3 \\
4 \\
5 \\
6 \\
7 \\
8 \\
9 \\
10 \\
11 \\
};
\end{tikzpicture}
\end{document}
答案1
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\ExplSyntaxOn
\cs_new:Npn\my_calculate:n #1
{ , \int_eval:n{#1*(#1+1)/2} }
\newcommand\createlist[1]{
\int_step_function:nnN{1}{#1}\my_calculate:n
}
\ExplSyntaxOff
\begin{document}
\begin{tikzpicture}[
highlight/.style={row #1/.style={nodes={fill=pink}}},
]
\matrix[matrix of nodes,
highlight/.list/.expanded={\createlist{5}}
] (m) {
1 \\
2 \\
3 \\
4 \\
5 \\
6 \\
7 \\
8 \\
9 \\
10 \\
11 \\
};
\end{tikzpicture}
\end{document}
答案2
Since it's just integer calculations that hopefully don't surpass 2³¹−1 you can use \int_eval:n
, \inteval
(which is a front-end version of int_eval) or \pgfinteval
(which is a clone of the previous) inside the key specification:
highlight/.style={
row \inteval{#1*(#1+1)/2}/.append style={nodes={fill=pink}}}
If you don't want to alter the highlight
key you can use a forwarder, of course:
highlight/.style={row #1/.append style={nodes={fill=pink}}},
highlight'/.style={highlight=\pgfinteval{#1*(#1+1)/2}}
It would also be possible to create something like
highlight/.list wrap={1, ..., 1000}{\inteval{#1*(#1+1)/2}}`
if the previous suggestion are not nice enough.
Code
\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}
\tikzset{
create column/.style={
matrix content/.initial=,
/utils/temp/.style={
matrix content/.append={##1\pgfmatrixendrow}},
/utils/temp/.list={#1},
node contents=\pgfkeysvalueof{/tikz/matrix content}}}
\begin{document}
\tikz[
highlight/.style={
row \inteval{#1*(#1+1)/2}/.append style={nodes={fill=pink}}}]
\matrix (m) [
matrix of nodes,
highlight/.list={1, ..., 1000},
create column={1, ..., 1000}];
\tikz[
highlight/.style={row #1/.append style={nodes={fill=pink}}},
highlight'/.style={highlight=\pgfinteval{#1*(#1+1)/2}}]
\matrix (m) [
matrix of nodes,
highlight'/.list={1, ..., 1000},
create column={1, ..., 1000}];
\end{document}