I have a structure with many fields which are vectors of different lengths. I would like to access the fields within a loop, in order. I tried getfield as follows but MATLAB doesn't like that. How can I do this?
S = struct('A', [1 2], 'B',[3 4 5]); SNames = fieldnames(S); for loopIndex = 1:2 field = getfield(S, SNames(loopIndex)); %do stuff w/ field end ??? Index exceeds matrix dimensions
I'm using structures in the first place because an array would have trouble with the different field lengths. Is there a better alternative to that?
Access Field of Scalar StructureWhen you use the getfield function, you can access a field of the structure returned by a function without using a temporary variable to hold that structure. You also can access a field using dot notation.
Field names that you reference with expressions are called dynamic fieldnames, or sometimes dynamic field names.
A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a structure using dot notation of the form structName.
Try dynamic field reference where you put a string in the parenthesis as seen on the line defining stuff.
S = struct('A', [1 2], 'B',[3 4 5]); SNames = fieldnames(S); for loopIndex = 1:numel(SNames) stuff = S.(SNames{loopIndex}) end
I concur with Steve and Adam. Use cells. This syntax is right for people in other situations though!
There are three points I'd like to make here:
The reason you are getting an error in your above code is because of how you are indexing SNames
. The function fieldnames
returns a cell array of strings, so you have to use content indexing (i.e. curly braces) to access the string values. If you change the fourth line in your code to this:
field = getfield(S, SNames{loopIndex});
then your code should work without error.
As suggested by MatlabDoug, you can use dynamic field names to avoid having to use getfield
(which yields cleaner looking code, in my opinion).
The suggestion from Adam to use a cell array instead of a structure is right on the mark. This is generally the best way to collect a series of arrays of different length into a single variable. Your code would end up looking something like this:
S = {[1 2], [3 4 5]}; % Create the cell array for loopIndex = 1:numel(S) % Loop over the number of cells array = S{loopIndex}; % Access the contents of each cell % Do stuff with array end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With