Structures in Matlab

In Matlab structures are a special kind of array that can contain many different data types and sizes. This can be useful to group data that is related but not of the same type/size.

Contents

To create a structure use the "." to Define a field. For example:

myStruct.Names = {'Bob' 'Ben' 'Alex' 'John'};
myStruct.Grades = [67 58 89 85];

This creates a structure called "myStruct" with fields "Names" and "Grades". Accessing a particular entry just uses "()".

aName = myStruct.Names(1)
aGrade = myStruct.Grades(1)
aName =

  cell

    'Bob'


aGrade =

    67

There are a number of built in Matlab functions which operate on structures.

This returns the field names of the structure.

fieldnames(myStruct)
ans =

  2×1 cell array

    'Names'
    'Grades'

This returns the values of a specific field.

getfield(myStruct,'Grades')
ans =

    67    58    89    85

This checks whether the input is a field in the structure.

isfield(myStruct,'Names')
isfield(myStruct,'BLAH')
ans =

  logical

   1


ans =

  logical

   0

Notes

To see the full list of functions that operate on Structures and for more examples please go to: https://www.mathworks.com/help/matlab/structures.html