Find the transposed matrix

Let's find the transposed matrix in Perl. A transposed matrix is ​​a matrix with rows and columns swapped. The calculation of the transposed matrix is ​​required by the inverse mispropagation method.

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,
};;

Transposing this matrix gives: The rows and columns are swapped.

#Transpose matrix

# Matrix representation of mathematics
# 2 rows and 3 columns matrix
# one two Three
# 4 5 6

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

Perl program for transposed matrix

Let's write a Perl program that finds the transposed matrix.

use strict;
use warnings;

sub mat_transpose {
  my ($mat) = @_;
  
  my $rows_length = $mat->{rows_length};
  my $columns_length = $mat->{columns_length};
  my $length = $rows_length * $columns_length;
  
  my $mat_trans = {};
  $mat_trans->{rows_length} = $columns_length;
  $mat_trans->{columns_length} = $rows_length;
  
  my $values ​​= $mat->{values};
  my $mat_trans_values ​​= [];
  
  for (my $row_index = 0; $row_index <$rows_length; $row_index ++) {
    for (my $column_index = 0; $column_index <$columns_length; $column_index ++) {
      $mat_trans_values->[$row_index * $columns_length + $column_index] = $values->[$column_index * $rows_length + $row_index];
    }
  }
  $mat_trans->{values} = $mat_trans_values;
  
  return $mat_trans;
}

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

my $mat_trans = mat_transpose ($mat);

#Row: 2, Column: 3, Values: 1 4 2 5 3 6
print "Row: $mat_trans->{rows_length}, Column: $mat_trans->{columns_length}, Values: @{$mat_trans->{values}}\n";

Associated Information