Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

6. Identity and diagonal matrices

easy
GeneralGeneral
senior

Identity and diagonal matrices show up everywhere in ML/AI pipelines, from feature scaling to simple linear layers. In this task, you’ll apply a diagonal linear transform to a vector using efficient NumPy operations.

Requirements

Implement the function

python

Rules:

  • Use the definition yi=diâ‹…xiy_i = d_i \cdot x_i where D=diag(d)D = \mathrm{diag}(d).
  • Do not construct the full n×nn \times n diagonal matrix (keep it efficient).
  • Return the result as a NumPy array.
  • Use only NumPy.
  • Keep the function self-contained (single function).

Example

python

Output:

python
Input Signature
ArgumentType
xnp.ndarray
diagnp.ndarray
Output Signature
Return NameType
valuenp.ndarray

Constraints

  • Do not build an n×n diagonal matrix.

  • Use only NumPy.

  • Return a NumPy array.

Hint 1

A diagonal matrix multiply y=Dxy = D x is equivalent to element-wise multiplication of the diagonal component vector and the input vector.

Hint 2

Use the * operator or np.multiply() in NumPy to perform element-wise multiplication.

Hint 3

Avoid constructing the full n×nn \times n diagonal matrix to save memory and computation time.

Roles
ML Engineer
AI Engineer
Companies
GeneralGeneral
Levels
senior
entry
Tags
diagonal-matrix
elementwise-multiplication
linear-algebra
numpy
35 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit