0
0
MatlabHow-ToBeginner ยท 3 min read

How to Delete a Row from a Matrix in MATLAB

In MATLAB, you can delete a row from a matrix by assigning an empty array to that row using matrix(rowIndex, :) = []. This removes the specified row and shifts remaining rows up.
๐Ÿ“

Syntax

To delete a row from a matrix, use the syntax:

  • matrix(rowIndex, :) = [];

Here, rowIndex is the number of the row you want to delete.

The colon : means all columns in that row.

Assigning [] removes that entire row.

matlab
matrix(rowIndex, :) = [];
๐Ÿ’ป

Example

This example shows how to delete the 2nd row from a 3x3 matrix.

matlab
A = [1 2 3; 4 5 6; 7 8 9];
A(2, :) = [];
disp(A);
Output
1 2 3 7 8 9
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using parentheses incorrectly, like matrix(rowIndex) = [], which deletes an element if the matrix is a vector.
  • Trying to delete a row index that does not exist, causing an error.
  • Not using the colon : to specify all columns, which leads to unexpected results.
matlab
A = [1 2 3; 4 5 6; 7 8 9];
% Wrong: deletes element, not row
% A(2) = [];

% Correct: deletes 2nd row
A(2, :) = [];
๐Ÿ“Š

Quick Reference

Summary tips for deleting rows in MATLAB:

  • Use matrix(rowIndex, :) = []; to delete a row.
  • Ensure rowIndex is valid and within matrix size.
  • Use : to select all columns in the row.
  • Deleting multiple rows: matrix([row1 row2], :) = [];
โœ…

Key Takeaways

Delete a row by assigning an empty array to that row with all columns: matrix(rowIndex, :) = [].
Always include the colon to specify all columns when deleting a row.
Check that the row index exists to avoid errors.
You can delete multiple rows by specifying their indices in a vector.
Incorrect indexing can delete columns or elements instead of rows.