Find the dimension of the vector space of $U$-invariant maps. I'm trying to solve the following:

Let $V$ be an $n$-dimensional vector space over a field $K$, and let $U$ be a $k$-dimensional subspace of $V.$ Find the dimension of the vector space $$M=\{\varphi:V\to V\mid \varphi \text{ is linear and }   \varphi(U)\subseteq U\}.$$

First I noted that $\dim(V^*)=\dim(V) = n$ and $M\subseteq V^*$. Thus $\dim(M)\leq n$. Let $\beta=\{\varphi_1,...,\varphi_n \}$ be a basis for $V^*$. Now if $\varphi \in V^*$, then we can write $\varphi = \lambda_1\varphi_1 + \cdots + \lambda_n\varphi_n$ for some $\lambda_1,...,\lambda_n$. Thus elements of $M$ can also be represented as linear combinations of $\varphi_1,...,\varphi_n$. Also, $\dim(U^*)=\dim(U)=k$, so we must have $\dim(M)\geq k$. However, I don't know how to proceed from here. 
I'd appreciate any help. 
 A: Let $\{v_1,\ldots,v_k\}$ be a basis of $U$ and extend this basis to $\{v_1,\ldots,v_k,v_{k+1},\ldots,v_n\}$ a basis of $V$. Then for all $v = \alpha_1v_1 + \cdots + \alpha_nv_n \in V$ and $\varphi \in M$ we have
\begin{align}
\varphi(v) = \left\{
\begin{array}{ll}
\alpha_1\varphi(v_1)+\cdots+\alpha_k\varphi(v_k) & \text{if}~ v\in U\\[1mm]
\alpha_1\varphi(v_1)+\cdots+\alpha_n\varphi(v_n) & \text{if}~ v \not\in U
\end{array}\right.
\tag{1}
\end{align}
Now for all $i,j\in\{1,\ldots,n\}$ define the linear maps $e_{ij} : V\to V$ by
$$
e_{ij}(v_m) = \left\{
\begin{array}{rl}
v_j, & m = i\\
0, & m \neq i
\end{array}\right.
$$
and observe that $e_{ij}(v) = \alpha_iv_j$ for all $v\in V$.
Since $\varphi(v_i) = \beta_{i1}v_1 + \cdots + \beta_{in}v_n \in V$ for some scalars $\beta_{i1},\ldots,\beta_{in}$, it follows that
$$
\varphi(v_i) = \sum_{j=1}^n \beta_{ij}e_{ij}(v_i)~~\forall i = 1,\ldots,n
$$
Thus
$$
\varphi(v) = \sum_{i=1}^n\alpha_i\sum_{j=1}^n\beta_{ij}e_{ij}(v_i) = \sum_{i=1}^n\sum_{j=1}^n\beta_{ij}e_{ij}(v)~~\forall v\in V \implies \varphi = \sum_{i=1}^n\sum_{j=1}^n\beta_{ij}e_{ij}
$$
Considering the restriction $(1)$ placed on all $\varphi\in M$ we find that $\beta_{ij} = 0$ if $1 \leq i \leq k$ and $k < j \leq n$. Otherwise, it would be possible for $\varphi(u) \not\in U$ for some $u\in U$. Thus, $M$ is spanned by the set $E = \{e_{ij}\,|\, 1 \leq i,j \leq k ~\text{or}~ k < i \leq n\}$. Since $E$ is linearly independent (this is easily confirmed) it forms a basis of $M$, which implies that $\dim M = n^2 - k(n-k)$.
