[Tex/LaTex] Data from file as list in \foreach in Tikz

external filestikz-pgf

I have data stored in files I named x.dat and y.dat. In the file are two columns and each row stands for one point. These points I plot in the beginning. But then I want some arrows from the x-points to the y-points. So I need a foreach over the points. But those points are not stored in a way the foreach-statement can handle.

How can I get the foreach-statement to walk through the points in the files, without changing the files?

\draw plot [only marks, mark=*, mark options={fill=red, scale=0.3}]
    file {x.dat};
\foreach \x  in file {x.dat}
    \foreach \y in file {y.dat}
    {
        \draw [->] \x -- \y;
    }

Best Answer

This is a code based on Torbjørn's code but here I try to use pgfplotstable. I'm not a great expert of this package also it's perhaps possible to use some useful macro to read \xA and \yA directly.

\documentclass{scrartcl}
\usepackage{pgfplotstable,tikz,filecontents}

\begin{document} 
  \begin{filecontents*}{coord1.dat}
% x   y
0    0
1    1
2    2
\end{filecontents*}
\begin{filecontents*}{coord2.dat}
%  x   y
0    1
1    2
2    3
\end{filecontents*}
  \pgfplotstableread{coord1.dat}{\firsttable}   
  \pgfplotstableread{coord2.dat}{\secodtable} 
  \pgfplotstablegetrowsof{coord1.dat}
  \pgfmathsetmacro{\rows}{\pgfplotsretval-1}      
\begin{tikzpicture}

\foreach \i in {0,...,\rows}{%
  \pgfplotstablegetelem{\i}{[index] 0}\of{\firsttable} 
  \let\xA\pgfplotsretval 
  \pgfplotstablegetelem{\i}{[index] 1}\of{\firsttable} 
  \let\yA\pgfplotsretval     
  \foreach \j in {0,...,\rows}{%
    \pgfplotstablegetelem{\j}{[index] 0}\of{\secodtable} 
    \let\xB\pgfplotsretval 
    \pgfplotstablegetelem{\j}{[index] 1}\of{\secodtable} 
    \let\yB\pgfplotsretval        
    \draw [-latex] (\xA,\yA) node[below]{\xA,\yA} -- (\xB,\yB) node[above]{\xB,\yB};
  }%
 }%   
\end{tikzpicture}
\end{document} 

enter image description here