Find the sum of matrices

Let's find the sum of the matrices in Perl. Think of the matrix as a column-first matrix.

# Matrix representation of mathematics
# 3 rows and 2 columns matrix
# 14
# twenty five
# 3 6

#How to use data with column priority
my $mat = {
  values ​​=> [1, 2, 3, 4, 5, 6],
  rows_length => 3,
  columns_length => 2,
};;

The calculation to find the sum of the matrices is just the calculation to find the sum of each element of the matrix of the array.

Perl program for matrix sums

A Perl program that finds the sum of matrices.

use strict;
use warnings;

#Matrix sum
sub mat_add {
  my ($mat1, $mat2) = @_;
  
  my $mat_out = {};
  $mat_out->{rows_length} = $mat1->{rows_length};
  $mat_out->{columns_length} = $mat2->{columns_length};
  
  for (my $i = 0; $i <@{$mat1->{values}}; $i ++) {
    $mat_out->{values}->[$i] = $mat1->{values}->[$i] + $mat2->{values}->[$i];
  }
  
  return $mat_out;
}

my $mat1 = {
  values ​​=> [1, 2, 3, 4, 5, 6],
  rows_length => 3,
  columns_length => 2,
};;

my $mat2 = {
  values ​​=> [7, 8, 9, 10, 11, 12],
  rows_length => 3,
  columns_length => 2,
};;

#Matrix sum
my $mat_add = mat_add ($mat1, $mat2);

# [Matrix Add] Row: 3, Column: 2, Values: 8 10 12 14 16 18
print "[Matrix Add] Row: $mat_add->{rows_length}, Column: $mat_add->{columns_length}, Values: @{$mat_add->{values}}\n";

Associated Information