# Piecewise linear plot with custom grid

I try to plot a piecewise linear interpolation of a function w on a grid \xn={x1,x2,...,xN} using tikz. I tried using a foreach loop and store the grid as a vector to do that, but it doesn't seem to work. Can anyone help?

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows, calc}
\begin{document}
\begin{tikzpicture}[scale=1.8]
\pgfkeys{ /pgf/declare function={
w(\x)=-.5+\x*\x*\x-\x+\x*\x;}
}
\def \xn {-1.8,-1,-.5,.1,.9,1}; %% grid
\foreach \i in {1,2,...,5}{
\draw({\xn(\i)},{w(\xn(\i))})--({\xn({\i+1})},{w(\xn({\i+1}))});
}
\end{tikzpicture}
\end{document}


This is how the output should look like (without the axes).

-
–  Peter Grill Apr 28 '14 at 20:57

One way is to directly access the \xn array instead of indexing into it:

## Notes:

• I would recommend getting used to using (\x) instead of \x in function computations as it can sometimes make a difference.

## Code:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows, calc}
\begin{document}
\begin{tikzpicture}[scale=1.8]
\pgfkeys{ /pgf/declare function={
w(\x)=-.5+(\x)*(\x)*(\x)-(\x)+(\x)*(\x);}
}
\def \xn {-1.8,-1,-.5,.1,.9,1}; %% grid
\draw [ultra thick, blue] (-1.8,{w(-1.8)})
\foreach \i in \xn {
--(\i,{w(\i)})
};
\end{tikzpicture}
\end{document}

-
Thank you very much. –  Gregor de Cillia Apr 28 '14 at 21:04

Also pgfplots can help.

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
\begin{tikzpicture}
\begin{axis}[axis lines=middle,
ytick=\empty,xtick=\empty,
ylabel=$I(w)x$,xlabel=$x$]

@GregordeCillia Is that the first error you get? Maybe you don't have pgfplots installed. –  percusse Apr 28 '14 at 21:34
@GregordeCillia Your pgfplots version is probably old. Change the line to \pgfplotsset{compat=newest} –  percusse Apr 28 '14 at 21:52