Tutorial

How to Delete Items From a Matrix in MATLAB

Use an empty array in the right part of the assignment to delete items from a matrix.

Preparation

Create a matrix using the following code:

A = [1:4; 5:8; 9:12];

Delete items

To delete items from a matrix, assign to the target an empty array. After the deletion, the items that followed the target are moved to occupy the vacated spot. You can use linear, subscript or logical indices to reference the target.

MATLAB allows only one non-colon index in deletion operations.
% Delete the third column
A(:,3) = [];
% Delete the second row
A(2,:) = [];
% Delete the first item
A(1) = [];
% Delete the items greater than 7
A(A>7) = [];

Note: If you use linear or logical indices, the result is a row vector. If an index is out of range, MATLAB generates an error.

Further reading

I recommend the following books to learn more on matrix manipulation in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a 2017 Textbook Excellence Award. The second chapter explains how to perform a wide list of operations on matrices, including deleting items.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Matrix manipulation is explained in the fourth chapter.

I also recommend the other tutorials in this series.

Exercise

Consult the help documentation of the rand function. Create a matrix of random numbers having five rows and four columns.

  1. Delete the fourth column
  2. Delete the last two rows
  3. Delete the items lower than 0.5
  4. Delete the second item, if it exists

Source code

I hope you have learned how to delete items from a matrix in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.