Skip to content

Instantly share code, notes, and snippets.

@ad-1
Last active April 13, 2023 20:56
Show Gist options
  • Select an option

  • Save ad-1/abb482de2f7b6bd974fbf7a7198d07a4 to your computer and use it in GitHub Desktop.

Select an option

Save ad-1/abb482de2f7b6bd974fbf7a7198d07a4 to your computer and use it in GitHub Desktop.
Fundamentals of Matrix Algebra | Part 2
# define array
A = np.array([[1, 0], [0, 1]])
# True if orthogonal
assert (A.T == np.linalg.inv(A)).all()
# area parallelogram
from matplotlib.patches import FancyArrowPatch
# create 2x2 array
A = np.array([[18, 6], [3, 15]])
# define vectors
v1 = A[:][0]
v2 = A[:][1]
# create figure and subplots
_, ax = plt.subplots()
# plot vectors as arrows
arrow = FancyArrowPatch((0, 0), (v1[0], v1[1]), mutation_scale=25)
ax.add_patch(arrow)
arrow = FancyArrowPatch((0, 0), (v2[0], v2[1]), mutation_scale=25)
ax.add_patch(arrow)
# plot other sides of parallelogram
ax.plot([v1[0], v1[0] + v2[0]], [v1[1], v1[1] + v2[1]])
ax.plot([v2[0], v1[0] + v2[0]], [v2[1], v1[1] + v2[1]])
# set labels and title
ax.set(xlabel='x', ylabel='y', title='2x2 Matrix Determinant')
# must update axis limits when changing vector components
plt.xlim(0, 25)
plt.ylim(0, 25)
# enable grid
ax.grid()
plt.show()
# permutations
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(A)
perumtation = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
# right multiplication - interchange columns 1 and 2
B = np.dot(A, perumtation)
print(B)
# left multiplication - interchange rows 1 and 2
C = np.dot(perumtation, A)
print(C)
# trace
# randomly initialise matrix
A = np.random.rand(560, 3000)
trace = 0
# iterate over smallest dimension to avoid index out of bound error
for i in range(min(A.shape[0], A.shape[1])):
# sum diagonal elements
trace += A[i][i]
# find trace using Numpy
trace_np = A.trace()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment