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