0
0
MATLABdata~5 mins

Matrix indexing (row, col) in MATLAB

Choose your learning style9 modes available
Introduction

Matrix indexing lets you pick or change specific parts of a matrix by using row and column numbers. It helps you work with data easily.

You want to get the value in a specific row and column of a matrix.
You need to change a value inside a matrix at a certain position.
You want to extract a smaller part (submatrix) from a bigger matrix.
You want to loop through rows and columns to process matrix data.
You want to check or compare values at certain positions in a matrix.
Syntax
MATLAB
matrix(row, column)

Row and column numbers start at 1 in MATLAB, not 0.

You can use ':' to select all rows or all columns.

Examples
Gets the value at row 2, column 3 of matrix A.
MATLAB
A(2,3)
Selects all columns in the first row of matrix A.
MATLAB
A(1, :)
Selects all rows in the second column of matrix A.
MATLAB
A(:, 2)
Extracts a submatrix from rows 2 to 4 and columns 1 to 3.
MATLAB
A(2:4, 1:3)
Sample Program

This program shows how to get a value, change a value, and extract a submatrix using matrix indexing.

MATLAB
A = [10, 20, 30; 40, 50, 60; 70, 80, 90];

% Get value at row 2, column 3
val = A(2, 3);
fprintf('Value at row 2, column 3: %d\n', val);

% Change value at row 1, column 1
A(1, 1) = 99;
fprintf('New matrix after change:\n');
disp(A);

% Extract submatrix rows 1-2, columns 2-3
sub = A(1:2, 2:3);
fprintf('Submatrix (rows 1-2, cols 2-3):\n');
disp(sub);
OutputSuccess
Important Notes

Remember MATLAB indexes start at 1, not 0 like some other languages.

Using ':' means you select all rows or all columns in that dimension.

You can assign new values to parts of the matrix using the same indexing.

Summary

Matrix indexing uses (row, column) to access or change elements.

Use ':' to select entire rows or columns easily.

It helps to work with parts of matrices like single elements or submatrices.