Using arrays and variables in TikZ
You need to use an \edef
instead of a \def
. When you use just a \def
, the value is set to the macro \pgfmathresult
, and not the value of \pgfmathresult
at the time of the \def
. The subsequent pgfmathparse
changes the value of \pgfmathresult=4
so this is the value that both \myl
and \myh
take on once they are evaluated.
Code:
\documentclass[border=2pt]{standalone}
\usepackage{pgfplots}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}
\def\zamkl{{3,4,4.5,5}}
\def\zamkh{{4,3.5,5,4.5}}
\pgfmathparse{\zamkl[0]}
\edef\myl{\pgfmathresult}
\pgfmathparse{\zamkh[0]}
\edef\myh{\pgfmathresult}
\draw[help lines] (0,0) grid (6,8);
\coordinate (A) at (0,0);
\coordinate (B) at (\myl,0); \node at (B) [below] {$T$};
\coordinate (C) at (2*\myl,0);
\coordinate (D) at (2*\myl,\myh); \node at (D) [left] {$S$};
\coordinate (E) at (2*\myl,2*\myh);
\coordinate (F) at (\myl,2*\myh); \node at (F) [below] {$R$};
\coordinate (G) at (0,2*\myh);
\coordinate (H) at (0,\myh); \node at (H) [right] {$W$};
\draw [very thick] (A) -- (C) -- (E) --(G) -- (A);
\fill (B) circle (4pt);
\fill (D) circle (4pt);
\fill (F) circle (4pt);
\end{tikzpicture}
\end{document}
Exactly what happens I don't know, but using
\pgfmathsetmacro\myl{\zamkl[0]}
\pgfmathsetmacro\myh{\zamkh[0]}
instead of the \def
s works.
\documentclass[border=5mm,tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\def\zamkl{{3,4,4.5,5}}
\def\zamkh{{4,3.5,5,4.5}}
\pgfmathsetmacro\myl{\zamkl[0]}
\pgfmathsetmacro\myh{\zamkh[0]}
\draw[help lines] (0,0) grid (6,8);
\coordinate (A) at (0,0);
\coordinate (B) at (\myl,0); \node at (B) [below] {$T$};
\coordinate (C) at (2*\myl,0);
\coordinate (D) at (2*\myl,\myh); \node at (D) [left] {$S$};
\coordinate (E) at (2*\myl,2*\myh);
\coordinate (F) at (\myl,2*\myh); \node at (F) [below] {$R$};
\coordinate (G) at (0,2*\myh);
\coordinate (H) at (0,\myh); \node at (H) [right] {$W$};
\draw [very thick] (A) -- (C) -- (E) --(G) -- (A);
\fill (B) circle (4pt);
\fill (D) circle (4pt);
\fill (F) circle (4pt);
\end{tikzpicture}
\end{document}