Special Matrices in MATLAB
🧩 Special Matrices in MATLAB (zeros, ones, eye, magic)
With Examples, Output & Interview Questions
MATLAB is developed by MathWorks.
🔹 What Are Special Matrices?
Special matrices are created using built-in functions to save time and avoid manual entry.
Commonly used:
-
zeros()→ All zeros -
ones()→ All ones -
eye()→ Identity matrix -
magic()→ Magic square
1️⃣ Zero Matrix – zeros()
Creates a matrix filled with 0.
🔸 Syntax
🔸 Example
Output
📌 Used for initializing arrays before computation.
2️⃣ Ones Matrix – ones()
Creates a matrix filled with 1.
🔸 Syntax
🔸 Example
Output
📌 Useful in testing formulas and normalization.
3️⃣ Identity Matrix – eye()
Creates a square matrix with:
-
1s on the main diagonal
-
0s elsewhere
🔸 Syntax
🔸 Example
Output
📌 Identity matrix acts like 1 in matrix multiplication:A * eye(n) = A
4️⃣ Magic Matrix – magic()
Creates a magic square where:
-
Sum of each row
-
Sum of each column
-
Sum of both diagonals
are equal.
🔸 Syntax
🔸 Example
Output
📌 Common sum = 15
Used mainly for learning, testing, and demonstrations.
🧪 Practical Example
Output
⚠️ Important Notes
-
zeros()andones()can create multi-dimensional arrays -
eye()always creates a square matrix -
magic()works for n ≥ 3 (exceptn = 2) -
Default data type is double
🎯 Interview Questions: Special Matrices in MATLAB
🔹 Q1. What is a zero matrix?
Answer: A matrix with all elements equal to zero.
🔹 Q2. Which function creates an identity matrix?
Answer: eye()
🔹 Q3. What is special about a magic matrix?
Answer: The sum of rows, columns, and diagonals is the same.
🔹 Q4. What is the use of ones() matrix?
Answer: Initialization, testing, and mathematical operations.
🔹 Q5. Does eye(3,4) work?
Answer: Yes, it creates a 3×4 identity-like matrix with ones on the diagonal.
🔹 Q6. What is the default data type of special matrices?
Answer: double
🔹 Q7. Can special matrices be multi-dimensional?
Answer: Yes (zeros(2,3,4)).
✅ Summary Table
| Function | Matrix Type | Use |
|---|---|---|
zeros() |
Zero matrix | Initialization |
ones() |
Ones matrix | Testing, scaling |
eye() |
Identity matrix | Linear algebra |
magic() |
Magic square | Learning & demos |
