Singular value decomposition

From Rosetta Code
Task
Singular value decomposition
You are encouraged to solve this task according to the task description, using any language you may know.

is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by Failed to parse (syntax error): {\displaystyle X^{−1}AX} . The eigenvectors in have three big problems: They are usually not orthogonal, there are not always enough eigenvectors, and = Failed to parse (syntax error): {\displaystyle λx} requires to be a square matrix. The singular vectors of solve all those problems in a perfect way.

The Singular Value Decomposition (SVD)

According to the web page above, for any rectangular matrix , we can decomposite it as Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "https://wikimedia.org/api/rest_v1/":): {\displaystyle A=UΣV^T}

Task Description

Firstly, input two numbers "m" and "n".

Then, input a square/rectangular matrix .

Finally, output Failed to parse (syntax error): {\displaystyle U,Σ,V} with respect to .

Example

Sample Input

2 2
3 0
4 5

From the input above we can know that is a 2 by 2 matrix.

Sample Output

   
0.31622776601683794 -0.9486832980505138
0.9486832980505138 0.31622776601683794

6.708203932499369 0
0 2.23606797749979

0.7071067811865475 -0.7071067811865475
0.7071067811865475 0.7071067811865475

The output may vary depending your choice of the data types.


Julia

Julia has an svd() function as part of its built-in LinearAlgebra package.

julia> using LinearAlgebra

julia> function testsvd()
           rows, cols = [parse(Int, s) for s in split(readline())]
           arr = zeros(rows, cols)
           for row in 1:rows
               arr[row, :] .= [tryparse(Float64, s) for s in split(readline())]
           end
           display(svd(arr))
       end
testsvd (generic function with 1 method)

julia> testsvd()
2 2
3 0
4 5
SVD{Float64, Float64, Matrix{Float64}, Vector{Float64}}
U factor:
2×2 Matrix{Float64}:
 -0.346946  -0.937885
 -0.937885   0.346946
singular values:
2-element Vector{Float64}:
 6.74492216626026
 2.0015056760076915
Vt factor:
2×2 Matrix{Float64}:
 -0.780042  -0.625727
 -0.625727   0.780042