While responding to this post I was wondering if it was possible write for loops inside addplot calls.
I really mean for loops inside addplot and not addplot inside for loop (just to make myself clear).
My answer to this post involves plotting multiple functions that are the sum of harmonics of a given frequency, which gives multiple addplot calls only differing by one term of the sum.
\addplot {sin(4*0.5*\x r)/0.5};
\addplot {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5};
\addplot {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5};
\addplot {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5};
\addplot {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5 + sin(4*4.5*\x r)/4.5};
\addplot {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5 + sin(4*4.5*\x r)/4.5 + sin(4*5.5*\x r)/5.5};
I don't think this is quite elegant, and I was wondering if there was a way to avoid this using something like
\addplot {sum[nmin,nmax,n](sin(\n*0.5*\x r)/0.5)};
where nmin/nmax would be the starting/ending indexes of the sum.
This question could be generalized to products or other for loops.
Here is the MWE to test this
\documentclass[tikz,border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.5}
\usepgfplotslibrary{colorbrewer}
\pgfplotsset{cycle list/Reds-6}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
width=\textwidth,
axis x line=bottom,
axis y line=left,cycle multi list={Reds-6}]
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5 + sin(4*4.5*\x r)/4.5};
\addplot+[samples=300,smooth] {sin(4*0.5*\x r)/0.5 + sin(4*1.5*\x r)/1.5 + sin(4*2.5*\x r)/2.5 + sin(4*3.5*\x r)/3.5 + sin(4*4.5*\x r)/4.5 + sin(4*5.5*\x r)/5.5};
\end{axis}
\end{tikzpicture}
\end{document}




tikzmathto define the function – percusse May 01 '18 at 13:50