S is diagonal matrix of singular values?
2 views (last 30 days)
Show older comments
Minkang Cheng
on 6 Nov 2020
Answered: Christine Tobler
on 6 Nov 2020
Hi
I did {U,S,V)=svd(A)
when A is mxn
results: U is mxm, V is nxn, S is mxn (n> m)
S should be a diagonal matrix of singular values, the m singular values are diagonal location.
How ever, I use fprinf print ths S in a file as
fprintf(fids,[repmat('%8.4f\t',1,size(S,2)) '\n'],S);
Then I read this using a fotran code as
do k = 1, m
read(1,*) (s(k,j) j=1,n)
enddo
I found the singular values are not in diagonal. If this is corect, the U and V must re-agranged based on singular values, from large down to smaller. Why this did not in matlab. if not, what is the wrong with fprintf or svd. How we can make S to be realy a diagonal matrix?
Thanks
MK
0 Comments
Accepted Answer
Christine Tobler
on 6 Nov 2020
MATLAB (and Fortran) store matrices in a column-first ordering, while in your file, you want to save numbers in a row-first order. The fprintf command passes the numbers of S in based on linear indexing into S:
>> S
S =
3.8795 0 0
0 1.4585 0
0 0 0.3144
0 0 0
>> fprintf([repmat('%8.4f\t',1,size(S,2)) '\n'],S)
3.8795 0.0000 0.0000
0.0000 0.0000 1.4585
0.0000 0.0000 0.0000
0.0000 0.3144 0.0000
Passing the transpose of S in fixes the issue:
>> fprintf([repmat('%8.4f\t',1,size(S,2)) '\n'],S')
3.8795 0.0000 0.0000
0.0000 1.4585 0.0000
0.0000 0.0000 0.3144
0.0000 0.0000 0.0000
You can also do this more directly using the writematrix command:
>> writematrix(S, 'S.txt')
>> type S.txt
3.87951723431537,0,0
0,1.4585169755725,0
0,0,0.31437233188791
0,0,0
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!