Matrix diagonal addition in PHP

Matrix addition is always a good pick for programming practice. Matrix is nothing but multi-dimensional array in terms of programming. Today, I will explain how people doing Layman code and how to optimize it.

$matrix = [ [1,2,3], [4,5,6], [7,8,9] ];

So the the forward diagonal elements are 1, 5, 9 and reverse diagonal elements are 3, 5, 7. Sum of both diagonal is 15.

Get sum of diagonal numbers of matrix:

<?php

$matrix = [ [1,2,3], [4,5,6], [7,8,9] ];

$sum = 0;

for($i=0; $i<count($matrix); $i++)
{
  for($j=0; $j<count($matrix[$i]); $j++)
  {
    if($i == $j){
      $sum = $sum + $matrix[$i][$j];
    }
  }
}
echo "Sum of Diagonal Elements = ".$sum;

// OUTPUT : Sum of Diagonal Elements = 15

Explanation: In above code, there are two for loops which are taking count of array element and then check for index which is same. As we need same index of the matrix, we can optimize it by avoiding inner loop and if condition. Take a look at following code.

<?php

$matrix = [ [1,2,3], [4,5,6], [7,8,9] ];

$sum = 0;

for($i=0; $i<count($matrix); $i++)
{
  $sum = $sum + $matrix[$i][$i];
}
echo "Sum of Diagonal Elements = ".$sum;

// OUTPUT : Sum of Diagonal Elements = 15

Get sum of reverse diagonal numbers of matrix:

<?php

$matrix = [ [1,2,3], [4,5,6], [7,8,9] ];

$sum = 0;

for($i=0; $i<count($matrix); $i++)
{
  for($j=0; $j<count($matrix); $j++)
  {
    if (($i + $j) == (count($matrix) - 1))
    {
      $sum = $sum + $matrix[$i][$j];
    }
  }
}
echo "Sum of Diagonal Elements = ".$sum;

// OUTPUT : Sum of Diagonal Elements = 15

Explanation: In above code, there are two for loops which are taking count of array element and then check for sum of index and count. When the condition meets, then we add the number which is present at that indexes. We can optimize it by avoiding inner loop and if condition. Take a look at following code.

<?php

$matrix = [ [1,2,3], [4,5,6], [7,8,9] ];

$sum = 0;
$count = count($matrix);

for($i=0, $j= ($count - 1); $i<$count; $i++, $j--)
{
  $sum = $sum + $matrix[$i][$j];
}
echo "Sum of Diagonal Elements = ".$sum;

// OUTPUT : Sum of Diagonal Elements = 15

Get sum of both diagonal numbers of matrix:

<?php

$matrix = [ [1,2,3], [4,5,6], [7,8,9] ];

$forward = 0;
$reverse = 0;

$count = count($matrix);

for($i=0, $j= ($count - 1); $i<$count; $i++, $j--)
{
  $forward = $forward + $matrix[$i][$i];
  $reverse = $reverse + $matrix[$i][$j];
}
echo "Sum of Forward Diagonal Elements = ".$forward;
echo "<br>";
echo "Sum of Reverse Diagonal Elements = ".$reverse;

// OUTPUT:
// Sum of Forward Diagonal Elements = 15
// Sum of Reverse Diagonal Elements = 15

Explanation: In above code, we integrate both sum in single loop. By using some techniques like above, we can optimize our code and we will get maximum output in minimum code.

Optimized and efficient code is always good.