Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you do Numpy.eye in JavaScript?

How to create the np.eye function in JavaScript? Or what would be the numpy.eye equivalent in JavaScript?

I would like a function that creates the "Identity matrix" in 2d dimensions, and you can change the number of rows, columns and the index of the diagonal.
https://numpy.org/devdocs/reference/generated/numpy.eye.html

This doesn’t take care of M,N,k
@Andy

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function eye(n){
var t=[];
for(var i=0;i<n;i++){
var p=[]
for(var j=0;j<n;j++){
p.push(j==i?1:0)
}
t.push(p)
}}

>Solution :

This doesn’t take care of M,N,k

You are almost there, just have to put the extra parameters there, like the outer loop (rows) runs to N, the inner loop (columns) runs to M, and the comparison would be j-i===k:

function eye(N,M,k) {
  var t = [];
  for (var i = 0; i < N; i++) {
    var p = []
    for (var j = 0; j < M; j++) {
      p.push(j - i === k ? 1 : 0)
    }
    t.push(p)
  }
  return t;
}

let NMk=prompt("N,M,k").split(",").map(x=>parseInt(x));
console.log(eye(...NMk).map(x=>x.join()));

Try entering something like 3,3,0 ("classic") or 2,3,1 (a "fancy" one) when asked.
(And don’t worry about the snippet printing strings, that’s just the join() , to keep output small, and without much coding).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading