Tutorial

How to Delete Items From a Cell Array in MATLAB

A cell array is a data type that uses indexed containers called “cells” to store data of varying types and sizes.

Preparation

Create a cell array using the following code:

A = {'Peter Pan', 'M', 11; 'Wendy Darling', 'F', 12; 'Captain Hook', 'M', 45};

Delete items

To delete items from a cell array, use cell indexing and assign to the target an empty array. After the deletion, the cells that followed the target are moved to occupy the vacated spot.

MATLAB allows only one non-colon index in deletion operations.
% Delete the third column
A(:,3) = [];
% Delete the third row
A(3,:) = [];
% Delete the cell 'Wendy Darling'
A(2) = [];

Note: You can use linear, subscript or logical indices to reference the target cells. If you use linear or logical indices, the result is a row vector.

Further reading

I recommend the following books to learn more on cell arrays 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. Cell arrays, and other data types, are explained clearly in the eighth chapter.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 11 explains excellently cell arrays, structure arrays, and character arrays, among other data types.

I also recommend the other tutorials in this series.

Exercise

Create a cell array using the following code:

mbrs = {'MBR1', 0, 0, 10, 5; 'MBR2', 10, 5, 7, 8; 'MBR3', 7, 9, 3, 6};
  1. Delete the last two columns
  2. Delete the second row
  3. Delete the cell ‘MBR3’

Source code

I hope you have learned how to delete items from cell arrays 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.