Identity and Eye Matrices
Problem Statement
Create identity matrices using NumPy.
Background
- np.eye(n): Creates n×n identity matrix (1s on diagonal, 0s elsewhere)
- np.identity(n): Same as eye, but only square matrices
- Identity matrix: I × A = A (identity element for matrix multiplication)
Your Task
Write a function create_identity(n) that returns a dictionary with:
- "identity": n×n identity matrix as nested list
- "trace": Sum of diagonal elements (should equal n)
- "shape": Shape as list [n, n]
Output Format
Return a dictionary with exactly these three keys.
Example:
n = 3
{'identity': [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], 'trace': 3.0, 'shape': [3, 3]}3x3 identity has 1s on diagonal, trace = 1+1+1 = 3
Constraints:
- Use np.eye() or np.identity()
- n will be a positive integer
1. Background Knowledge
Identity matrices are square matrices In∈Rn×n with 1s on the main diagonal and 0s elsewhere, serving as the multiplicative identity: In⋅A=A⋅In=A for any compatible matrix A.
NumPy provides efficient n-dimensional array operations central to scientific Python computing. Key functions:
- np.eye(n): Returns n×n identity matrix as a float NumPy array (dtype float64 by default).
- np.identity(n): Identical to np.eye(n) for square matrices.
Trace of a matrix is the sum of its diagonal elements: trace(In)=n, since only diagonal 1s contribute.
Shape is the tuple (n, n) converted to list [n, n] for the output.
Prerequisites: Basic NumPy array handling, list comprehension for nested lists, dictionary creation.
2. Algorithm Approach
Use np.eye(n) (or np.identity(n)) to generate the identity array directly—no manual construction needed, as it's O(n2) optimized in C.
- Generate identity array.
- Compute trace via np.trace() or np.diagonal().sum() (O(n)).
- Extract shape and convert to list.
- Convert array to nested list via array.tolist().
This leverages NumPy's vectorized operations for efficiency over pure Python loops.
3. Step-by-Step Strategy
import numpy as np
def create_identity(n):
# Step 1: Create n x n identity matrix (float64)
identity_array = np.eye(n)
# Step 2: Compute trace (sum of diagonal = n)
trace = np.trace(identity_array)
# Step 3: Get shape as list
shape = list(identity_array.shape)
# Step 4: Convert to nested list (preserves float values like 1.0)
identity_list = identity_array.tolist()
# Step 5: Return exact dictionary format
return {
"identity": identity_list,
"trace": trace,
"shape": shape
}
Verification:
result = create_identity(3)
print(result["identity"] == [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) # True
print(result["trace"] == 3.0) # True
print(result["shape"] == [3, 3]) # True
4. Common Pitfalls
- Data type mismatch: np.eye(n) returns floats (1.0, not 1); sample expects 1.0—.tolist() preserves this.
- Shape as tuple: array.shape is (n, n); must convert to [n, n] list.
- Manual loops: Avoid for loops to build matrix—use np.eye() for O(1) logical time.
- Integer input: n is positive integer, but output trace/shape use float/list—no casting needed.
- Import missing: Always import numpy as np.
- Non-square: Constraints guarantee square; no need for rectangular handling.
5. Time & Space Complexity
- Time: O(n2) dominant from np.eye() allocation and .tolist() traversal. Trace is O(n).
- Total: Θ(n2), optimized via C backend (vectorized, no Python loops).
- Space: O(n2) for array storage (dense matrix).
- Auxiliary: O(n2) for list conversion; dictionary overhead O(1).
- Identity matrix sparsity unused here (all zeros explicit).
This approach is optimal for constraints, scaling linearly in memory but constant-time logically via NumPy primitives.