这是解决方案为 pgfplots 定义分段函数。
但是,我希望能够使用宏来定义函数的每个部分。如果使用局部宏,则可以轻松实现这一点,如下declare function
方的 MWE 所示,它使用\LocalPieceA
和\LocalPieceB
作为函数在两个独立域中执行的操作的定义。
但是,我该如何修改\PieceA
和\PieceB
使用它们\pgfmathdeclarefunction
?我尝试使用##
在需要访问外部宏的参数的宏中定义宏时有效的技巧,而 Jake\edef\PieceA{\noexpand#1}
在上述问题中尝试了,但也没有用。
\documentclass{article}
\usepackage{amsmath}
\usepackage{pgfplots}
\newcommand{\rLabel}{
$r(x)=
\begin{cases}
x & 0 < x < 1\\
-x+2 & 1 < x < 2\\
0 & \text{otherwise}
\end{cases}$
}
% Want to be able to use \PieceA and \PieceB in the \pgfmathdeclarefunction instead
% of (#1) and (-#1+2). With [declare function], this is easy as shown below
\newcommand{\PieceA}{(##1)}
\newcommand{\PieceB}{(-##1+2)}
\pgfmathdeclarefunction{q}{1}{%
\pgfmathparse{((and(#1>0, #1<1)*#1)+(and(#1>1, #1<4)*(-#1+2)))}%
}
\tikzstyle{MyPlotStyle}=[domain=-5:5, samples=50, ultra thick]
\tikzstyle{rLabelStyle}=[above, yshift=-15ex, xshift=-25ex]
\begin{document}
%------------------ Using \pgfmathdeclarefunction -----------
Plot of $r(x)$ using PGF Version \pgfversion.
\begin{tikzpicture}
\begin{axis}[clip=false]
\addplot[MyPlotStyle, red]{q(x)} node [rLabelStyle] {\rLabel};
\end{axis}
\end{tikzpicture}
% --------------------- Using "declare function" -------------
Using declare function to define localp(x) and localq(x):
\newcommand{\LocalPieceA}{(\x)}% These two works great!!
\newcommand{\LocalPieceB}{(-\x+2)}
\begin{tikzpicture}
[declare function={localr(\x) = and(\x > 0, \x < 1)*\LocalPieceA+and(\x > 1, \x < 4)*\LocalPieceB;}]
\begin{axis}[clip=false]
\addplot[MyPlotStyle, blue]{localr(x)} node [rLabelStyle] {\rLabel};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
这是你需要的吗?
\newcommand{\PieceA}[1]{(#1)}
\newcommand{\PieceB}[1]{(-#1+2)}
\pgfmathdeclarefunction{q}{1}{%
\pgfmathparse{((and(#1>0, #1<1)*\PieceA{#1})+(and(#1>1, #1<4)*\PieceB{#1}))}%
}