SVD/Matlab. Function that takes matrix as input, calculates svd, returns approximation matrix Input is supposed to be a mxn matrix and a natural number k so that 0

I started with this code
function AK = svdapprox(A,k)
tol=0.001                                   
r=rank(A,tol)
if k>r           % return error message if k exceeds rank of matrix          
        fprintf('Value of k must not exceed that of r' ); 
end
[U, S, V]=svd(A)             %calculate the svd of a

To proceeed from here, I was thinking since number of singular values in s=rank A, i could limit the diagnoal  of s to k elements and then make it return usv, but i couldn't find a way to make this work. As you can see I don't have much experience with matlab and I'm not sure if this is the best way to go about this. Any help would be appreciated. 

You want the first $k$ columns of $U$, the upper $k \times k$ part of $S$, and the first $k$ rows of $v$. 
For this you want
 u = U(1:k, :)
 s = S(1:k, 1:k)
 v = V(:, 1:k)

