Matrix Indexing in MATLAB

MATLAB Tutorial

🔢 Matrix Indexing in MATLAB

Matrix indexing in MATLAB lets you access, modify, and extract elements from matrices efficiently.

MATLAB is developed by MathWorks.


🔹 What Is Matrix Indexing?

Indexing means selecting elements using their row and column positions.

📌 MATLAB uses 1-based indexing (the first element is index 1, not 0).


1️⃣ Basic Matrix Indexing (Row, Column)

🔸 Syntax

A(row, column)

🔸 Example


 

Output

60

👉 Element at row 2, column 3.


2️⃣ Accessing Entire Rows or Columns

🔸 Entire Row

A(2,:)

Output

40 50 60

🔸 Entire Column

A(:,1)

Output

10
40
70

📌 Colon : means all rows or all columns.


3️⃣ Accessing Multiple Rows & Columns

Output

20 30
50 60

👉 Extracts rows 1 to 2 and columns 2 to 3.


4️⃣ Linear Indexing

MATLAB stores matrices column-wise in memory.

Output

50

📌 Linear indexing counts down columns first.

Order of elements:

10, 40, 70, 20, 50, 80, 30, 60, 90

5️⃣ Indexing Using End Keyword

A(end, end)

Output

90

📌 end refers to the last row or column.


6️⃣ Logical Indexing

Select elements based on a condition.

A(A > 50)

Output

60 70 80 90

📌 Very powerful for filtering data.


7️⃣ Modifying Matrix Elements Using Indexing

Output

100 20 30
40 50 60
70 80 90

8️⃣ Deleting Rows or Columns

🔸 Delete a Row

A(2,:) = [];

🔸 Delete a Column

A(:,3) = [];

⚠️ Important Notes

  • Indexing starts from 1

  • : selects all elements in a dimension

  • Linear indexing is column-major

  • Logical indexing is faster and cleaner than loops


🎯 Interview Questions: Matrix Indexing in MATLAB

🔹 Q1. What is matrix indexing?

Answer: Accessing elements of a matrix using row and column indices.


🔹 Q2. What does A(:, :) mean?

Answer: Selects all rows and all columns (entire matrix).


🔹 Q3. What is linear indexing?

Answer: Accessing elements using a single index in column-wise order.


🔹 Q4. How do you access the last element of a matrix?

Answer: A(end, end)


🔹 Q5. What is logical indexing?

Answer: Selecting elements using logical conditions (e.g., A > 10).


🔹 Q6. How do you extract the 2nd row?

Answer: A(2,:)


🔹 Q7. How do you delete a column?

Answer: A(:,column_number) = []


Summary

  • MATLAB uses 1-based indexing

  • Supports row, column, linear, and logical indexing

  • Colon : and end simplify selection

  • Essential for matrix manipulation and data analysis

You may also like...