0

i am totally new guy to javascript.I dont know how to add these two varible that are in multidimensional array in matrix way.Would you pls suggest any npm module with an example or the manual algorithm would be appreciated.

these are my two varibles

var MatrixA = [[13,5,0][11,6,4][10,7,2][9,8,0]]
var MatrixB =  [[103,50,0][11,60,40][10,70,20][90,80,0]]

enter image description here

Nane
  • 2,370
  • 6
  • 34
  • 74

4 Answers4

0

Not sure what exactly you want I am considering you want to add up all the numbers of these arrays If so ,consider the following code snippet

var MatrixA = [[13,5,0],[11,6,4],[10,7,2],[9,8,0]];
var MatrixB =  [[103,50,0],[11,60,40],[10,70,20],[90,80,0]];
var sum=0;
for(var i=0;i<3;i++){
    for(var j=0;j<3;j++){
        sum+=MatrixA[i][j]+MatrixB[i][j];
    }

}
console.log(sum);

Hope this helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
0

Check the following code snippet

var MatrixA = [[13, 5, 0], [11, 6, 4], [10, 7, 2], [9, 8, 0]];
var MatrixB = [[103, 50, 0], [11, 60, 40], [10, 70, 20], [90, 80, 0]];
var sumMatrix = [[], [], []];
var j = 0
  , k = 0;
l = 0;
for (var i = 0; i < 3; i++) {
  for(var j=0;j<3;j++){
    sumMatrix[i][j]=MatrixA[i][j]+MatrixB[i][j];
  }
}for (var i = 0; i < 3; i++) {
  for(var j=0;j<3;j++){
    console.log(sumMatrix[i][j]);
    }
  }

Hope this helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
0

First of all you need to declare another 2d array, lets say sum=[[],[],[]] to store the sum in. Then all you need to do is simply add the the two matrices.

C code:

for(i=0;i<r;++i)
    for(j=0;j<c;++j)
    {
        sum[i][j]=a[i][j]+b[i][j];
    }

I have actually never really coded much in Javascript but was able to put together a program on an online compiler I am getting NaN. But still works, and gives output.

var MatrixA = [[13,5,0],[11,6,4],[10,7,2],[9,8,0]];
var MatrixB =  [[103,50,0],[11,60,40],[10,70,20],[90,80,0]];
var sum=[[],[],[],[]];

for (var i=0 ; i<MatrixA.length; i++ )

    for (var j=0;j<MatrixB.length; j++)
        {
             sum[i][j]=MatrixA[i][j]+MatrixB[i][j];
        }

for (var i=0 ; i<MatrixA.length; i++ )

    for (var j=0;j<MatrixB.length; j++)
        {
             console.log(sum[i][j]);
        }
hamadkh
  • 359
  • 1
  • 16
0

May be you can do as follows;

var m1 = [[13,5,0],[11,6,4],[10,7,2],[9,8,0]],
    m2 = [[103,50,0],[11,60,40],[10,70,20],[90,80,0]],
result = m1.map((a,i) => a.map((n,j) => n + m2[i][j]));

console.log(JSON.stringify(result));
Redu
  • 25,060
  • 6
  • 56
  • 76