Ruby/Number/matrix

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

matrix in action

require "matrix"
# Represent the point (1,1) as the vector [1,1]
unit = Vector[1,1]
identity = Matrix.identity(2)  # 2x2 matrix
identity*unit == unit          # true: no transformation



This matrix rotates counterclockwise around the origin

require "matrix"
unit = 2
theta = Math::PI/2     # 90 degrees
rotate = Matrix[[Math.cos(theta), -Math.sin(theta)],
                [Math.sin(theta),  Math.cos(theta)]]
rotate*unit            # [-1.0, 1.0]: 90 degree rotation



This matrix scales a point by sx,sy

require "matrix"
unit = 2
sx,sy = 2.0, 3.0;
scale = Matrix[[sx,0], [0, sy]]
scale*unit             # => [2.0, 3.0]: scaled point



Two transformations in one

require "matrix"
sx,sy = 2.0, 3.0;
unit = 2
scale = Matrix[[sx,0], [0, sy]]
scale*unit             # => [2.0, 3.0]: scaled point
theta = Math::PI/2     # 90 degrees
rotate = Matrix[[Math.cos(theta), -Math.sin(theta)],
                [Math.sin(theta),  Math.cos(theta)]]
rotate*unit            # [-1.0, 1.0]: 90 degree rotation
 
scale * (rotate*unit)  # [-2.0, 3.0]