Loren on the Art of MATLAB

Turn ideas into MATLAB


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

Iterating over Non-Numeric Values

Recently a colleague was hoping to write some code to iterate over fields in a structure. There are at least three different ways I can think of, some more straight-forward than others. Here's what I've come up with.


Create Data for an Example

I'm only going to consider scalar structures for this post. The contents of each field in this case will also be scalars, for easy illustration. I'd like to create output that increases the value of each entry by 1.

s.a = 1;
s.b = 2;
s.c = 3;

Let me get the field names so I can have the code be reasonably generic.

fn = fieldnames(s)
fn = 

First Method - Loop Over Number of Field Names

In the first case, I find out how many fields are in the struct, and then loop over each of them, using dynamic field referencing to access the value in each field.

out1 = zeros(1, length(fn));
for n = 1:length(fn)
    out1(n) = s.(fn{n}) + 1;
out1 =
     2     3     4

Second Method - Loop Over Field Names Themselves

In the second case, I am going to bypass the numeric indexing and loop through the fields themselves. Since the for loop in MATLAB processes the indices a column at a time, I have to turn my column of field names into a row vector. It happens to be a cell array, so I also have to convert the field names to character arrays to use dynamic field referencing. I won't preallocate the output out2 this time, but allow this small array to grow, so I don't need to add a counter to the loop.

out2 = [];
for str = fn'
    out2(end+1) = s.(char(str)) + 1;
out2 =
     2     3     4

Check that the results of the first two methods agree.

ans =

Third Method - Use structfun

Instead of looping through fields at all, use structfun which iterates over fields in a scalar structure.

out3 = structfun(@(x)x+1,s);
out3 = out3.'
out3 =
     2     3     4

Since the results are returned as a column vector, I transpose them so I can compare the output to that of the other methods. Check that the results of the last two methods agree.

ans =

Which Way is Clearest?

I've shown you three ways to iterate over fields in a structure. Which method(s) do you currently use? Which one seems clearest to you? Let me know here.

Published with MATLAB® 7.4

  • print
  • send email