Home > Software engineering >  How to add 2X2 matrix in Flutter/dart
How to add 2X2 matrix in Flutter/dart

Time:08-11

in my dart code, I have a 2X2 matrix, like this

    List<List<int>> a = 
  [
    [10,   2],
    [2,  2],
  ];
  
      List<List<int>> b = 
  [
    [1,   2],
    [2,  2],
  ];

so, I want to add these two matrices without using any predefined function.

the result that I want, like this

List<List<int>> c = 
      [
        [11,   4],
        [4,  4],
      ];

CodePudding user response:

this is the general answer to the sum 2D matrix

List<List<int>> c=[];
int minSize=a.length>b.length?b.length:a.length;

 for(int i=0;i<minSize;i  ){
  List<int> temp=[];
  int minListSize=a[i].length>b[i].length?b[i].length:a[i].length;

   for(int j=0;j<minListSize;j  ){
     temp.add(a[i][j] b[i][j]);
    }
  c.add(temp);
}

CodePudding user response:

Well, if you know beforehand they are both 2x2 matrices, then this straightforward way is a trivial solution, which I think even beats every other solution in terms of performance.

List<List<int>> c =
[
  [a[0][0]   b [0][0], a[0][1]   b [0][1]],
  [a[1][0]   b [1][0], a[1][1]   b [1][1]]
];
  • Related