-3

I have the following matrix in javascript, modelled with the library math.js:

<script src='math.js' src='sylvester.js' type='text/javascript'></script>

var CN = math.matrix([[8], [7],[3],[1]]) 

I would like to change this matrix into a diagonal matrix:
<script src='math.js' src='sylvester.js' type='text/javascript'></script>

var CN = math.matrix([[8,0,0,0], [0,7,0,0],[0,0,3,0], [0,0,0,1]]);

I cannot find the appropriate code for this to do so.
Can someone help me with the appropriate code?

Sebsemillia
  • 9,366
  • 2
  • 55
  • 70
  • 6
    Programming is not about "finding" code but about writing it. And this community is for developers, not copy-pasters, sorry. – zerkms Jun 25 '14 at 11:57
  • For each element a[i], initialise a row with a.length zeroes and update the value at the i'th index. – Ja͢ck Jun 25 '14 at 11:59

1 Answers1

0

To create a diagonal matrix from a vector with math.js, you can use the function math.diag. First though you will have to turn your input matrix into a vector, something like:

var A = [[8], [7], [3], [1]];
var B = math.transpose(A); // B = [[8, 7, 3, 1]]
var C = math.squeeze(B);   // C = [8, 7, 3, 1]
var D = math.diag(C);      // D = [[8,0,0,0], [0,7,0,0],[0,0,3,0], [0,0,0,1]]
Jos de Jong
  • 6,602
  • 3
  • 38
  • 58