Indices in MATLAB
Indices are used to access, modify, and manipulate specific elements of matrices and arrays in MATLAB. MATLAB indices are one-based, meaning the first element has an index of 1 (not 0, as in some other programming languages).
Accessing Elements Using Indices
Individual elements of a matrix can be accessed using their row and column indices:
% Accessing matrix elements
A = [10 20 30; 40 50 60; 70 80 90];
disp(A)
val = A(2,3); % Access element in 2nd row, 3rd column
disp(val);
Output of disp(A):
10 20 30 40 50 60 70 80 90
Output of disp(val), 2nd row, 3rd column of A:
60
Indexing Rows and Columns
You can access entire rows or columns using a colon (:
):
% Accessing rows and columns
A = [10 20 30; 40 50 60; 70 80 90];
row2 = A(2, :); % Access the entire 2nd row
col3 = A(:, 3); % Access the entire 3rd column
disp(row2);
disp(col3);
Output for row2
:
40 50 60
Output for col3
:
30 60 90
Logical Indexing
Logical conditions can be used to index elements based on their values:
% Logical indexing
A = [10 20 30; 40 50 60; 70 80 90];
idx = A > 50; % Find elements greater than 50
disp(idx);
result = A(idx); % Get elements greater than 50
disp(result);
Output for idx
(logical array):
0 0 0 0 0 1 1 1 1
Output for result
:
60 70 80 90
Using the end
Keyword
The end
keyword is used to refer to the last element in a row, column, or array dimension:
% Using end keyword
A = [10 20 30; 40 50 60; 70 80 90];
lastRow = A(end, :); % Access the last row
lastElement = A(end, end); % Access the last element of the matrix
disp(lastRow);
disp(lastElement);
Output for lastRow
:
70 80 90
Output for lastElement
:
90
Setting Elements to Zero Based on a Condition
Use logical indexing to find elements greater than a specified value and set them to zero:
% Setting elements to zero based on a condition
A = [10 20 30; 40 50 60; 70 80 90];
disp('Original Matrix:');
disp(A);
A(A > 50) = 0; % Set all elements greater than 50 to zero
disp('Updated Matrix:');
disp(A);
Output for the original matrix:
10 20 30 40 50 60 70 80 90
Output for the updated matrix:
10 20 30 40 50 0 0 0 0
Useful MATLAB Functions for Indices
find(condition)
returns the indices of array elements that satisfy the condition.sub2ind(size, row, col)
converts row and column subscripts to linear indices.ind2sub(size, index)
converts a linear index to row and column subscripts.ismember(A, B)
returns an array indicating if elements of A are in B.Practice Questions
Test Yourself
1. Create a 4×4 matrix and extract the 3rd column using indices.
2. Use logical indexing to find all elements in a matrix greater than a specified value.
3. Write a script to extract the diagonal elements of a 5×5 matrix using indices.