我想使用 Tikz 图片中二维数组的值列表。
下面的代码在使用随机数时有效:
\pgfmathtruncatemacro{\r}{round(rnd*20)}
但是当我用以下几行替换它时,它会产生“数组超出范围”错误(但索引是正确的):
\pgfmathtruncatemacro\a{\x-1}
\pgfmathtruncatemacro\b{\y-1}
\pgfmathparse{\myNotes[\b][\a]} \let\r\pgfmathresult <<<<< ***** problem...
感谢帮助。
有效的代码:
\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usetheme{CambridgeUS}
\usepackage{tikz}
% list of numbers : 2d array
\def \myNotes {{12,6,13,15}{16,11,15,13} {14,8,10,9}{16,13,10,5}{7,11,15,12}}
\begin{document}
\begin{frame}
\frametitle{Array}
\newcommand{\Depth}{1}
\newcommand{\Height}{0.9}
\newcommand{\Width}{1}
\pgfmathsetseed{1} % for random
\begin{tikzpicture}[scale = 0.80]
\foreach \y in {5,4,3,2,1}
{
\node at (0,\y*-1) {t} ;
\node at (0.25,\y*-1) {\y};
\foreach \x in {1,2,3,4}
{
\begin{scope}[shift={(\x,\y*-1)}]
\pgfmathtruncatemacro\a{\x-1}
\pgfmathtruncatemacro\b{\y-1}
% following ligne produce "array out of bounds" for each b and a
% *******************************************************
%\pgfmathparse{\myNotes[\b][\a]} \let\r\pgfmathresult
\pgfmathtruncatemacro{\r}{round(rnd*20)}%
\coordinate (C) at (0,0,0);
\node[black,fill=yellow] (C) {\r};
\end{scope}
}
}
\end{tikzpicture}
\end{frame}
\end{document}
** 编辑:更新按我想要的方式工作的代码(来自 percusse):
(不必要的线条已被删除...)
\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usetheme{CambridgeUS}
\usepackage{tikz}
% **** declare a 2d array *********************************** OK
\def\myNotes{{{12,6,13,15},{16,11,15,13},{14,8,10,9},{16,13,10,5},{7,11,15,12}}}
\begin{document}
\begin{frame}
\frametitle{Array}
\begin{tikzpicture}[scale = 0.80]
\foreach \y in {5,4,3,2,1}{
\node at (0,\y*-1) {t} ;
\node at (0.25,\y*-1) {\y};
\foreach \x in {1,2,3,4}
{
\begin{scope}[shift={(\x,\y*-1)}]
% get the value at index y-1 and x-1 ************************ OK
\pgfmathtruncatemacro{\r}{int(\myNotes[\y-1][\x-1])}
\coordinate (C) at (0,0,0);
\node[black,fill=yellow] (C) {\r};
\end{scope}
}
}
\end{tikzpicture}
\end{frame}
\end{document}
答案1
你的数组中缺少一组括号和逗号。如果你这样写,它应该可以正常工作
\def\myNotes{{{12,6,13,15},{16,11,15,13},{14,8,10,9},{16,13,10,5},{7,11,15,12}}}
另外,你可以直接r
设置
\pgfmathtruncatemacro{\r}{\myNotes[\y-1][\x-1]}
或手动转换为整数
\pgfmathsetmacro{\r}{int(\myNotes[\y-1][\x-1])}