Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

286
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda