Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: using getfield() with a stuct array
Replies: 3   Last Post: Jan 18, 2013 5:14 PM

 Messages: [ Previous | Next ]
 Steven Lord Posts: 18,038 Registered: 12/7/04
Re: using getfield() with a stuct array
Posted: Jan 18, 2013 5:14 PM

"Bruce Elliott" <bruce.elliott@jhuapl.nospam.edu> wrote in message
news:kdc3h7\$d6b\$1@newscl01ah.mathworks.com...
> Is there any way to use getfield() on an array of structure and to get a
> same-sized array of field values?
>
> In other words, I can do this:
>
> x = [myArr.F];
>
> to get an array with the values in the field F in my stuct array, myArr.
>
> This, however, does not work:
>
> x = getfield(myArr,'F');
>
> (Putting [] around anything on the right-hand-side does not help.)
>
> There's probably a good reason for this, but the documentation suggests
> that x = getfield(S,'F') is equivalent to x = S.F, so I would have hoped
> that I could do this.

For _scalar_ struct arrays S, yes those are equivalent.

http://www.mathworks.com/help/matlab/ref/getfield.html

"value = getfield(struct, 'field'), where struct is a 1-by-1 structure,
returns the contents of the specified field, equivalent to value =
struct.field."
and
"If structure struct or any of the fields is a nonscalar structure, and you
do not specify an Indx, the getfield function returns the values associated
with the first index."

Try:

thefieldname = 'F';
x = [myArr.(thefieldname)]

You can use this like:

F = struct('x', {2, 5, 17})
z = F(mod([F.('x')], 2) == 1)

This will extract the elements of F whose x fields contain odd values. From
the way I constructed F you would expect z to contain two elements, and it
does.

--
Steve Lord
slord@mathworks.com