When coding in MATLAB, your functions must be organized and well-written. Although having well-written functions can seem somewhat subjective, there are objective criteria to assess how well-written a function is.

In this article, we’ll see why structures (or MATLAB struct) can help meet some of these criteria and how to use them. Specifically, we’ll tackle the following:

  • Improve your code by using structures
  • Define a structure in MATLAB
  • Manipulate MATLAB struct arrays
  • Convert a structure to a matrix
  • Use MATLAB commands to manipulate structures

Improve Your Code by Using Structures

Improving Your Architecture

Using structures forces you to see variables as subcategories of other variables. This way of thinking is a lot more intuitive than considering all the variables you’ve defined as “equal.”

I know it can sound erudite or impractical to think about that while coding. I mean, do you really have time for such minutia?

But, this would be disregarding the number of times you need to go back at your code to tweak and debug it. Trying to find a variable in a piece of code without structures would be like having all your household supplies on the floor and trying to find a screwdriver. Admittedly, placing it in the toolshed takes more time than throwing it on the floor, but doing so will save you time when you need to locate a certain portion.

Improving Your Readability

If a set of variables that describe the attributes of the same item is used separately in your code, the meaning of every variable needs to be separately investigated. If you use a structure to put them together, you only need to probe into one variable.

Doing the opposite would be a violation of the “DRY” (Don’t Repeat Yourself) principle since you somewhat repeat the shared meaning in every separate variable.

Using Fewer Arguments in a Function

On a more pragmatic note, structures promote the maintainability of your code. When a structure is used as an argument in a function, you get access to the different fields of the structure from within that function.

If you need access to a new variable that is outside that function, you can define that variable as a new field in an existing structure argument of that function. In this example, the more nested the function is, the more useful that structure becomes.

Generally speaking, the fewer input/output arguments in a function the better.

How to Define a Structure in MATLAB?

Define a Simple Structure

There are 2 ways to define a structure in MATLAB (i.e. a MATLAB struct). Let’s say you want to define a structure named block (representing a Simulink block) with 2 fields:

  1. Using the struct MATLAB command: Here’s the generic definition:
    namOfTheStructure = struct(fieldName1, valueOfTheFieldOne, fieldName2, valueOfTheFieldTwo);

    For example:

    block = struct('name', 'Subsystem', 'path', 'mySimpleModel/Subsystem');
  2. Using the dot symbol (.): Here’s the generic definition:
    nameOfTheStructure.fieldName1 = valueOfTheFieldOne;
    nameOfTheStructure.fieldName2 = valueOfTheFieldTwo;

    For example:

    block.name = 'Subsystem'; % name of the block 
    block.path = 'mySimpleModel/Subsystem'; % location of the block in your model
  • fieldName1 and fieldName2 are the names of the fields of the structure nameOfTheStructure.
  • valueOfTheFieldOne and valueOfTheFieldTwo are the variables contained in the fields of the structure. They could be anything—an array, a matrix, and, even a structure (that we would refer to as a “nested structure”).

In both examples, we’ve defined the same MATLAB struct:
Example of defining a structure using the MATLAB struct commandexample of a matlab structure definition
Let’s break it down:

  • Structure fields: “name” and “path” are fields of the structure block. Sometimes in Simulink, you’ll have to analyze or modify blocks in your model. To do that, you may need the name of the block you want to modify and its path (i.e. its location in the model) and other information.
  • Using a structure: if you need more information about a block (e.g. its handle), adding a field in the function where you define your structure will do the trick. This field can then be accessed by every function using the “block” variable.
  • Structure data type: the data type of a structure is struct, as you can see using the MATLAB command class:struct data type of a structure

Define an Array in a Structure

Defining an array in a structure comes down to considering the field as a regular variable:

matrix.value = [1 2 3 ; 4 5 6]; % value field of the matrix structure
matrix.size = size(matrix.value); % size field of the matrix structure

There are 2 things to notice here:

  • The “value” field of the matrix structure (matrix.value) is defined as a matrix in the same way you would define a regular matrix.
  • You can define a field of a structure using another field (namely matrix.value). This is another good practice because you only use the size MATLAB command once; then, you can use the size field of the matrix structure as much as you want. They will both improve the computation time and the readability of your code.

Access an Element in a Structure

Now that you can define a structure, you need to know how to access an element within a structure. Again, doing this is possible when considering the field as a regular variable:

