Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
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

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)
}}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!