打印上三角或下三角矩阵(9x9) - perl, R
欲打印矩阵位置示意图
1 #!/usr/bin/perl -w 2 use strict; 3 4 ## bottom left 5 for my $row (1..9) 6 { 7 for my $col(1..9) 8 { 9 if($col <= $row) 10 { 11 print $row * $col, "\t"; 12 } 13 else 14 { 15 print " \t"; 16 } 17 } 18 print "\n"; 19 } 20 print "-" x 100 , "\n"; 21 22 ## top left 23 for my $row (reverse(1..9)) 24 { 25 for my $col(1..9) 26 { 27 if($col <= $row) 28 { 29 print $row * $col, "\t"; 30 } 31 else 32 { 33 print " \t"; 34 } 35 } 36 print "\n"; 37 }
输出:
1 ## bottom right 2 for my $row (reverse(1..9)) 3 { 4 for my $col(1..9) 5 { 6 #print $row * $col, "\t"; 7 if($col >= $row) 8 { 9 print $row * $col, "\t"; 10 } 11 else 12 { 13 print " \t"; 14 } 15 } 16 print "\n"; 17 } 18 print "-" x 100 , "\n"; 19 20 ## top right 21 for my $row (1..9) 22 { 23 for my $col(1..9) 24 { 25 if($col >= $row) 26 { 27 print $row * $col, "\t"; 28 } 29 else 30 { 31 print " \t"; 32 } 33 } 34 print "\n"; 35 }
输出:
R 取上下三角矩阵(top right, bottom left)就简单的多,有函数可以直接用!
upper.tri()
lower.tri()