2

I want to draw the following piecewise function:

enter image description here

I used the following codes:

\begin{tikzpicture}[
    declare function={
        func(\x)= (\x<-0.5) * (0)  +
        and(\x>=-0.5, \x<=0.5) * (1)     +
        (\x>0.5) * (0);
    }
    ]
    \begin{axis}[
        axis x line=middle, axis y line=middle,
        ymin=-0.25, ymax=1.25, ylabel=$y$,
        xmin=-1, xmax=1, xlabel=$x$,
        ]
        \addplot[domain=-1:1]{func(x)};
    \end{axis}
\end{tikzpicture} 

But the output is not the same as the above plot:

enter image description here

2
  • 1
    This is expected --- you are joining each calculated point with the following one! try \addplot coordinates{(-1,0) (-0.5,0) (-0.5,1) (0.5,1) (0.5,0) (1,0)}: (or something like that)
    – Rmano
    Jan 19, 2021 at 10:43
  • 2
    Or \addplot[domain=-1:=0.5] 0; \addplot[domain=-0.5:0.5] 1; addplot[domain=0.5:1] 0; which is more correct (there are no vertical lines in the function!)
    – Rmano
    Jan 19, 2021 at 10:45

1 Answer 1

2

By use of the const plot pgfplots option:

\documentclass[border=3.141592]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}

\begin{document}
    \begin{tikzpicture}[
declare function={func(\x) = (\x<-0.5)*(0) +
                             and 
                             (\x>=-0.5, \x<=0.5)*(1) +
                             (\x>0.5)*(0);}
                        ]
\begin{axis}[
    axis lines=middle,
    ymin=-0.25, ymax=1.25, ylabel=$y$,
    xmin=-1, xmax=1, xlabel=$x$,
    const plot,
    every axis plot post/.append style={thick},
            ]
        \addplot[domain=-1:1]{func(x)};
\end{axis}
    \end{tikzpicture}
\end{document}

enter image description here

Addendum: As you can se with your function declaration pulse is shifted for one sample to right. This you can corecte on two ways:

  • use @Rmano suggestion and draw your pulse by help of coordinates
  • correct definition of your function:
declare function={func(\x) = (\x<-0.5)*(0) +
                             and
                             (\x>-0.51, \x<0.49)*(1) +  % <--- 
                             (\x>0.5)*(0);}

its effect using \addplot +[domain=-1:1]{func(x)};, whis show samples marks is:

enter image description here

3
  • Yep, better than my suggestion, +1
    – Rmano
    Jan 19, 2021 at 10:46
  • The vertical lines should intersect x-axis at exactly 0.5 and -0.5 but they have a distance of about 0.25!
    – Moreza7
    Jan 19, 2021 at 10:50
  • 2
    @Moreza7, you are right. For exactly you need to use Rmano comment, approximate you can with increase number of samples or by change your function declaration (see addendum in answer).
    – Zarko
    Jan 19, 2021 at 11:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .