【发布时间】:2019-12-10 10:32:02
【问题描述】:
我需要在不使用库的情况下用 Perl 编写一个矩阵。 如何在我的代码中实现以下操作? - 转置矩阵 - 计算每一行和每一列的平均值,(我试图在下面的脚本中制作它) - 找到整个矩阵中的最小值, - 找到值总和最小的行的索引。
我将此代码用于矩阵运算,它可以工作,但我完全不明白如何执行这些运算。提前谢谢你
#!usr/bin/perl
use strict;
use warnings;
my(@MatrixA, @MatrixB, @Resultant) = ((), (), ());
# Asking for User Input for Matrix A
print"Let's begin with the matrix A dimensions\n";
print"\tPlease, enter how many rows should Matrix A have:";
chomp(my$rowA= <>); # CHOMP TO TAKE USER INPUT
print"\tPlease, enter how many columns should Matrix A have:";
chomp(my$columnA= <>);
# Asking for User Input for Matrix B
print"Then we have matrix B:\n";
print"\tPlease, enter how many rows should Matrix B have:";
chomp(my$rowB= <>);
print"\tPlease, enter how many columns should Matrix B have:";
chomp(my$columnB= <>);
# Asking User to input elements of matrices
if($rowA== $rowB and $columnA== $columnB) #checking the dimensions whether they match
{
print"Enter $rowA * $columnA elements in MatrixA:\n";
foreach my $m(0..$rowA- 1)
{
foreach my $n(0..$columnA- 1)
{
chomp($MatrixA[$m][$n] = <>); # reading the values
}
}
print"Enter $rowB * $columnB elements in MatrixB:\n";
foreach my$m(0..$rowB- 1)
{
foreach my $n(0..$columnB- 1)
{
chomp($MatrixB[$m][$n] = <>); # reading the values
}
}
# Performing Addition operation
foreach my $m(0..$rowB- 1)
{
foreach my $n(0..$columnB- 1)
{
$Resultant[$m][$n] = $MatrixA[$m][$n] +
$MatrixB[$m][$n];
}
}
# Printing Matrix A
print"MatrixA is :\n";
foreach my $m(0..$rowB- 1)
{
foreach my $n(0..$columnB- 1)
{
print"$MatrixA[$m][$n] ";
}
print"\n";
}
# Printing Matrix B
print"MatrixB is :\n";
foreach my$m(0..$rowB- 1)
{
foreach my$n(0..$columnB- 1)
{
print"$MatrixB[$m][$n] ";
}
print"\n";
}
# Printing the sum of Matrices
print"SUM of MatrixA and MatrixB is :\n";
foreach my $m(0..$rowB- 1)
{
foreach my $n(0..$columnB- 1)
{
print"$Resultant[$m][$n] ";
}
print"\n";
}
# Printing the average of Matrices
print"The average of Matrices (row) :\n";
foreach my $m(0..$rowB- 1)
{
my $sum_r += $m;
my $average_r = $sum_r/$rowB;
print "Average is $average_r\n";
print"\n";
}
print"The average of Matrices (column) :\n";
foreach my $n(0..$columnB- 1)
{
my $sum_c += $n;
my $average_c = $sum_c/$columnB;
print "Average is $average_c\n";
print"\n";
}
}
# Error if Matrices are of different order
else
{
print"Matrices order does not MATCH, Addition is not Possible";
}
【问题讨论】:
-
如果您对问题的数学方面有疑问,我们对此概不负责。请参考math.stackexchange.com。对于学习 Perl,我推荐Learning Perl, 6th Edition。
-
你需要弄清楚算法。拿纸和铅笔。写下几个小的示例矩阵。手动计算每列的平均值。注意重复的工作部分。用英语写下重复部分的描述,就好像你想向同事解释一样。现在告诉计算机,使用 Perl。 -- 对其他三个任务做同样的事情。