Reputation: 805
Suppose we have computed the svd of a matrix A in Julia via svd(A). How would we compute a rank r approximation of that matrix A in Julia, given we already have its singular value decomposition?
Upvotes: 0
Views: 688
Reputation: 10982
I would suggest something as follows:
using LinearAlgebra
A=rand(10,20)
svd_fact = svd(A)
function r_rank_approx(svd::SVD,r::Int)
@assert 1 ≤ r
n,m = size(svd)
u,s,v = svd
r = min(r,min(n,m))
# like u[:,1:r]*Diagonal(s[1:r])*v[:,1:r]'
# but reduce number of memory allocs
view(u,:,1:r)*Diagonal(view(s,1:r))*view(v,:,1:r)'
end
r_rank_approx(svd_fact,2)
The idea is to only use the first r-singular values from the complete SVD.
Note: if you have big matrices, there are dedicated algorithms that compute a truncated SVD directly, see TSVD.jl by example.
Upvotes: 1