0% found this document useful (0 votes)
31 views7 pages

Algebra For Ai Miscellaneous Code Snippets

This document contains 12 examples of generating and manipulating matrices in NumPy. The examples cover topics like generating random matrices, constructing matrices from vectors, finding matrix ranks and null spaces, and computing projections onto subspaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views7 pages

Algebra For Ai Miscellaneous Code Snippets

This document contains 12 examples of generating and manipulating matrices in NumPy. The examples cover topics like generating random matrices, constructing matrices from vectors, finding matrix ranks and null spaces, and computing projections onto subspaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

ML BOOTCAMP ASSIGNMENT

CB.SC.U4AIE23104
1.

import numpy as np

# Generate random numbers between 0 and 1


matrix = np.random.rand(4, 4)

# Normalize rows to make row sums equal to 1


matrix /= matrix.sum(axis=1, keepdims=True)

print(matrix)

2.

import numpy as np

# Define a diagonal matrix with two non-zero elements and one zero element
diagonal_elements = [1, 2, 0] # One eigenvalue is zero

# Create the diagonal matrix


matrix = np.diag(diagonal_elements)

print(matrix)

3.

import numpy as np

# Generate a random 3x3 matrix with non-zero elements


matrix = np.random.rand(3, 3)

# Ensure the matrix is symmetric


matrix = (matrix + matrix.T) / 2

# Ensure the matrix is positive definite


while not np.all(np.linalg.eigvals(matrix) > 0):
matrix = np.random.rand(3, 3)
matrix = (matrix + matrix.T) / 2

print(matrix)

4.

import numpy as np

# Define the vectors


v1 = np.array([2, 2, 1, 0])
v2 = np.array([3, 1, 0, 1])

CB.SC.U4AIE23104 1
ML BOOTCAMP ASSIGNMENT
CB.SC.U4AIE23104
# Stack the vectors vertically to form a matrix
matrix = np.vstack((v1, v2))

# Find the reduced row echelon form (RREF)


rref, pivot_cols = sympy.Matrix(matrix).T.rref()

# Add additional rows to the matrix based on the RREF


for i in range(matrix.shape[0]):
if i not in pivot_cols:
null_vector = np.zeros(matrix.shape[1])
null_vector[i] = 1
matrix = np.vstack((matrix, null_vector))

print(matrix)

5.

import numpy as np

def construct_matrix(t):
column_space_vector = np.array([1, 1, 1])
nullspace_vector = np.array([1, 1, 1, 1])

# Construct the matrix


column1 = column_space_vector
column2 = -t * nullspace_vector[:3] # Exclude the last element of nullspace_vector
matrix = np.column_stack((column1, column2))

return matrix

# Example usage
t_value = 2
result_matrix = construct_matrix(t_value)
print("Matrix:")
print(result_matrix)

6.

import numpy as np

def construct_matrix():
nullspace_vector = np.array([4, 3, 2, 1])
# Transpose the vector to make it a row vector
matrix = nullspace_vector.reshape(1, -1)

return matrix

CB.SC.U4AIE23104 2
ML BOOTCAMP ASSIGNMENT
CB.SC.U4AIE23104
# Example usage
result_matrix = construct_matrix()
print("Matrix:")
print(result_matrix)

7.

import numpy as np

# Define the vectors


v1 = np.array([1, 1, 5])
v2 = np.array([0, 3, 1])
nullspace_vector = np.array([1, 1, 2])

# Create a matrix with the given column vectors


A = np.column_stack((v1, v2))

# Find the third column to make the matrix singular


nullspace_column = np.linalg.lstsq(A, nullspace_vector, rcond=None)[0]

# Add the third column to the matrix


A = np.column_stack((A, nullspace_column))

print("The constructed matrix is:")


print(A)

8.

import numpy as np

# Define the vectors


v1 = np.array([1, 1])
v2 = np.array([1, -1])

# Compute the outer products


outer_product_v1_v1 = np.outer(v1, v1)
outer_product_v1_v2 = np.outer(v1, v2)
outer_product_v2_v1 = np.outer(v2, v1)
outer_product_v2_v2 = np.outer(v2, v2)

# Construct the basis matrices


basis_matrices = [outer_product_v1_v1, outer_product_v1_v2, outer_product_v2_v1,
outer_product_v2_v2]

print("The basis matrices are:")


for i, matrix in enumerate(basis_matrices):
print(f"Basis Matrix {i+1}:\n{matrix}\n")

CB.SC.U4AIE23104 3
ML BOOTCAMP ASSIGNMENT
CB.SC.U4AIE23104

9.

import numpy as np

# Define a matrix A with linearly independent columns


A = np.array([[1, 2],
[3, 4],
[5, 6]])

# Define a vector b that is not in the column space of A


b = np.array([7, 8, 9])

# Check if b is in the column space of A


# If rank(A) = rank(A|b), then b is in the column space of A
augmented_matrix = np.column_stack((A, b))
rank_A = np.linalg.matrix_rank(A)
rank_augmented = np.linalg.matrix_rank(augmented_matrix)

