CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
program to compute the transpose of a 3X3 matrix

 



sgupta
New User

May 29, 2015, 3:00 AM

Post #1 of 4 (1779 views)
program to compute the transpose of a 3X3 matrix Can't Post

i need a program to compute the transpose of a 3X3 matrix. A
matrix and its transpose are shown below.

matrix
A1 A2 A3
B1 B2 B3
C1 C2 C3

Transpose
A1 B1 C1
A2 B2 C2
A3 B3 C3


Laurent_R
Veteran / Moderator

May 29, 2015, 1:19 PM

Post #2 of 4 (1763 views)
Re: [sgupta] program to compute the transpose of a 3X3 matrix [In reply to] Can't Post

What have you tried?


Laurent_R
Veteran / Moderator

May 29, 2015, 1:48 PM

Post #3 of 4 (1760 views)
Re: [sgupta] program to compute the transpose of a 3X3 matrix [In reply to] Can't Post

All right, there are some more clever ways to do it in Perl, but the following implements a very simple algorithm following the basic definition of matrix transposition:

Code
use strict; 
use warnings;
use Data::Dumper;

my @matrix = (
[ qw /A1 A2 A3/],
[ qw /B1 B2 B3/],
[ qw /C1 C2 C3/] );

print "Original matrix: \n", Dumper \@matrix;

my @transposed;
for my $i (0..2) {
for my $j (0..2) {
$transposed[$i][$j] = $matrix[$j][$i];
}
}
print "Transposed matrix: \n", Dumper \@transposed;


This is the output:

Code
$ perl transpose.pl 
Original matrix:
$VAR1 = [
[
'A1',
'A2',
'A3'
],
[
'B1',
'B2',
'B3'
],
[
'C1',
'C2',
'C3'
]
];
Transposed matrix:
$VAR1 = [
[
'A1',
'B1',
'C1'
],
[
'A2',
'B2',
'C2'
],
[
'A3',
'B3',
'C3'
]
];



BillKSmith
Veteran

May 29, 2015, 1:51 PM

Post #4 of 4 (1758 views)
Re: [sgupta] program to compute the transpose of a 3X3 matrix [In reply to] Can't Post

There are many possible answers to this question. The choice among them depends on the application.

For production work, I would refer you to CPAN. For such a small matrix in a "throw away" program, the transpose can be computed "in place" by swapping only three pairs of elements.

Code
use strict; 
use warnings;
my @m = (
[qw( A1 A2 A3)],
[qw( B1 B2 B3)],
[qw( C1 C2 C3)],
);
foreach my $v (@m) {
print "@$v\n";
}
print "\n\n";

($m[0][1], $m[1][0]) = ($m[1][0], $m[0][1]);
($m[0][2], $m[2][0]) = ($m[2][0], $m[0][2]);
($m[1][2], $m[2][1]) = ($m[2][1], $m[1][2]);

foreach my $v (@m) {
print "@$v\n";
}


OUTPUT:

Code
A1 A2 A3 
B1 B2 B3
C1 C2 C3


A1 B1 C1
A2 B2 C2
A3 B3 C3

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives