Skip to content

Commit 5819c99

Browse files
Create LinearTransformationAlgorithm.crystal
1 parent 7322649 commit 5819c99

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

LinearTransformationAlgorithm.crystal

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class LinearTransform
2+
# The matrix representing the linear transformation
3+
property matrix : Array(Array(Float64))
4+
5+
# Initializes a new LinearTransform instance with the given matrix
6+
def initialize(matrix : Array(Array(Float64)))
7+
@matrix = matrix
8+
end
9+
10+
# Applies the linear transformation to the given input vector and
11+
# returns the transformed vector
12+
def transform(vector : Array(Float64))
13+
# Validate the size of the input vector
14+
if vector.size != matrix.size
15+
raise "Invalid input vector size"
16+
end
17+
18+
# Create an empty output vector with the same size as the input vector
19+
output = Array(Float64).new(vector.size)
20+
21+
# Loop through the rows and columns of the matrix and apply the
22+
# linear transformation to the input vector
23+
matrix.each_with_index do |row, i|
24+
row.each_with_index do |element, j|
25+
output[i] += element * vector[j]
26+
end
27+
end
28+
29+
# Return the transformed vector
30+
output
31+
end
32+
end
33+
34+
# Create a new LinearTransform instance with the matrix
35+
# representing a 90-degree clockwise rotation
36+
transform = LinearTransform.new([[0, -1], [1, 0]])
37+
38+
# Apply the transformation to the input vector [1, 1]
39+
vector = transform.transform([1, 1])
40+
41+
# Print the transformed vector
42+
puts vector # Output: [-1, 1]

0 commit comments

Comments
 (0)