Tutorial

How to Delete Items From a Struct Array in MATLAB

A struct array is a data type that uses named containers called “fields” to store data of varying types and sizes.

Preparation

Create a struct array using the following code:

reds = {128, 255, 0, 51, 255};
greens = {128, 255, 0, 25, 150};
blues = {128, 255, 200, 30, 0};
points = struct('red', reds, 'green', greens, 'blue', blues);

Delete items

To delete items from a struct array, assign to the target an empty array. After the deletion, the structs that followed the target are moved to occupy the vacated spot.

MATLAB allows only one non-colon index in deletion operations.
% Delete the first struct
points(1) = [];
% Delete the first two structs
points(1:2) = [];
% Delete all structs
points(:) = [];

Note: In all examples I used linear indexing to reference the target structs, but you can use subscript indexing and logical indexing too. If you use linear or logical indices, the result is a row vector.

Further reading

I recommend the following books to learn more on struct 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. Struct arrays, 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 struct arrays, cell arrays, and character arrays, among other data types.

I also recommend the other tutorials in this series.

Exercise

A Minimum Bounding Box (MBR) is the minimum rectangle that encloses a group of pixels. MBRs are usually defined by the location of the upper-left corner, a width, and a height.

Create a struct array using the following code. Each struct represents a bounding box.

labels = {'MBR1', 'MBR2', 'MBR3'}; 
xOrigins = {0, 10, 7};
yOrigins = {0, 5, 9};
widths = {10, 7, 3};
heights = {5, 8, 6};
mbrs = struct('label', labels, 'xorigin', xOrigins, 'yorigin', yOrigins, 'width', widths, 'height', heights);
  1. Delete the struct labeled with ‘MBR2’
  2. Delete the struct labeled with ‘MBR3’
  3. Delete all structs

Source code

I hope you have learned how to delete items from a struct array 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.