How to compute the projection of a vector onto a n-dimensional box (hyperparallelepiped) Definition:
Let $C$ be a closed convex set in $\mathcal E$. For every $z\in \mathcal E$, there exists a unique minimizer (denoted as $\operatorname{Proj}_{C} (z)$ and called as the projection of $z$ onto $C$) of
$$
\min \{\frac{1}{2} \| x-z \|^2 | x\in C\}
$$
where $\| \cdot \|$ is the Euclidean norm.
Set $x^\star = \operatorname{Proj}_{C} (z)$ is the projection of $z$ onto $C$ if and only if
$$
\langle z-x^\star, x-x^\star \rangle \leq 0, \forall x \in C.
$$
Problem:
Given a hyperparallelipiped (box) set $[a,b]$ with $b>a$ and $a,b\in \mathbb R^n$, for any $z\in \mathbb R^n$, the projection of $z$ onto the box $[a,b]$ is $\operatorname{Proj}_{[a, b]} (z)$.
I wonder how to calculate $\operatorname{Proj}_{[a, b]} (z)$. Please teach me the details of the calculation process.
 A: The technique to solve this is by recalling that box constraints are separable. Over $\mathbb{R}^n$, we have $n$ variables $x_1,x_2,\dots,x_n$, where both the objective function and constraints are not dependent of each other. Therefore we will solve the projection problem in $\mathbb{R}$, and this will give the solution in $\mathbb{R}^n$.
Consider the problem: $$\text{prox}(x) = \text{argmin}_{l\leq z\leq u} \frac{1}{2}(x-z)^2$$
Clearly if $l\leq x\leq u$ then $z=x$. Now assume $x<l$ or that $x>u$. It's easy to see that an optimal solution is attained on the boundary of the constraint set - we're talking about a line interval here, so the solution is very intuitive. To summarize: $$\text{prox}_{I_{[l,u]}}(x)=\begin{cases} &x, &l\leq x \leq u \\
& l, & x<l \\ & u, & x>u
\end{cases}$$
Which means that when $\mathbf{x}\in\mathbb{R}^n$ and the feasible set $C=\{\mathbf{x}\,|\,l_i\leq x_i\leq u_i,\,i=1,\dots,n\}$ we have $$\text{prox}_{C}(\mathbf{x})=\begin{cases} &x_i, &l_i\leq x_i \leq u_i \\
& l_i, & x_i<l_i \\ & u_i, & x_i>u_i
\end{cases}$$
I will leave to you the proof as to why we can look at each coordinate independently of other coordinates, but it is really very simple. Recall that if we minimize a function comprised of separable functions, we just need to minimize each component on its own.
