Tutorial

How to Remove Fields From a Struct Array in MATLAB

The function rmfield removes fields from a struct array.

Preparation

Create a struct array using the following code:

names = {'Peter Pan','Wendy Darling'};
sexes = {'M','F'};
ages = {11,12};
A = struct('name', names, 'sex', sexes, 'age', ages);
whos A;

Remove fields

R = rmfield(s,field) removes a field or multiple fields from a copy of the struct array s, and saves the result in R. Specify multiple fields using a cell array of strings. Both R and s are struct arrays of the same size.

Note that the original struct array remains unaffected.
% Remove the field 'sex'
resultExample1 = rmfield(A,'sex');
% Remove the fields 'name' and 'age'
fields = {'name','age'};
resultExample2 = rmfield(A,fields);
% Permanently remove the field 'age' from A
A = rmfield(A,'age');
If a field does not exist, MATLAB generates an error.

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 following page in the MATLAB help documentation, and the other tutorials in this series.

doc rmfield;

Exercise

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);
  1. Create a struct array equivalent to points, but without the field ‘red’
  2. Create a struct array equivalent to points, but without the fields ‘red’ and ‘green’
  3. Permanently remove the field ‘blue’ from points

Source code

I hope you have learned how to remove fields 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.