Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Write a Perl program to find the inverse of a #4745

Merged
merged 6 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions program/program/find-the-inverse-of-a/FindTheInverseOfA.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
require 'matrix'

def matrix_inverse(matrix)
a = Matrix[*matrix]

# Check if the matrix is invertible
if a.det == 0
puts "The matrix is not invertible."
return
end

a_inv = a.inverse

# Print the inverse matrix with floating-point numbers
a_inv.to_a.each do |row|
row.each { |element| print "#{element.to_f} " }
puts
end
end

# Example input matrix (invertible)
input_matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Find and print the inverse
matrix_inverse(input_matrix)

67 changes: 67 additions & 0 deletions program/program/find-the-inverse-of-a/find_the_inverse_of_a.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use strict;
use warnings;

sub matrix_inverse {
my ($matrix) = @_;

my $size = scalar(@$matrix);

# Check if the matrix is square
die "Matrix must be square for inversion" if $size != scalar(@{$matrix->[0]});

# Augment the matrix with an identity matrix
my @augmented_matrix;
for my $i (0..$size-1) {
for my $j (0..$size-1) {
$augmented_matrix[$i][$j] = $matrix->[$i][$j];
$augmented_matrix[$i][$j+$size] = ($i == $j) ? 1 : 0;
}
}

# Perform Gauss-Jordan elimination
for my $i (0..$size-1) {
my $pivot = $augmented_matrix[$i][$i];

die "Matrix is singular, cannot find inverse" if $pivot == 0;

for my $j (0..2*$size-1) {
$augmented_matrix[$i][$j] /= $pivot;
}

for my $k (0..$size-1) {
next if $k == $i;
my $factor = $augmented_matrix[$k][$i];
for my $j (0..2*$size-1) {
$augmented_matrix[$k][$j] -= $factor * $augmented_matrix[$i][$j];
}
}
}

# Extract the inverse matrix from the augmented matrix
my @inverse_matrix;
for my $i (0..$size-1) {
for my $j ($size..2*$size-1) {
push @{$inverse_matrix[$i]}, $augmented_matrix[$i][$j];
}
}

return @inverse_matrix;
}

# Example usage
my @matrix = (
[4, 2, 7],
[1, 5, 3],
[8, 6, 9]
);

my @inverse_matrix = matrix_inverse(\@matrix);

# Print the inverse matrix
for my $i (0..$#inverse_matrix) {
for my $j (0..$#{$inverse_matrix[$i]}) {
printf "%.16f ", $inverse_matrix[$i][$j];
}
print "\n";
}