0
# Matrix Visualization
1
2
ManimGL provides specialized tools for visualizing matrices and linear algebra concepts through the matrix module. These components enable the creation of matrix displays, linear transformation demonstrations, and educational content around linear algebra with proper mathematical formatting and interactive capabilities.
3
4
## Capabilities
5
6
### Matrix Display and Formatting
7
8
Create visual representations of matrices with proper mathematical formatting, brackets, and element positioning for linear algebra demonstrations.
9
10
```python { .api }
11
class Matrix(VMobject):
12
def __init__(
13
self,
14
matrix: list[list] | np.ndarray,
15
v_buff: float = 0.8,
16
h_buff: float = 1.3,
17
bracket_h_buff: float = MED_SMALL_BUFF,
18
bracket_v_buff: float = MED_SMALL_BUFF,
19
add_background_rectangles_to_entries: bool = False,
20
include_background_rectangle: bool = False,
21
element_to_mobject: Callable = TexText,
22
element_to_mobject_config: dict = {},
23
element_alignment_corner: np.ndarray = ORIGIN,
24
**kwargs
25
):
26
"""
27
Create a visual matrix with proper mathematical formatting.
28
29
Parameters:
30
- matrix: 2D array or list of lists representing matrix elements
31
- v_buff: Vertical spacing between matrix rows
32
- h_buff: Horizontal spacing between matrix columns
33
- bracket_h_buff: Horizontal buffer for brackets
34
- bracket_v_buff: Vertical buffer for brackets
35
- add_background_rectangles_to_entries: Add backgrounds to elements
36
- include_background_rectangle: Add background to entire matrix
37
- element_to_mobject: Function to convert elements to mobjects
38
- element_to_mobject_config: Configuration for element conversion
39
- element_alignment_corner: Alignment point for elements
40
"""
41
42
def get_entries(self) -> VGroup:
43
"""Get all matrix entries as a VGroup."""
44
45
def get_brackets(self) -> VGroup:
46
"""Get the matrix brackets."""
47
48
def get_mob_matrix(self) -> list[list]:
49
"""Get matrix elements as nested list of mobjects."""
50
51
def set_column_colors(self, *colors):
52
"""Set colors for matrix columns."""
53
54
def add_background_to_entries(self):
55
"""Add background rectangles to matrix entries."""
56
```
57
58
### Vector Visualization
59
60
Display vectors as column matrices with specialized formatting for vector operations and transformations.
61
62
```python { .api }
63
class Vector(Matrix):
64
def __init__(self, vector: list | np.ndarray, **kwargs):
65
"""
66
Create a column vector display.
67
68
Parameters:
69
- vector: 1D array or list representing vector components
70
- kwargs: Additional Matrix parameters
71
"""
72
73
class IntegerMatrix(Matrix):
74
def __init__(self, matrix: list[list] | np.ndarray, **kwargs):
75
"""
76
Matrix specialized for integer entries with proper formatting.
77
78
Parameters:
79
- matrix: Matrix with integer entries
80
- kwargs: Additional Matrix parameters
81
"""
82
83
class DecimalMatrix(Matrix):
84
def __init__(
85
self,
86
matrix: list[list] | np.ndarray,
87
num_decimal_places: int = 2,
88
**kwargs
89
):
90
"""
91
Matrix specialized for decimal number display.
92
93
Parameters:
94
- matrix: Matrix with decimal entries
95
- num_decimal_places: Number of decimal places to display
96
- kwargs: Additional Matrix parameters
97
"""
98
```
99
100
### Matrix Operations Visualization
101
102
Tools for demonstrating matrix operations, transformations, and linear algebra concepts with visual feedback.
103
104
```python { .api }
105
def get_det_text(
106
matrix: Matrix,
107
determinant: float | None = None,
108
background_rect: bool = False,
109
initial_scale_factor: float = 2
110
) -> VMobject:
111
"""
112
Create determinant notation for a matrix.
113
114
Parameters:
115
- matrix: Matrix object to show determinant for
116
- determinant: Determinant value (calculated if None)
117
- background_rect: Add background rectangle
118
- initial_scale_factor: Initial scaling for animation
119
120
Returns:
121
Determinant notation as VMobject
122
"""
123
```
124
125
## Usage Examples
126
127
### Basic Matrix Display
128
129
```python
130
from manimlib import *
131
132
class BasicMatrixDemo(Scene):
133
def construct(self):
134
# Create a simple 2x2 matrix
135
matrix_data = [[1, 2], [3, 4]]
136
matrix = Matrix(matrix_data)
137
matrix.set_color(BLUE)
138
139
# Add title
140
title = Text("2×2 Matrix", font_size=36).to_edge(UP)
141
142
self.play(Write(title))
143
self.play(ShowCreation(matrix))
144
145
# Highlight individual elements
146
entries = matrix.get_entries()
147
148
for i, entry in enumerate(entries):
149
self.play(
150
entry.animate.set_color(YELLOW).scale(1.5),
151
run_time=0.5
152
)
153
self.play(
154
entry.animate.set_color(BLUE).scale(1/1.5),
155
run_time=0.5
156
)
157
158
self.wait()
159
```
160
161
### Linear Transformation Visualization
162
163
```python
164
class LinearTransformation(Scene):
165
def construct(self):
166
# Original vector
167
original_vector = Vector([3, 2])
168
original_vector.set_color(GREEN)
169
original_vector.to_edge(LEFT)
170
171
# Transformation matrix
172
transform_matrix = Matrix([[2, 1], [0, 1]])
173
transform_matrix.set_color(BLUE)
174
175
# Result vector (computed)
176
result_data = np.array([[2, 1], [0, 1]]) @ np.array([3, 2])
177
result_vector = Vector(result_data)
178
result_vector.set_color(RED)
179
result_vector.to_edge(RIGHT)
180
181
# Labels
182
original_label = Text("Original Vector", font_size=24)
183
original_label.next_to(original_vector, DOWN)
184
185
matrix_label = Text("Transformation Matrix", font_size=24)
186
matrix_label.next_to(transform_matrix, DOWN)
187
188
result_label = Text("Transformed Vector", font_size=24)
189
result_label.next_to(result_vector, DOWN)
190
191
# Show transformation sequence
192
self.play(
193
ShowCreation(original_vector),
194
Write(original_label)
195
)
196
self.wait()
197
198
self.play(
199
ShowCreation(transform_matrix),
200
Write(matrix_label)
201
)
202
self.wait()
203
204
# Animate the transformation
205
equals = Text("=", font_size=48)
206
multiplication = VGroup(
207
transform_matrix,
208
original_vector.copy(),
209
equals,
210
result_vector
211
).arrange(RIGHT, buff=0.5)
212
213
self.play(
214
Transform(
215
VGroup(transform_matrix, original_vector),
216
multiplication[:2]
217
),
218
Write(equals),
219
ShowCreation(result_vector),
220
Write(result_label)
221
)
222
self.wait()
223
```
224
225
### Matrix Operations
226
227
```python
228
class MatrixOperations(Scene):
229
def construct(self):
230
# Matrix addition demonstration
231
matrix_a = Matrix([[1, 2], [3, 4]])
232
matrix_a.set_color(BLUE)
233
234
matrix_b = Matrix([[5, 6], [7, 8]])
235
matrix_b.set_color(GREEN)
236
237
# Result matrix
238
result_data = [[6, 8], [10, 12]]
239
result_matrix = Matrix(result_data)
240
result_matrix.set_color(YELLOW)
241
242
# Arrange for addition
243
plus = Text("+", font_size=48)
244
equals = Text("=", font_size=48)
245
246
addition_group = VGroup(
247
matrix_a, plus, matrix_b, equals, result_matrix
248
).arrange(RIGHT, buff=0.5)
249
250
title = Text("Matrix Addition", font_size=36).to_edge(UP)
251
252
self.play(Write(title))
253
self.play(ShowCreation(matrix_a))
254
self.play(Write(plus))
255
self.play(ShowCreation(matrix_b))
256
self.wait()
257
258
# Show element-wise addition
259
entries_a = matrix_a.get_entries()
260
entries_b = matrix_b.get_entries()
261
262
for i in range(len(entries_a)):
263
self.play(
264
entries_a[i].animate.set_color(RED),
265
entries_b[i].animate.set_color(RED),
266
run_time=0.5
267
)
268
self.play(
269
entries_a[i].animate.set_color(BLUE),
270
entries_b[i].animate.set_color(GREEN),
271
run_time=0.3
272
)
273
274
self.play(Write(equals))
275
self.play(ShowCreation(result_matrix))
276
self.wait()
277
```
278
279
### Determinant Calculation
280
281
```python
282
class DeterminantDemo(Scene):
283
def construct(self):
284
# Create matrix for determinant
285
matrix_data = [[3, 1], [2, 4]]
286
matrix = Matrix(matrix_data)
287
matrix.set_color(BLUE)
288
289
# Calculate determinant
290
det_value = 3 * 4 - 1 * 2 # 10
291
292
# Show determinant notation
293
det_text = get_det_text(matrix, det_value)
294
det_text.next_to(matrix, RIGHT, buff=1)
295
296
title = Text("Determinant Calculation", font_size=36).to_edge(UP)
297
298
self.play(Write(title))
299
self.play(ShowCreation(matrix))
300
301
# Highlight diagonal elements
302
entries = matrix.get_entries()
303
304
# Main diagonal (3, 4)
305
main_diag = VGroup(entries[0], entries[3])
306
self.play(main_diag.animate.set_color(GREEN))
307
308
# Anti-diagonal (1, 2)
309
anti_diag = VGroup(entries[1], entries[2])
310
self.play(anti_diag.animate.set_color(RED))
311
312
# Show calculation
313
calculation = TexText(
314
f"det = (3)(4) - (1)(2) = 12 - 2 = {det_value}",
315
font_size=24
316
).to_edge(DOWN)
317
318
self.play(Write(calculation))
319
self.play(ShowCreation(det_text))
320
321
# Reset colors
322
self.play(entries.animate.set_color(BLUE))
323
self.wait()
324
```
325
326
### Eigenvalue Visualization
327
328
```python
329
class EigenvalueDemo(Scene):
330
def construct(self):
331
# Matrix with known eigenvalues
332
matrix_data = [[3, 1], [0, 2]]
333
matrix = Matrix(matrix_data)
334
matrix.set_color(BLUE)
335
336
# Eigenvectors
337
eigenvector1 = Vector([1, 0]) # For eigenvalue 3
338
eigenvector1.set_color(GREEN)
339
340
eigenvector2 = Vector([1, -1]) # For eigenvalue 2
341
eigenvector2.set_color(RED)
342
343
# Arrange display
344
matrix.to_edge(LEFT)
345
346
eigen_group = VGroup(eigenvector1, eigenvector2)
347
eigen_group.arrange(RIGHT, buff=1).to_edge(RIGHT)
348
349
# Labels
350
matrix_label = Text("Matrix A", font_size=24).next_to(matrix, DOWN)
351
eigen_label1 = Text("λ₁ = 3", font_size=20).next_to(eigenvector1, DOWN)
352
eigen_label2 = Text("λ₂ = 2", font_size=20).next_to(eigenvector2, DOWN)
353
354
title = Text("Eigenvalues and Eigenvectors", font_size=32).to_edge(UP)
355
356
self.play(Write(title))
357
self.play(ShowCreation(matrix), Write(matrix_label))
358
self.wait()
359
360
# Show first eigenvector
361
self.play(
362
ShowCreation(eigenvector1),
363
Write(eigen_label1)
364
)
365
366
# Demonstrate Av₁ = λ₁v₁
367
equation1 = TexText(
368
"Av₁ = 3v₁", font_size=24
369
).next_to(eigenvector1, UP)
370
371
self.play(Write(equation1))
372
self.wait()
373
374
# Show second eigenvector
375
self.play(
376
ShowCreation(eigenvector2),
377
Write(eigen_label2)
378
)
379
380
equation2 = TexText(
381
"Av₂ = 2v₂", font_size=24
382
).next_to(eigenvector2, UP)
383
384
self.play(Write(equation2))
385
self.wait()
386
```
387
388
### Interactive Matrix Editor
389
390
```python
391
from manimlib.mobject.interactive import Textbox
392
393
class InteractiveMatrix(Scene):
394
def setup(self):
395
# Create input textboxes for matrix elements
396
self.textboxes = []
397
positions = [
398
[-1, 0.5], [1, 0.5], # First row
399
[-1, -0.5], [1, -0.5] # Second row
400
]
401
402
for pos in positions:
403
textbox = Textbox(value="1", box_kwargs={"width": 0.8, "height": 0.6})
404
textbox.move_to(pos)
405
self.textboxes.append(textbox)
406
self.add(textbox)
407
408
def construct(self):
409
# Create responsive matrix display
410
def get_current_matrix():
411
try:
412
values = []
413
for i in range(0, 4, 2): # Process in pairs for 2x2
414
row = [
415
float(self.textboxes[i].get_value() or "1"),
416
float(self.textboxes[i+1].get_value() or "1")
417
]
418
values.append(row)
419
return Matrix(values)
420
except ValueError:
421
# Return identity matrix if invalid input
422
return Matrix([[1, 0], [0, 1]])
423
424
# Display matrix
425
display_matrix = get_current_matrix()
426
display_matrix.scale(1.5).to_edge(RIGHT)
427
428
def update_matrix(m):
429
new_matrix = get_current_matrix()
430
new_matrix.scale(1.5).to_edge(RIGHT)
431
m.become(new_matrix)
432
433
display_matrix.add_updater(update_matrix)
434
435
# Calculate and display determinant
436
det_display = Text("det = 1.0", font_size=24).to_edge(DOWN)
437
438
def update_determinant(d):
439
try:
440
a = float(self.textboxes[0].get_value() or "1")
441
b = float(self.textboxes[1].get_value() or "1")
442
c = float(self.textboxes[2].get_value() or "1")
443
d_val = float(self.textboxes[3].get_value() or "1")
444
445
det = a * d_val - b * c
446
new_text = Text(f"det = {det:.2f}", font_size=24)
447
new_text.to_edge(DOWN)
448
d.become(new_text)
449
except ValueError:
450
pass
451
452
det_display.add_updater(update_determinant)
453
454
# Labels
455
title = Text("Interactive Matrix Editor", font_size=32).to_edge(UP)
456
instruction = Text("Click boxes to edit values", font_size=20)
457
instruction.next_to(title, DOWN)
458
459
self.add(display_matrix, det_display, title, instruction)
460
self.wait(20) # Interactive exploration time
461
```
462
463
## Advanced Features
464
465
### Matrix Animation Utilities
466
467
```python
468
# Smooth matrix transformations
469
def animate_matrix_transform(scene, matrix, new_data, run_time=2):
470
"""Animate smooth transition between matrix states."""
471
# Custom animation logic for matrix entries
472
pass
473
474
# Row operations visualization
475
def show_row_operation(scene, matrix, operation_type, rows, scalar=1):
476
"""Visualize elementary row operations."""
477
# Highlight affected rows and show operation
478
pass
479
```
480
481
### Custom Matrix Styling
482
483
```python
484
# Color-coded matrices for different purposes
485
def create_identity_matrix(size, highlight_diagonal=True):
486
"""Create identity matrix with diagonal highlighting."""
487
pass
488
489
def create_augmented_matrix(left_matrix, right_vector):
490
"""Create augmented matrix for solving systems."""
491
pass
492
```
493
494
The matrix visualization module in ManimGL provides comprehensive tools for linear algebra education and demonstration, enabling clear visualization of matrix operations, transformations, and mathematical concepts with proper formatting and interactive capabilities.