The question is of course simple, but I can not find info in Russian. How correctly in the simplest form to use matrices to convert a picture? For example, the rotation matrix, which for the plane has the form 2 × 2. Do you need to multiply each coordinate of an object by a cycle by each element of such a matrix, or how?

  • The vector of coordinates multiplied by the matrix, get a new vector. - Yaant
  • Well, how to multiply? The vector on the plane has two coordinates, do you have to multiply each by turns for each element of the matrix or how? - Alexey
  • Do you mean that the vector of coordinates must be represented by a 2 × 1 matrix and multiplied by a 2 × 2 matrix? Then it is clear. - Alexey
  • Yes exactly. :) - Yaant pm

1 answer 1

You can see how the turtle.Vec2D.rotate method is implemented. Its essence comes to multiplying the rotation matrix by the vector itself:

 x, y = x*c - y*s, y*c + x*s 

where с, s = cos(angle), sin(angle) . It's just literally matrix multiplication, for example, if you take the R matrix:

 ⎡R₀₀ R₀₁⎤ ⎢ ⎥ ⎣R₁₀ R₁₁⎦ 

and multiply by v vector:

 ⎡v₀₀⎤ ⎢ ⎥ ⎣v₁₀⎦ 

then the product R⋅v looks like a vector:

 ⎡R₀₀⋅v₀₀ + R₀₁⋅v₁₀⎤ ⎢ ⎥ ⎣R₁₀⋅v₀₀ + R₁₁⋅v₁₀⎦ 

Thus, to rotate the point x1 , y1 with respect to x0 , y0 center on the angle :

 from turtle import Vec2D def rotate2D(angle, x0, y0, x1, y1): """Rotate (x0, y0) -> (x1, y1) vector by *angle*.""" x, y = Vec2D(x1-x0, y1-y0).rotate(angle) return x + x0, y + y0 

Rotating triangle example:

rotating cyan triangle on white background

 import tkinter as tk def draw2Dpolygon(canvas, points, alpha, origin, *, color='gray'): points = [rotate2D(alpha, *[*origin, *p]) for p in points] canvas.create_polygon(points, outline=color, fill=color) def draw_circle(canvas, center, radius, *, color='black'): x, y, r = *center, radius canvas.create_oval(xr, yr, x+r, y+r, outline=color) def make_loop(): width, height = 400, 300 canvas = tk.Canvas(width=width, height=height, background='white') canvas.pack() angle = 0 A = width // 4, height // 4 B = 3 * width // 4, height // 4 C = width // 2, 3*height // 4 origin = width // 2, height // 2 def loop(): nonlocal angle angle += .025 canvas.delete('all') # clear canvas draw2Dpolygon(canvas, [A, B, C], angle, origin, color='#0DD') draw_circle(canvas, origin, radius=5, color='red') root.after(1, loop) return loop root = tk.Tk() root.after_idle(make_loop()) root.mainloop()