if rank_A == rank_augmented:
print("Error: b is in the column space of A. Choose a different b.")
else:
print("The system Ax = b, where b is not in the column space of A, is:")
print("A:")
print(A)
print("b:")
print(b)

10.

% Generate a rank-3 5x5 matrix X


X = randi(10, 5, 3) * randi(10, 3, 5);

% Compute the singular value decomposition of X


[U, S, V] = svd(X);
r = rank(X);

% Extract bases for column space, left null space, row space, and right null space
A = U(:, 1:r); % Basis for column space
B = U(:, r+1:end); % Basis for left null space
C = V(:, 1:r); % Basis for row space
D = V(:, r+1:end); % Basis for right null space

% Compute projection matrices


Prc = A * A'; % Projection matrix onto column space
Prln = B * B'; % Projection matrix onto left null space
Prr = C * C'; % Projection matrix onto row space
Prrn = D * D'; % Projection matrix onto right null space

CB.SC.U4AIE23104 4
ML BOOTCAMP ASSIGNMENT
CB.SC.U4AIE23104
% Display projection matrices
disp('Projection matrix for projecting into column space:');
disp(Prc);
disp('Projection matrix for projecting into left null space:');
disp(Prln);
disp('Projection matrix for projecting into row space:');
disp(Prr);
disp('Projection matrix for projecting into right null space:');
disp(Prrn);

11.

% Given matrix X
X = [39, 42, 39, 34, 29;
23, 24, 22, 23, 18;
28, 24, 20, 28, 18;
34, 32, 28, 36, 25;
10, 10, 9, 9, 7];

% Vector y
y = [1, 2, 3, 4, 5]';

% Compute the singular value decomposition of X


[U, S, V] = svd(X);
r = rank(X);

% Extract bases for column space, left null space, row space, and right null space
A = U(:, 1:r); % Basis for column space
B = U(:, r+1:end); % Basis for left null space
C = V(:, 1:r); % Basis for row space
D = V(:, r+1:end); % Basis for right null space

% Compute projection matrices


Prc = A * A'; % Projection matrix onto column space
Prln = B * B'; % Projection matrix onto left null space
Prr = C * C'; % Projection matrix onto row space
Prrn = D * D'; % Projection matrix onto right null space

% Project vector y onto each subspace


y_proj_column_space = Prc * y;
y_proj_left_null_space = Prln * y;
y_proj_row_space = Prr * y;
y_proj_right_null_space = Prrn * y;

% Display the projected vectors


disp('Projection onto column space:');
disp(y_proj_column_space);
disp('Projection onto left null space:');
disp(y_proj_left_null_space);

CB.SC.U4AIE23104 5
ML BOOTCAMP ASSIGNMENT
CB.SC.U4AIE23104
disp('Projection onto row space:');
disp(y_proj_row_space);
disp('Projection onto right null space:');
disp(y_proj_right_null_space);

12 .

% Given matrix X
X = [23, 41, 50, 50;
11, 21, 25, 24;
17, 25, 33, 37;
13, 23, 29, 30;
22, 36, 46, 49];

% Vectors y1 and y2
y1 = [1, 2, 3, 4, 5]';
y2 = [4, 3, 2, 1]';

% Compute the singular value decomposition of X


[U, S, V] = svd(X);
r = rank(X);

% Extract bases for column space, left null space, row space, and right null space
A = U(:, 1:r); % Basis for column space
B = U(:, r+1:end); % Basis for left null space
C = V(:, 1:r); % Basis for row space
D = V(:, r+1:end); % Basis for right null space

% Compute projection matrices


Prc = A * A'; % Projection matrix onto column space
Prln = B * B'; % Projection matrix onto left null space
Prr = C * C'; % Projection matrix onto row space
Prrn = D * D'; % Projection matrix onto right null space

% Project vectors y1 and y2 onto each subspace


y1_proj_column_space = Prc * y1;
y1_proj_left_null_space = Prln * y1;
y1_proj_row_space = Prr * y1;
y1_proj_right_null_space = Prrn * y1;

y2_proj_column_space = Prc * y2;


y2_proj_left_null_space = Prln * y2;
y2_proj_row_space = Prr * y2;
y2_proj_right_null_space = Prrn * y2;

% Display the projected vectors


disp('Projection of y1 onto column space:');
disp(y1_proj_column_space);
disp('Projection of y1 onto left null space:');

CB.SC.U4AIE23104 6
ML BOOTCAMP ASSIGNMENT
CB.SC.U4AIE23104
disp(y1_proj_left_null_space);
disp('Projection of y1 onto row space:');
disp(y1_proj_row_space);
disp('Projection of y1 onto right null space:');
disp(y1_proj_right_null_space);

disp('Projection of y2 onto column space:');


disp(y2_proj_column_space);
disp('Projection of y2 onto left null space:');
disp(y2_proj_left_null_space);
disp('Projection of y2 onto row space:');
disp(y2_proj_row_space);
disp('Projection of y2 onto right null space:');
disp(y2_proj_right_null_space);

CB.SC.U4AIE23104 7

You might also like