[Tex/LaTex] TikZ: Relative positioning of nodes

positioningtikz-pgf

I am working on script to build chart depending on the input data and one of the troubles is to place node right of the rightest node.

This is MWE:

\documentclass[border=.5cm]{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}

\node at (0,0) [draw] (n1) {node1};
\node at (-1,1) [draw] (n2) {node2};
\node at (1,2) [draw] (n3) {node3};
\node at (0.5,-1) [draw] (n4) {node4};

\end{tikzpicture}

\end{document}

So, I have several nodes placed in several rows. Only one node in a row. And I need to place a new node in the specific row but right of the rightest node in all row. In the above example I need to place a node in the one row with n1, but on .5cm right of the n3 (this node is rightest node of all nodes in picture).

I could use low level commands to compare nodes right corner coordinates, but maybe there easier way?

Any suggestions?

UPDATE:
I could use the let command to position node relatively to the other nodes:

\path let \p1=(n3.south east), \p2=(n1.south east) in
node[anchor = south west, draw, xshift=.5cm] at (\x1,\y2) {node5};

But how I can compute the most right node?

UPDATE 2:
I tried to use max command:

\path let \p1=(n1.south east),
          \p2=(n2.south east),
          \p3=(n3.south east),
          \p4=(n4.south east) in
node[anchor = south west, draw, xshift=.5cm] at (max(\x1,\x2,\x3, \x4), \y2) {node5};

but receiving following error:

! Package tikz Error: A node must have a (possibly empty) label text.

See the tikz package documentation for explanation.
Type  H <return>  for immediate help.
...                                              

l.25 ...aw, xshift=.5cm] at (max(\x1,\x2,\x3,\x4),
                                                  \y2) {node5};

What am I doing wrong?

Best Answer

You need the {} to wrap the max(...). Also, it seems that n1 node assigned to \p1 should use \y1. OP's code \y2 causes error result.

enter image description here

Code

\documentclass[border=.5cm]{standalone}

\usepackage{tikz}
\usetikzlibrary{positioning}
 \usetikzlibrary{calc}
\begin{document}

\begin{tikzpicture}

\node at (0,0) [draw] (n1) {node1};
\node at (-1,1) [draw] (n2) {node2};
\node at (1,2) [draw] (n3) {node3};
\node at (0.5,-1) [draw] (n4) {node4};

\path let \p1=(n1.south east),
          \p2=(n2.south east),
          \p3=(n3.south east),
          \p4=(n4.south east)
in node[anchor = south west, draw, xshift=.5cm] at ({max(\x1,\x2,\x3,\x4)}, \y1) {node5};
\end{tikzpicture}

\end{document}