I want to set a matrix with random numbers. I used a function to create a 0 matrix first, then loop through every cell and assign a random number to it.
function getRandomArbitrary(min, max) {
let value = Math.random() * (max - min) min;
if (value === 0)
return getRandomArbitrary(min, max);
return value;
}
function matrix(m, n, d) {
return Array.apply(null, new Array(m)).map(
Array.prototype.valueOf,
Array.apply(null, new Array(n)).map(
function() {
return d;
}
)
);
}
let weight_1 = matrix(4, 3, 0);
for (let i = 0; i < 4; i ) {
for (let j = 0; j < 3; j ) {
weight_1[i][j] = getRandomArbitrary(-1, 1);
}
}
console.table(weight_1)
When I run the code, I get the following output.
As can be seen in the picture, the random value changes only when i
changes. Is this related to JS being asynchronous or because random numbers generated by Math.random
has a relation to timestamp?
CodePudding user response:
Array.prototype.valueOf
is Object.prototype.valueOf
, and simply returns the receiver value (this
argument). It does not create a copy of the array - so you are map
ping to an outer array that contains the same inner array at every index. Instead, use
function matrix(m, n, d) {
return Array.apply(null, new Array(m)).map(
function() {
return Array.apply(null, new Array(n)).map(
function() {
return d;
}
);
}
);
}
or the simpler and more conventionally formatted
function matrix(m, n, d) {
return Array.from({length: m}, () =>
Array.from({length: n}, () =>
d
)
);
}
Also you might want to make d
a callback function and call it, so that you create your matrix directly by matrix(4, 3, () => getRandomArbitrary(-1, 1))
instead of initialising it with 0
and then looping it to change the values.