在 Tikz 中更改矩阵中的各个元素

在 Tikz 中更改矩阵中的各个元素

我正在准备讲义,需要在迭代之间操作矩阵。通常,只有少数元素会发生变化。因此,最好更改这些元素,而不是一次又一次地复制矩阵。我将不胜感激您的见解。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,shapes,arrows,fit,automata}
\usepackage{adjustbox}

\begin{document}

\begin{tikzpicture}

\matrix(rij) [matrix of math nodes, nodes in empty cells, nodes={minimum size=1cm, outer sep=0pt, text height=1.5ex, text depth=.25ex}]
{
 6      &  11    &   5    & 0  \\
 4      &   3    &   3    & M  \\
 3      &   6    &   7    & 0  \\
 3      &   7    &   8    & M  \\
 M      &   0    &   0    & 0  \\
};

\end{tikzpicture}
\end{document}

答案1

这里有一个例子:在图片中画出矩阵,然后通过某些键设置值value to be changed。这样做的好处是你可以像平常一样访问矩阵的坐标。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,shapes,arrows,fit,automata,positioning}
\usepackage{adjustbox}
\tikzset{
  value to be changed/.store in=\anytl,
  value to be changed=11, % default value,
  mymatrix/.pic={
    \matrix(-rij) [
      matrix of math nodes,
      nodes in empty cells,
      nodes={
        minimum size=1cm,
        outer sep=0pt,
        text height=1.5ex,
        text depth=.25ex
      },
      ampersand replacement=\&
    ]
    {
     6      \&  \anytl\&   5    \& 0  \\
     4      \&   3    \&   3    \& M  \\
     3      \&   6    \&   7    \& 0  \\
     3      \&   7    \&   8    \& M  \\
     M      \&   0    \&   0    \& 0  \\
    };
    \coordinate (-south) at (current bounding box.south);
  }
}

\begin{document}
\begin{tikzpicture}
  \pic (a) at (0, 0) {mymatrix};
  \pic [value to be changed=change, below=of a-south] {mymatrix};
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

您可以对矩阵的条目执行操作,其中可能取决于计数\pgfmatrixcurrentrow\pgfmatrixcurrentcolumn。矩阵内容存储在中\myarray。如果你只是说

\mymatrix

你会得到相应的矩阵,但如果你说例如

\mymatrix[\ifnum\pgfmatrixcurrentcolumn=2
\pgfmathparse{int(\pgfmatrixcurrentrow+\originalentry)}\pgfmathresult
\else
\originalentry
\fi]

您将把行索引添加到第二列的条目中。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\edef\myarray{{"6","11","5","0"},%
{"4","3","3","M"},%
{"3","6","7","0"},%
{"3","7","8","M"},%
{"M","0","0","0"}}
\newcommand\mymatrix[1][\originalentry]{\begin{tikzpicture}
\matrix(rij) [matrix of math nodes, nodes in empty cells, 
nodes={minimum size=1cm, outer sep=0pt, text height=1.5ex, text depth=.25ex},
cells={nodes={execute at begin node={\pgfmathsetmacro\originalentry{{\myarray}[\pgfmatrixcurrentrow-1][\pgfmatrixcurrentcolumn-1]}%
#1}}},
ampersand replacement=\&]
{
 \& \& \& \\
 \& \& \& \\
 \& \& \& \\
 \& \& \& \\
 \& \& \& \\
};
\end{tikzpicture}}
\begin{document}
\mymatrix
\bigskip

\mymatrix[\ifnum\pgfmatrixcurrentcolumn=2
\pgfmathparse{int(\pgfmatrixcurrentrow+\originalentry)}\pgfmathresult
\else
\originalentry
\fi]
\end{document}

在此处输入图片描述

相关内容