0

I have a numeric 2D array (an array of arrays, or a matrix) and I need to do simple matrix operations like adding a value to each row, or multiplying every value by a single number. I have little experience with math operations in JavaScript, so this may be a bone-headed code snippet. It is also very slow, and I need to use it when the number of columns is 10,000 - 30,000. By very slow I mean roughly 500 ms to process a row of 2,000 values. Bummer.

var ran2Darray = function(row, col){
    var res = [];
    for (var i = 0 ; i < row; i++) {
        res[i] = [];
        for (var j = 0; j < col; j++) {
            res[i][j] = Math.random();
        }
    }
    return res;
}

var myArray = ran2Darray(5, 100);
var offset = 2;

for (i = 0; i < myArray.length; i++) {
    aRow = myArray[i];
    st = Date.now();
    aRow.map(function addNumber(offset) {myArray[i] + offset*i; })
    end = Date.now();
    document.write(end - st);
    document.write("</br>");
    myArray[i] = aRow;
}

I want to avoid any added libraries or frameworks, unless of course, that is my only option. Can this code be made faster, or is there another direction I can go, like passing the calculation to another language? I'm just not familiar with how people deal with this sort of problem. forEach performs roughly the same, by the way.

2
  • 1
    Array.map as well as forEach calls a function for each element. Try replacing that with a for loop. Commented Mar 2, 2015 at 22:32
  • Right you are! Thanks, this is the kind of thing I don't yet really appreciate in JavaScript. In my usual language, R, these sorts of things are highly optimized and the mapped version is usually faster. I rewrote it to use 2 indices and for a 5 x 50000 matrix it took 7 ms. The answer from @Artyom took 47 ms (but I learned several things from that answer). Commented Mar 2, 2015 at 23:03

2 Answers 2

1

You don't have to rewrite array items several times. .map() returns a new array, so just assign it to the current index:

var myArray = ran2Darray(5, 100000);
var offset = 2;

var performOperation = function(value, idx) {
    return value += offset * idx;
}

for (i = 0; i < myArray.length; i++) {
    console.time(i);
    myArray[i] = myArray[i].map(performOperation)
    console.timeEnd(i);
}

It takes like ~20ms to process.

Fiddle demo (open console)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this was very helpful and fast, though slightly slower than just using two loops (see comment on original question). I learned a couple of helpful things from your example.
1

Ok, Just a little modification and a bug fix in what you have presented here.

function addNumber(offset) {myArray[i] + offset*i; }) is not good.

myArray[i] is the first dimention of a 2D array why to add something to it?

function ran2Darray (row, col) {

    var res = [];

    for (var i = 0 ; i < row; i++) {

        res[i] = [];

        for (var j = 0; j < col; j++) {
            res[i][j] = Math.random();
        }
    }
    return res;
}

var oneMillion = 1000000;
var myArray = ran2Darray(10, oneMillion);
var offset = 2;
var startTime, endTime;

for (i = 0; i < myArray.length; i++) {

    startTime = Date.now();
    myArray[i] = myArray[i].map(function (offset) {

        return (offset + i) * offset;
    });
    endTime = Date.now();

    document.write(endTime - startTime);
    document.write("</br>");
}

try it. It's really fast https://jsfiddle.net/itaymer/8ttvzyx7/

1 Comment

Thank you, more good stuff for me to study. Looks a little slower than @Artyom 's answer. Much appreciated, I knew I wasn't doing it quite right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.