Find a Guide

Creating Structures in MATLAB

Introduction

Another handy way to store data in MATLAB is with structures. Structures allow us to assign a variable sub-values that can be named and filled out by the user. Instead of having many variables all related to the same problem, you can cluster them under one structure to keep your code clean and legible! Let's get started.

Creating Structs

Creating a structure is a quick thing to do. Let's say we want to have a structure with the name 'pizza' and we want to assign information to the pizza such as number of slices it can have or toppings it can have. Let's do that!

matlab

pizza.numOfSlices = 8;
pizza.topping = "cheese;

Here we just defined a pizza structure that holds the number of slices on the pizza and the topping on it! However, that would take up a lot of space if we had a different line for each structure field. What if we had 10? In that case, we can use a shorter format to do this!

matlab

pizza = struct('numOfSlices', 8, 'topping', "cheese");

Editing Structs

That is better, but now what if we want to say that the pizza can be cut into a different number of slices? Then we can override the field 'numOfSlices' as so:

matlab

pizza.numOfSlices = [6 8 12];

Now we know how to create and edit structures!

Find a Guide