MATLAB techniques for modeling and simulation
MCB 419: Brain, Behavior and Information Processing
M. Nelson, Univ. of Illinios, Urbana-Champaign, Jan 2005
Structures are a useful way of grouping MATLAB variables that belong together. For example, imagine that you're simulating a ball being dropped from a building. You might have a scalar representing the mass of the ball, a vector representing its position, another vector representing its velocity, etc. You can group all the ball properties together into a MATLAB structure called ball:
clear ball.mass = 10; ball.position = [0, 0, 100]; ball.velocity = [0, 0, 0];
To see the contents of a structure, just type it's name at the command prompt >>
ball
ball =
mass: 10
position: [0 0 100]
velocity: [0 0 0]
The individual components of the structure are called fields. You can also examine the content of an individual field:
ball.position
ans =
0 0 100
You can operate on elements of the structure just like any other MATLAB variable. For example to move the current XYZ-position of the ball by +10 in the y direction, you could type:
ball.position = ball.position + [0, 10, 0]
ball =
mass: 10
position: [0 10 100]
velocity: [0 0 0]
You can add a new field to the data structure at any time. For example, we'll add a new field for the radius and set its value:
ball.radius = 2.0
ball =
mass: 10
position: [0 10 100]
velocity: [0 0 0]
radius: 2
You can have an array of structures to represent multiple objects. For example, let's create two more "balls" by making a copy of the original "ball" structure:
ball(2:3,1) = ball;
now let's see what has happened:
ball
ball =
3x1 struct array with fields:
mass
position
velocity
radius
MATLAB tells us that "ball" is now a 3x1 struct array. Each of the three elements of the struct array is a "ball" structure. Let's say we wanted each of the three balls to have a different mass:
ball(1).mass = 1.0; ball(2).mass = 5.0; ball(3).mass = 10.0;
Let's look at ball(2) now:
ball(2)
ans =
mass: 5
position: [0 10 100]
velocity: [0 0 0]
radius: 2
Now let's examine the masses of all three balls:
ball.mass
ans =
1
ans =
5
ans =
10
Notice that MATLAB returned 3 different answers, one for each structure in the struct array.
Usually, we'd like all of these answers returned together in a single array. This can be accomplished by enclosing everything in square brackets.
[ball.mass]
ans =
1 5 10
So, if we wanted to compute the total mass of all three balls, we could type:
totalMass = sum([ball.mass])
totalMass =
16
However, if we tried it without the square brackets, we would get an obscure error message:
try totalMass = sum(ball.mass) catch lasterr end
ans = Error using ==> sum Trailing string input must be 'double' or 'native'.
If you see strange error messages like the one above when using struct arrays, it should make you think about square brackets!