block.name % access the name of the block
block.path % access the path of the block
matrix.value % access the matrix
matrix.size % access the size of the matrix

So, if you want to access an element of the “matrix.value” variable, for example, you can do that by considering “matrix.value” as a regular matrix:

rowOneColumnTwoElement = matrix.value(1,2);

Which would access the element of the 1st row and 2nd column of the “matrix.value” matrix:
example of accessing an element in a matrix structure

MATLAB Structure Array

Define an Array of MATLAB Struct

We’ve seen how to define an array in a structure, but you’ll often need to define an array of structure (matrix or vector). Let’s say that you want to define an array of Simulink blocks:

i = 1;
blockList(i).name = 'Subsystem';
blockList(i).path = 'mySimpleModel/Subsystem';
i = i+1;
blockList(i).name = 'Subsystem1';
blockList(i).path = 'mySimpleModel/Subsystem1';
i = i+1;
blockList(i).name = 'Subsystem2';
blockList(i).path = 'mySimpleModel/Subsystem2';

Another way would be to define an empty vector and to concatenate every element to the rest of the array as you go:

blockList = [];
block.name = 'Subsystem';
block.path = 'mySimpleModel/Subsystem';
blockList = [blockList block];
block.name = 'Subsystem1';
block.path = 'mySimpleModel/Subsystem1';
blockList = [blockList block];
block.name = 'Subsystem2';
block.path = 'mySimpleModel/Subsystem2';
blockList = [blockList block];

In both cases, you end up with:

Example of a matlab structure array

Although identical, I personally tend to use the second option much more frequently in a for loop and the first option as a way of initializing a structure. This is because the second way uncouples the loop iteration variable from the index of the array (there is no “i” in the second way).

Incidentally, using structures could be a way of circumventing the issue of lists of strings where each character is considered to be an element of a matrix. Therefore, storing a list of words that don’t have the same number of letters wouldn’t work.

For example, this wouldn’t work:

listOfWords = ['importantWord' ; 'anotherImportantWord']; % this wouldn't work

List of strings with matrix dimensions concatenated that are not consistent

But this would:

wordStructure.value = 'importantWord';
anotherWordStructure.value = 'anotherImportantWord';
listOfWordStructures = [wordStructure ; anotherWordStructure];

“listOfWordStructures” would then look like the following:

list of matlab struct words

Access an Element in a Structure Array

Accessing an element in a structure array is essentially the same as accessing an element in a regular array.

For example, if you want to access the second element of the “blockList” structure array defined above, use:

blockList(2) % acess the second element of the block list

example of accessing an element in an array structure

You can then access any field of this element:

blockList(2).name % this is 'Subsystem1'
blockList(2).path % this is 'mySimpleModel/Subsystem1'

Convert a Structure to a Matrix

In MATLAB, if you want to convert a structure to a matrix, you have to use a workaround. Let’s see how to do that by defining a structure with 4 fields:

mStructure.One = 1;
mStructure.Two = 2;
mStructure.Three = 3;
mStructure.Four = 4;

Let’s say that you want the following 2×2 matrix:

\(\begin{pmatrix}1 & 3\\2 & 4\end{pmatrix}\)

Using the struct2cell MATLAB command you can convert the structure “mStructure” into a vector of cells, which you can convert into a matrix using the command cell2mat:

mVector = cell2mat(struct2cell(mStructure));

Then, using the reshape MATLAB command as the following:

mMatrix = reshape(mVector, [2 2]); % reshape mVector as a 2x2 matrix

We can obtain the desired matrix:

Example of converting a matrix to a structure

But, if you want your matrix organized in such a way that the first fields of your structure appear on the first row instead of the first column (i.e. you want this matrix):

\(\begin{pmatrix}1 & 2\\3 & 4\end{pmatrix}\)

Then, using the transpose function:

mMatrixTranspose = reshape(mVector, [2 2])'; % notice the single quotation mark

We get:

Example of converting a matrix to a structure row wise

Useful Functions for Structures

Knowing Whether a MATLAB Struct Field Exists

When defining a structure based on a conditional statement you may need to query for the existence of a specific field in this structure. To do that, you can use the MATLAB command isfield:

matrix.value = [1 2 3 ; 4 5 6];
matrix.size = size(matrix.value);
isfield(matrix, 'value')

The first argument of this command is the structure, and the second is the field. The command isfield returns the Boolean value “1” if the field has been defined in the structure and “0” if it’s not. Thus, we get:
MATLAB command isfield example

