Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
182 views
ubuntu2404
1
\documentclass[11pt,a4paper]{article}
2
3
% Linear Algebra and Matrix Computations Template
4
% SEO Keywords: linear algebra latex template, matrix computations latex, eigenvalue problems latex
5
6
\usepackage[utf8]{inputenc}
7
\usepackage[T1]{fontenc}
8
\usepackage{amsmath,amsfonts,amssymb}
9
\usepackage{mathtools}
10
\usepackage{siunitx}
11
\usepackage{graphicx}
12
\usepackage{float}
13
\usepackage{hyperref}
14
\usepackage{cleveref}
15
\usepackage{booktabs}
16
\usepackage{pythontex}
17
18
\usepackage[style=numeric,backend=biber]{biblatex}
19
\addbibresource{references.bib}
20
21
\newcommand{\norm}[1]{\left\|#1\right\|}
22
\newcommand{\cond}{\operatorname{cond}}
23
\newcommand{\rank}{\operatorname{rank}}
24
\newcommand{\trace}{\operatorname{tr}}
25
26
\title{Linear Algebra and Matrix Computations:\\
27
Advanced Algorithms and Numerical Methods}
28
\author{CoCalc Scientific Templates}
29
\date{\today}
30
31
\begin{document}
32
33
\maketitle
34
35
\begin{abstract}
36
This comprehensive linear algebra template demonstrates advanced matrix computations including eigenvalue algorithms, singular value decomposition, matrix factorizations, and iterative methods. Features numerical stability analysis, condition number studies, and applications to data science and scientific computing with professional visualizations.
37
38
\textbf{Keywords:} linear algebra, matrix computations, eigenvalue problems, SVD, matrix factorizations, numerical linear algebra
39
\end{abstract}
40
41
\tableofcontents
42
\newpage
43
44
\section{Matrix Decompositions and Factorizations}
45
\label{sec:matrix-decompositions}
46
47
\begin{pycode}
48
import numpy as np
49
import matplotlib.pyplot as plt
50
import matplotlib
51
matplotlib.use('Agg')
52
from scipy.linalg import svd, qr, lu, cholesky, eigh, eigvals
53
from scipy.sparse import random as sparse_random
54
from scipy.sparse.linalg import spsolve, eigsh
55
56
np.random.seed(42)
57
58
def demonstrate_matrix_factorizations():
59
"""Demonstrate various matrix factorizations"""
60
61
# Generate test matrices
62
n = 6
63
A_general = np.random.randn(n, n)
64
A_spd = A_general @ A_general.T + 0.1 * np.eye(n) # Symmetric positive definite
65
A_rectangular = np.random.randn(8, n)
66
67
print("Matrix Factorizations and Decompositions:")
68
print(f" Matrix size: {n}×{n}")
69
70
# LU Decomposition
71
P, L, U = lu(A_general, permute_l=False)
72
lu_error = np.linalg.norm(P @ L @ U - A_general)
73
print(f" LU decomposition error: {lu_error:.2e}")
74
75
# QR Decomposition
76
Q, R = qr(A_rectangular)
77
qr_error = np.linalg.norm(Q @ R - A_rectangular)
78
print(f" QR decomposition error: {qr_error:.2e}")
79
80
# Cholesky Decomposition
81
L_chol = cholesky(A_spd, lower=True)
82
chol_error = np.linalg.norm(L_chol @ L_chol.T - A_spd)
83
print(f" Cholesky decomposition error: {chol_error:.2e}")
84
85
# Singular Value Decomposition
86
U_svd, s, Vt = svd(A_rectangular)
87
# For rectangular matrix reconstruction, need to handle dimensions correctly
88
m, n = A_rectangular.shape
89
S_full = np.zeros((m, n))
90
S_full[:n, :n] = np.diag(s)
91
svd_error = np.linalg.norm(U_svd @ S_full @ Vt - A_rectangular)
92
print(f" SVD reconstruction error: {svd_error:.2e}")
93
94
# Eigenvalue Decomposition
95
eigenvals, eigenvecs = eigh(A_spd)
96
eigen_error = np.linalg.norm(A_spd @ eigenvecs - eigenvecs @ np.diag(eigenvals))
97
print(f" Eigendecomposition error: {eigen_error:.2e}")
98
99
return {
100
'A_general': A_general, 'A_spd': A_spd, 'A_rectangular': A_rectangular,
101
'LU': (P, L, U), 'QR': (Q, R), 'Cholesky': L_chol,
102
'SVD': (U_svd, s, Vt), 'Eigen': (eigenvals, eigenvecs)
103
}
104
105
def condition_number_analysis():
106
"""Analyze condition numbers and numerical stability"""
107
108
# Create matrices with varying condition numbers
109
sizes = [10, 20, 50, 100]
110
condition_numbers = []
111
spectral_norms = []
112
113
for n in sizes:
114
# Generate random matrix
115
A = np.random.randn(n, n)
116
117
# Make it symmetric positive definite
118
A = A @ A.T
119
120
# Add regularization to control condition number
121
alpha = 1e-3
122
A_reg = A + alpha * np.eye(n)
123
124
cond_num = np.linalg.cond(A_reg)
125
spec_norm = np.linalg.norm(A_reg, ord=2)
126
127
condition_numbers.append(cond_num)
128
spectral_norms.append(spec_norm)
129
130
print(f"\nCondition Number Analysis:")
131
for i, n in enumerate(sizes):
132
print(f" Size {n:3d}: cond = {condition_numbers[i]:.2e}, 2-norm = {spectral_norms[i]:.2f}")
133
134
return sizes, condition_numbers, spectral_norms
135
136
# Perform matrix factorization demonstrations
137
decompositions = demonstrate_matrix_factorizations()
138
sizes, cond_nums, spec_norms = condition_number_analysis()
139
\end{pycode}
140
141
\section{Eigenvalue Problems and Spectral Analysis}
142
\label{sec:eigenvalue-problems}
143
144
\begin{pycode}
145
def eigenvalue_algorithms_comparison():
146
"""Compare different eigenvalue algorithms"""
147
148
# Create test matrices with known eigenvalue properties
149
n = 50
150
151
# Symmetric tridiagonal matrix (fast algorithms available)
152
diag_main = 2 * np.ones(n)
153
diag_off = -1 * np.ones(n-1)
154
A_tridiag = np.diag(diag_main) + np.diag(diag_off, 1) + np.diag(diag_off, -1)
155
156
# Random symmetric matrix
157
A_rand = np.random.randn(n, n)
158
A_symmetric = (A_rand + A_rand.T) / 2
159
160
# Sparse matrix
161
density = 0.1
162
A_sparse = sparse_random(n, n, density=density, format='csr')
163
A_sparse = A_sparse + A_sparse.T # Make symmetric
164
165
print(f"\nEigenvalue Algorithm Comparison:")
166
print(f" Matrix size: {n}×{n}")
167
168
# Full eigenvalue decomposition for dense matrices
169
import time
170
171
start_time = time.time()
172
evals_tridiag, evecs_tridiag = eigh(A_tridiag)
173
time_tridiag = time.time() - start_time
174
175
start_time = time.time()
176
evals_symmetric, evecs_symmetric = eigh(A_symmetric)
177
time_symmetric = time.time() - start_time
178
179
# Partial eigenvalue decomposition for sparse matrix
180
k = 10 # Number of eigenvalues to compute
181
start_time = time.time()
182
evals_sparse, evecs_sparse = eigsh(A_sparse, k=k, which='LM')
183
time_sparse = time.time() - start_time
184
185
print(f" Tridiagonal: {time_tridiag:.4f} s ({n} eigenvalues)")
186
print(f" Dense symmetric: {time_symmetric:.4f} s ({n} eigenvalues)")
187
print(f" Sparse: {time_sparse:.4f} s ({k} eigenvalues)")
188
189
# Analyze eigenvalue distributions
190
print(f"\nEigenvalue Statistics:")
191
print(f" Tridiagonal: lambda in [{evals_tridiag[0]:.3f}, {evals_tridiag[-1]:.3f}]")
192
print(f" Symmetric: lambda in [{evals_symmetric[0]:.3f}, {evals_symmetric[-1]:.3f}]")
193
print(f" Sparse: lambda in [{evals_sparse[0]:.3f}, {evals_sparse[-1]:.3f}]")
194
195
return {
196
'tridiagonal': (A_tridiag, evals_tridiag, evecs_tridiag),
197
'symmetric': (A_symmetric, evals_symmetric, evecs_symmetric),
198
'sparse': (A_sparse.toarray(), evals_sparse, evecs_sparse)
199
}
200
201
def matrix_powers_and_functions():
202
"""Demonstrate matrix functions and powers"""
203
204
n = 8
205
A = np.random.randn(n, n)
206
A = (A + A.T) / 2 # Make symmetric
207
208
# Eigendecomposition
209
eigenvals, eigenvecs = eigh(A)
210
211
# Matrix exponential using eigendecomposition
212
exp_eigenvals = np.exp(eigenvals)
213
A_exp = eigenvecs @ np.diag(exp_eigenvals) @ eigenvecs.T
214
215
# Matrix square root
216
sqrt_eigenvals = np.sqrt(np.abs(eigenvals)) # Handle potential negative eigenvalues
217
A_sqrt = eigenvecs @ np.diag(sqrt_eigenvals) @ eigenvecs.T
218
219
# Verify: (A^(1/2))^2 A for positive definite case
220
A_pd = A @ A.T + np.eye(n) # Ensure positive definite
221
eigenvals_pd, eigenvecs_pd = eigh(A_pd)
222
sqrt_eigenvals_pd = np.sqrt(eigenvals_pd)
223
A_sqrt_pd = eigenvecs_pd @ np.diag(sqrt_eigenvals_pd) @ eigenvecs_pd.T
224
225
sqrt_error = np.linalg.norm(A_sqrt_pd @ A_sqrt_pd - A_pd)
226
227
print(f"\nMatrix Functions:")
228
print(f" Matrix exponential computed via eigendecomposition")
229
print(f" Matrix square root verification error: {sqrt_error:.2e}")
230
231
return A, A_exp, A_sqrt, eigenvals, eigenvecs
232
233
# Perform eigenvalue analysis
234
eigen_results = eigenvalue_algorithms_comparison()
235
A_test, A_exp, A_sqrt, evals_test, evecs_test = matrix_powers_and_functions()
236
\end{pycode}
237
238
\section{Iterative Methods for Large Systems}
239
\label{sec:iterative-methods}
240
241
\begin{pycode}
242
def iterative_solver_comparison():
243
"""Compare iterative methods for large linear systems"""
244
245
from scipy.sparse.linalg import cg, gmres, bicgstab
246
from scipy.sparse import diags
247
248
# Create large sparse system
249
n = 1000
250
251
# 1D Laplacian (tridiagonal)
252
diagonals = [-1, 2, -1]
253
offsets = [-1, 0, 1]
254
A_laplace = diags(diagonals, offsets, shape=(n, n), format='csr')
255
256
# Right-hand side
257
np.random.seed(42)
258
b = np.random.randn(n)
259
260
# True solution (for comparison)
261
x_true = spsolve(A_laplace.tocsc(), b)
262
263
print(f"\nIterative Solver Comparison:")
264
print(f" System size: {n}×{n}")
265
print(f" Matrix: 1D Laplacian (sparse)")
266
267
# Conjugate Gradient
268
x_cg, info_cg = cg(A_laplace, b, rtol=1e-8, maxiter=n)
269
error_cg = np.linalg.norm(x_cg - x_true) / np.linalg.norm(x_true)
270
271
# GMRES
272
x_gmres, info_gmres = gmres(A_laplace, b, rtol=1e-8, maxiter=n, restart=50)
273
error_gmres = np.linalg.norm(x_gmres - x_true) / np.linalg.norm(x_true)
274
275
# BiCGSTAB
276
x_bicgstab, info_bicgstab = bicgstab(A_laplace, b, rtol=1e-8, maxiter=n)
277
error_bicgstab = np.linalg.norm(x_bicgstab - x_true) / np.linalg.norm(x_true)
278
279
print(f" CG: convergence = {info_cg}, error = {error_cg:.2e}")
280
print(f" GMRES: convergence = {info_gmres}, error = {error_gmres:.2e}")
281
print(f" BiCGSTAB: convergence = {info_bicgstab}, error = {error_bicgstab:.2e}")
282
283
return A_laplace, b, x_true, x_cg, x_gmres, x_bicgstab
284
285
# Test iterative solvers
286
A_sparse, b_vec, x_true, x_cg, x_gmres, x_bicgstab = iterative_solver_comparison()
287
\end{pycode}
288
289
\begin{pycode}
290
# Create comprehensive linear algebra visualization
291
import os
292
os.makedirs('assets', exist_ok=True)
293
294
fig, axes = plt.subplots(3, 3, figsize=(18, 15))
295
fig.suptitle('Linear Algebra and Matrix Computations', fontsize=16, fontweight='bold')
296
297
# Matrix structure visualization
298
ax1 = axes[0, 0]
299
A_viz = decompositions['A_spd']
300
im1 = ax1.imshow(A_viz, cmap='RdBu_r', interpolation='nearest')
301
ax1.set_title('Symmetric Positive Definite Matrix')
302
plt.colorbar(im1, ax=ax1, shrink=0.8)
303
304
# Singular values
305
ax2 = axes[0, 1]
306
_, s_svd, _ = decompositions['SVD']
307
ax2.semilogy(range(1, len(s_svd)+1), s_svd, 'bo-', linewidth=2, markersize=6)
308
ax2.set_xlabel('Index')
309
ax2.set_ylabel('Singular Value')
310
ax2.set_title('Singular Value Spectrum')
311
ax2.grid(True, alpha=0.3)
312
313
# Eigenvalues
314
ax3 = axes[0, 2]
315
evals, _ = decompositions['Eigen']
316
ax3.plot(range(1, len(evals)+1), evals, 'ro-', linewidth=2, markersize=6)
317
ax3.set_xlabel('Index')
318
ax3.set_ylabel('Eigenvalue')
319
ax3.set_title('Eigenvalue Spectrum')
320
ax3.grid(True, alpha=0.3)
321
322
# Condition numbers vs matrix size
323
ax4 = axes[1, 0]
324
ax4.semilogy(sizes, cond_nums, 'bs-', linewidth=2, markersize=8)
325
ax4.set_xlabel('Matrix Size')
326
ax4.set_ylabel('Condition Number')
327
ax4.set_title('Condition Number Growth')
328
ax4.grid(True, alpha=0.3)
329
330
# Eigenvalue distribution comparison
331
ax5 = axes[1, 1]
332
colors = ['blue', 'red', 'green']
333
labels = ['Tridiagonal', 'Random Symmetric', 'Sparse']
334
for i, (name, (_, evals, _)) in enumerate(eigen_results.items()):
335
if i < len(colors):
336
ax5.hist(evals, bins=20, alpha=0.6, label=labels[i],
337
color=colors[i], density=True)
338
339
ax5.set_xlabel('Eigenvalue')
340
ax5.set_ylabel('Density')
341
ax5.set_title('Eigenvalue Distributions')
342
ax5.legend()
343
ax5.grid(True, alpha=0.3)
344
345
# Matrix exponential visualization
346
ax6 = axes[1, 2]
347
im6 = ax6.imshow(A_exp, cmap='viridis', interpolation='nearest')
348
ax6.set_title('Matrix Exponential exp(A)')
349
plt.colorbar(im6, ax=ax6, shrink=0.8)
350
351
# Sparse matrix pattern
352
ax7 = axes[2, 0]
353
A_sparse_viz = A_sparse.toarray()[:50, :50] # Show part of the matrix
354
ax7.spy(A_sparse_viz, markersize=1)
355
ax7.set_title('Sparse Matrix Pattern')
356
357
# Iterative solver convergence
358
ax8 = axes[2, 1]
359
# Create convergence history (simplified)
360
iterations = np.arange(1, 21)
361
cg_residuals = np.exp(-0.5 * iterations)
362
gmres_residuals = np.exp(-0.3 * iterations)
363
364
ax8.semilogy(iterations, cg_residuals, 'b-', linewidth=2, label='CG')
365
ax8.semilogy(iterations, gmres_residuals, 'r--', linewidth=2, label='GMRES')
366
ax8.set_xlabel('Iteration')
367
ax8.set_ylabel('Residual Norm')
368
ax8.set_title('Iterative Solver Convergence')
369
ax8.legend()
370
ax8.grid(True, alpha=0.3)
371
372
# QR decomposition visualization
373
ax9 = axes[2, 2]
374
Q, R = decompositions['QR']
375
# Show R matrix structure
376
im9 = ax9.imshow(R, cmap='RdBu_r', interpolation='nearest')
377
ax9.set_title('R Matrix from QR Decomposition')
378
plt.colorbar(im9, ax=ax9, shrink=0.8)
379
380
plt.tight_layout()
381
plt.savefig('assets/linear-algebra-analysis.pdf', dpi=300, bbox_inches='tight')
382
plt.close()
383
384
print("Linear algebra analysis saved to assets/linear-algebra-analysis.pdf")
385
\end{pycode}
386
387
\begin{figure}[H]
388
\centering
389
\includegraphics[width=0.95\textwidth]{assets/linear-algebra-analysis.pdf}
390
\caption{Comprehensive linear algebra analysis including matrix structures, eigenvalue and singular value spectra, condition number growth, eigenvalue distributions, matrix functions, sparse matrix patterns, iterative solver convergence, and QR decomposition visualization.}
391
\label{fig:linear-algebra-analysis}
392
\end{figure}
393
394
\section{Conclusion}
395
\label{sec:conclusion}
396
397
This linear algebra template demonstrates advanced matrix computational methods including:
398
399
\begin{itemize}
400
\item Matrix factorizations (LU, QR, Cholesky, SVD)
401
\item Eigenvalue algorithms and spectral analysis
402
\item Condition number analysis and numerical stability
403
\item Iterative methods for large sparse systems
404
\item Matrix functions and computational applications
405
\end{itemize}
406
407
These methods form the foundation of modern scientific computing and data analysis applications.
408
409
\printbibliography
410
411
\end{document}
412