v9.1.1
Menu

Identity and Eye Matrices

easyFREEI/ONumPy Array CreationNumpy

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

Input
n = 3
Output
{'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]}
Reasoning
  • Input: n = 3 is the side length of a square matrix, so the result has 3 rows and 3 columns.
  • Math: the identity matrix I3I_3 has entries Iij=1I_{ij} = 1 when i=ji = j and Iij=0I_{ij} = 0 otherwise. Row 1 is (1,0,0)(1, 0, 0), row 2 is (0,1,0)(0, 1, 0), row 3 is (0,0,1)(0, 0, 1): the ones run down the main diagonal.
  • Trace: the trace is the sum of the diagonal entries, tr⁡(I3)=I11+I22+I33=1+1+1=3\operatorname{tr}(I_3) = I_{11} + I_{22} + I_{33} = 1 + 1 + 1 = 3. For any size the trace equals nn.
  • Output: identity holds the three rows as nested lists, trace is 3.0, and shape is [3, 3] (rows, then columns).
  • Notice the entries and the trace are written as floats (1.0, 3.0), while the shape values are plain integers, since they count rows and columns rather than store matrix values.
  • Why it matters: IA=AI A = A for any 3×33 \times 3 matrix AA, which is why II is the identity element of matrix multiplication.

Constraints

  • Use np.eye() or np.identity()
  • n will be a positive integer

More from Numpy

solution.py

Test results

Sign in to run your code against the test cases.