This is because the field named “value” exists in the “matrix” structure.

Finding the Names of the Fields in a Structure

Sometimes, you won’t know what the fields of a structure are, so you’ll want to use the MATLAB command fieldnames to figure them out:

matrix.value = [1 2 3 ; 4 5 6];
matrix.size = size(matrix.value);
fieldnames(matrix)

The fieldnames command returns a cell array containing the name of the fields of the structure. In this example, the field names are “value” and “size”:
MATLAB command fieldnames example on a matrix structure
This command is particularly useful when you want to know the field of a Simulink block. For example:

fieldnames(get_param(gcb, 'ObjectParameters'))

If you click on a Simulink block and run the command above, you’ll get the list of all the fields of a Simulink block structure.

Determining If a Variable Is a Structure

Another simple and useful MATLAB command is the isstruct command, which returns the Boolean value “1” if its argument is a structure and “0” otherwise:

matrix.value = [1 2 3 ; 4 5 6];
matrix.size = size(matrix.value);
isstruct(matrix)

In our case, we have:
Example of isstruct matlab command

Defining and Displaying a Nested Structure

As we saw already, we can define a nested structure by defining a structure in the field of another structure.

For example, instead of defining the field “size” in the matrix structure, we could define another structure that we would call “info” with the field “size” and “numberOfElements”:

matrix.value = [1 2 3 ; 4 5 6];
matrix.info.size = size(matrix.value);
matrix.info.numberOfElements = numel(matrix.value);

“matrix.info” would then be a nested structure of the data type “struct”:
Example of definition of a nested structure
The issue with nested structure is that you don’t see them by typing the upper-level structure name; instead, you only see the current layer of the level of the structure typed into your workspace:
hidden nested structure matlab example

You can’t see the fields of the structure in the “info” field of the matrix structure.

To display every level of the structure, you can use the function “datastructure” (see here:
https://www.mathworks.com/MATLABcentral/fileexchange/35156-display-data-structure-for-nested-struct)
Then, you can use as the following:

matrix.value = [1 2 3 ; 4 5 6];
matrix.info.size = size(matrix.value);
matrix.info.numberOfElements = numel(matrix.value);
datastructure(matrix, [], 'test.txt');

This will create a text file (called “test.txt” in this example) where the nested structures are detailed:
Example of displaying nested structures in matlab

Key takeaways:

  1. There are 2 ways to define a structure:
    • Using the struct MATLAB command:
      namOfTheStructure = struct(fieldName1, valueOfTheFieldOne, fieldName2, valueOfTheFieldTwo);
    • Using a dot (.) after the name of a variable:
      nameOfTheStructure.fieldName1 = valueOfTheFieldOne;
      nameOfTheStructure.fieldName2 = valueOfTheFieldTwo;
  2. To access an element of a structure:
    nameOfTheStructure.fieldName1 % access valueOfTheFieldOne
    nameOfTheStructure.fieldName2 % access valueOfTheFieldTwo
  3. To define an array of structure:
    i = 1;
    nameOfTheStructure(i).fieldName = valueOne; % first element of the array 
    i = i+1;
    nameOfTheStructure(i).fieldName = valueTwo; % second element of the array 
    i = i+1;
    nameOfTheStructure(i).fieldName = valueThree; % third element of the array
  4. To access an element in a structure array:
    nameOfTheStructure(elementIndex).fieldName % access one element of the array
  5. To convert a structure to a matrix:
    mVector = cell2mat(struct2cell(mStructure)); % mStructure is the structure
    mMatrix = reshape(mVector, [m n]); % reshape mVector as a m x n matrix
    mMatrixRow = reshape(mVector, [m n])'; % first fields appear on first row
  6. Here are some useful functions:
    nameOfTheStructure.fieldName = valueOfTheField; % structure definition
    isfield(nameOfTheStructure, fieldName) % 1 if fieldName is a field, 0 otherwise
    fieldnames(nameOfTheStructure) % returns the name of the fields of the structure
    isstruct(nameOfTheStructure) % 1 if the argument is a structure, 0 otherwise
  7. To define a nested function:
    nameOfTheStructure.fieldNameLevelOne.fieldNameLevelTwo = variable;

🌲 If you want to learn more about the tools that helped me stop wasting time doing mindless work (such as generating Excel reports, Word documents, or creating clean and simple user interfaces) I wrote a small reference book about it:

👉 www.amazon.com/dp/B08L7FM1BB