Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

Vectorizing Access to an Array of Structures

Though I have written about this topic before, I continue to get questions on working with arrays of structures. So I thought I would focus on that alone today.

Contents

Recent Sample Question

Recently there was a question on the newsgroup about how to vectorize the access to elements in a structure array. And also got an email from a customer on this topic. Here is one customer's description of his problem:

    In a nutshell, what I am trying to do (in as few lines of code as
    possible) is:
    state = an array of structs, say N items each with (for example)
    components x and y.
    In my case 'state' is reasonably complicated and hence does not
    warrant the use of a simple 2 x N matrix.
    for i=2:N
       state(i)=markovmodel(state(i-1)); % 1. Access individual structs
    end
    plot(state.x) % 2. Access all of the entries of one element as  vector.

The Answer

Let's create an array of structures first.

states(1).x = 3;
states(2).x = 4;
states(3).x = 5;
states(1).y = 42;
states(2).y = 99;
states(3).y = 0;
states
states = 
1x3 struct array with fields:
    x
    y

Let's see what's in states.x

states.x
ans =
     3
ans =
     4
ans =
     5

With an array of structs, you can gather the x values using

allxvals = [states.x]
allxvals =
     3     4     5

This is because states.x produces a comma-separated list. How do I know this? Because, if I leave the semi-colon off, I see a bunch of output with ans =; in other words, I am getting multiple output values. How do I collect multiple values into an array? I can use either square brackets or curly braces.

Using the square brackets, [], just places that list into between the brackets, creating an array of one type, in this case, doubles. You can do likewise with struct arrays with fields that are more suitable for a cell array using curly braces, {} in place of the square brackets.

User Solution

If instead of using

    plot(state.x)
above, the user replaced this with
    plot([state.x])

the informationg gets plotted correctly.

Comments?

My question to you is why this question keeps getting asked. Is the concept unusual enough that people don't know how to even look for the information on-line? What can we do at The MathWorks to make this more visible? Please pass along your thoughts here.




Published with MATLAB® 7.4


  • print