Special Matrices in MATLAB

MATLAB Tutorial

🧩 Special Matrices in MATLAB (zeros, ones, eye, magic)

With Examples, Output & Interview Questions

Special matrices are predefined matrices that MATLAB can generate instantly. They are widely used for initialization, testing algorithms, linear algebra, and teaching concepts.

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

Z = zeros(m, n)

🔸 Example


 

Output

0 0 0 0
0 0 0 0
0 0 0 0

📌 Used for initializing arrays before computation.


2️⃣ Ones Matrix – ones()

Creates a matrix filled with 1.

🔸 Syntax

O = ones(m, n)

🔸 Example


 

Output

1 1 1
1 1 1

📌 Useful in testing formulas and normalization.


3️⃣ Identity Matrix – eye()

Creates a square matrix with:

  • 1s on the main diagonal

  • 0s elsewhere

🔸 Syntax

I = eye(n)

🔸 Example


 

Output

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

📌 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

M = magic(n)

🔸 Example


 

Output

8 1 6
3 5 7
4 9 2

📌 Common sum = 15

Used mainly for learning, testing, and demonstrations.


🧪 Practical Example


 

Output

2 1 1
1 2 1
1 1 2

⚠️ Important Notes

  • zeros() and ones() can create multi-dimensional arrays

  • eye() always creates a square matrix

  • magic() works for n ≥ 3 (except n = 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

You may also like...