Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Structures

What Is a Structure?

A structure is a MATLAB data type that provides the means to store hierarchical data together in a single entity. A structure consists mainly of data containers, called fields, and each of these fields stores an array of some MATLAB data type. You assign a name to each field as you create the structure. The figure below shows a structure s that has three fields: a, b, and c.

Each field of a structure contains a separate MATLAB array. This array can belong to any one MATLAB or user-defined class, and can have any valid array dimensions. A second field of the same structure can belong to an entirely different class, and can also have different dimensions than the first. The fields of the structure shown above, for example, contain a 1-by-6 array of class double, a 1-by-5 array of class char, and a 3-by-3 array of double.

Like all MATLAB data types, the structure is an array. The class of a structure is called struct, so an array of structures is often referred to as a struct array. Like other MATLAB arrays, a struct array can have any dimensions. The struct array shown below has the dimensions 1-by-2 and is composed of two elements: s(1) and s(2). Each of these elements is a structure with fields a, b, and c of its own.

Each element of a struct array must contain the same number of fields and use the same field names as every other element of that struct array. The arrays of data that are stored in these fields, however, do not have to match; they can belong to different classes, and they can have different dimensions. In the struct array shown above, for example, fields b and c of element s(1) contain arrays of different classes and dimensions. The same holds true for fields that are named the same but belong to different elements of the struct array. An example of this is field b in s(1) and field b in s(2).

Reasons to Use a Structure

Perhaps the most common reason for using a structure (or a cell array) is the ability to store arrays of mixed classes and sizes. Most MATLAB arrays must contain the same number of elements which must also be of the same class. The role of the structure, and cell array, as containers of heterogeneous data is very important.

A structure also provides the means to store selected data together in a single entity. This offers you the ability to access and operate on all or parts of the data collectively. You can apply functions directly to a structure, pass the structure to and from your functions, display the value of any fields, or perform most any MATLAB operation on the contents of a structure.

A third reason to use structures is that they give you the ability to apply text labels to your data, as opposed to using array subscripting.

Comparing Struct Arrays with Cell Arrays

Struct arrays and cell arrays are similar in purpose and, in some ways, also design. Both provide a means of storing heterogeneous data in containers of different size and type. Probably the most noticeable difference between the two is that the containers of a structure are named fields, whereas a cell array uses numerically indexed cells.

Structures are often used in applications where organization of the data is of high importance. Cell arrays are often used when working with data that you intend to process by index in a programming control loop. Cell arrays are also useful in storing character strings of different lengths.

There are many reasons for choosing either structures, cell arrays, or both for your work in MATLAB. For more information on cell arrays, see Cell Arrays in the MATLAB Programming Fundamentals documentation.

Creating a Structure

This section describes how to create struct arrays of different shapes and sizes, how MATLAB keeps the number of fields the same for all elements, and how to preallocate memory for larger structures.

Creating Structures and Structure Fields

There are two ways of creating a MATLAB structure: by individual assignments to its fields, or by a single call to the struct function. The figure below shows a 1-by-1 structure s having three fields: a, b, and c. The two sets of commands that can create this structure are shown to the left of and below the figure:

The three statements at the top left are an example of individual assignment to fields. The syntax s.a used in the first of these statements refers to field a of structure s. The structure does not exist yet, so MATLAB creates the structure and the given field a, and assigns the value 5 to the field. The two remaining statements add two new fields to the structure and set their values to 10 and 15, respectively.

The statement at the bottom left uses the struct function to create the structure and its fields and to assign the respective values to each. See the reference page for the struct function for the various syntax options you can use.

Structures with Nonscalar Fields.  The next figure creates a three-field structure to contain nonscalar array values. The statements used to create this structure are very much like those used in the previous figure.

Nonscalar Struct Arrays.  The next figure creates a struct array s that has two elements, s(1) and s(2). Each element of the struct array has three fields: a, b, and c. To create this array by assigning to fields, you need to specify which element of s you are assigning to. For example, to create a field b for element 2 of struct array s, assign to s(2).b.

The struct function requires a slightly different syntax when creating fields in multiple elements of the struct array. Follow each field name argument with a list of values enclosed in curly braces {}. The enclosed list specifies the values to be assigned to that field for the successive elements of the struct array. For example, the first two input arguments shown in the struct command below are 'a' and {[1 4 7 2 9 3],'Anne'}. This tells MATLAB to assign the vector [1 4 7 2 9 3] to s(1).a, and the string 'Anne' to s(2).a:

In mmatlab, curly braces {} operator constructs a cell array. One use of cell arrays is as a convenient way to pass arguments when calling a function. This is exactly how they are used with the struct function. When you use this operator to pass multiple field values to the struct function, you are actually passing these values packaged in a cell array. The struct function, upon receiving the cell array argument, removes the field values from the cell array and assigns them to the fields specified in your struct command.

Suppose that, in the example above, you want to create a field a of for struct element s(1). But instead of s(1).a being a 1-by-6 numeric array, you want it to be a 1-by-6 cell array. In that case, you would need to enclose the first argument itself with curly braces:

s = struct('a', {{1 4 7 2 9 3}, 'Anne'}, ...
           'b', {'James', pi}, ...
           'c', {magic(3), (1:7)'});

Nested Structures.  The next figure shows an example of one struct array stored (or nested) within another struct array. The inner struct array, called myfun, is a collection of two function handles. The commands shown to the left build the two structures, storing the inner structure in field c of the first element of the outer structure:

How you organize your structure will depend on your use case. See the reference page for the struct function for more information on using this function to create structures.

Handling Unassigned Fields

Each element of a nonscalar struct array must have the same set of fields. Whenever you add a new field to a struct array, MATLAB adds a field of the same name to all elements of the struct array.

For example, if you enter the following commands:

s.a = 5;
s.b = 10;
s(2).a = 15;

MATLAB creates and assigns values to the three specified fields, and also creates an unspecified field s(2).b, setting its value to the empty array ([]). This ensures that the fields of s(1) and s(2) are the same in number and name. This is called scalar expansion:

s(2).b
ans =
     []

MATLAB also automatically keeps field naming and count the same for all elements when you use the struct function to create a struct array. In this case, however, field b of elements s(2) and s(3) are set to the value specified for s(1).b, which is 10:

s = struct('a', {5, 15, 25}, 'b', 10);
[v1 v2 v3] = s.b;

[v1  v2  v3]
ans =
    10    10    10

This example calls struct with three values for field a and two values for field b, causing the command to generate an error:

s = struct('a', {5, 15, 25}, 'b', {10, 15});
??? Error using ==> struct
Array dimensions of input 4 must match those of 
   input 2 or be scalar.

Preallocating Memory for the Array

MATLAB stores the field names and any overhead information required by a struct array in contiguous memory. If you increase the number of fields used by a struct array over time, even if this happens just by increasing the dimensions of the array, MATLAB uses up more of this contiguous piece of memory for field name storage. This can eventually lead to "out of memory" errors.

If you can roughly estimate the number of fields and the number of struct array elements at the time you create a struct array, you can preallocate the necessary space in memory and help to avoid this type of problem. See the documentation on Data Structures and Memory to help you make this estimate.

How to Preallocate Memory.  Methods for preallocating and initializing a struct array are as follows:

After the memory has been allocated, you can begin to construct the array by assigning data to it.

Structure Fields

This section describes how to name the fields you create, how to find out what fields a structure contains, how to create and assign field names at run time, and the functions that MATLAB provides to help work with the fields of a structure.

Guidelines for Naming Structure Fields

A field name is just a character string. MATLAB field names must follow the same rules as standard MATLAB variables:

  1. Structure field names must begin with a letter, and can contain additional letters, digits, or underscore characters.

  2. It is advisable to keep field names to a maximum of N characters, where N is the number returned by the function namelengthmax. MATLAB accepts longer names, but only uses the first N characters and ignores the rest.

  3. MATLAB distinguishes between uppercase and lowercase characters. The field name S.income is not the same as the name S.Income.

  4. In most cases, you should refrain from using the names of functions or other active variables as field names.

Listing the Fields of a Structure

To access the contents of a struct array, you first need to find out what the names of its fields are. The fieldnames function returns a cell array of strings listing all fields belonging to the structure array. The fields appear in the order in which they were created.

Here is a structure with four fields:

USPres.name = 'Franklin D. Roosevelt';  
USPres.vp(1) = {'John Garner'};
USPres.vp(2) = {'Henry Wallace'};       
USPres.vp(3) = {'Harry S. Truman'};
USPres.term = [1933, 1945];             
USPres.party = 'Democratic';

The fieldnames function returns the names of each field of USPres in a 4-by-1 cell array of strings:

presFields = fieldnames(USPres)
ans = 
    'name'
    'vp'
    'term'
    'party'

Another means of acquiring fieldnames is to just enter the name of the structure. For a scalar structure, this returns more than just the fieldnames; it also displays the value of each field:

USPres = 
     name: 'Franklin D. Roosevelt'
       vp: {'John Garner'  'Henry Wallace'  'Harry S. Truman'}
     term: [1933 1945]
    party: 'Democratic'

Arranging Fieldnames Alphabetically

By default, MATLAB orders the fieldnames of a structure according to the order in which they were created. The orderfields function returns a new struct array that is just like the original, except that the order of the field names is alphabetical. If you assign the output of orderfields back to the input structure, it effectively modifies the field ordering of the input structure:

USPres = orderfields(USPres);

Creating Field Names Dynamically

Another way to give a name to a structure field is to derive the name at the time MATLAB executes your code. First, establish a variable to represent the field name of your structure. Then, at run time, MATLAB uses the current value of this variable as the field name. This is called a dynamic field name. You can only use dynamic field names when you create your struct array using individual assignment to fields.

The syntax for creating a field name dynamically is

structName.(dynamicExpression) = fieldValue;

The term dynamicExpression is any MATLAB expression that returns a character or string. For example, in the following statement, the datestr function returns the string Nov2708 which then becomes a field name in the price structure. The dot-parentheses .( ) syntax tells MATLAB that the string value returned by datestr(now,'mmmddyy') is a field name for the structure:

price.(datestr(now,'mmmddyy')) = 89.99;

Examining the field names for the price structure shows the Nov2708 field just added:

fieldnames(price)
ans =
    'Nov2708'

Functions That Operate on Fields

The following functions are commonly used with the field names of structures. For more information on these functions, consult the MATLAB Function Reference documentation:

FunctionDescriptionReturn Value
fieldnamesGet all field names of specified structure.Cell array of strings listing fields of input structure in the order in which they were assigned to the structure.
getfieldGet contents of the specified field.Current value assigned to specified field.
isfieldDetermine if input is a structure field.true if the field is a structure field. Otherwise, false.
orderfieldsOrder fields of a structure array.Copy of the input structure with fields ordered alphabetically.
rmfieldRemove structure field.Input structure with specified field removed.
setfieldSet structure field contents, returning the modified structure.Input structure with specified field set to new value.

To set the value of a structure field, you can either assign it directly, or use the setfield function. Likewise, you can obtain the value of a field as shown in the section Returning Data from a Struct Array or by using the getfield function.

Concatenating Structures

You can concatenate arrays of structures and arrays of structure fields as explained below.

Concatenating Structure Arrays

When concatenating structure arrays, all of the following must be true:

Create three struct arrays S1, S2, and S3, each having three fields F1, F2, and F3:

rand('state', 0);     % Initialize random number generator
S1 = struct('F1', 'ID_1', 'F2', 2:3:14, 'F3', rand(3,3));
S2 = struct('F1', 'ID_3', 'F2', -2:3:10, 'F3', rand(3,2));
S3 = struct('F1', 'ID_4', 'F2', -3:2:5, 'F3', rand(3,1));

Concatenate the three structures to create a 1-by-3 array of structures:

	T1 = [S1 S2 S3]
T1 = 
1x3 struct array with fields:
    F1
    F2
    F3

This creates a single structure T1 having the same fields as S1, S2, and S3. Each field in the new structure T1 contains the data from all of the concatenated fields:

T1.F3
ans =
    0.9501    0.4860    0.4565
    0.2311    0.8913    0.0185
    0.6068    0.7621    0.8214
ans =
    0.4447    0.9218
    0.6154    0.7382
    0.7919    0.1763
ans =
    0.4057
    0.9355
    0.9169

Concatenating Structure Fields

You concatenate structure field arrays following the same guidelines used when concatenating any other types of arrays.

Indexing into a Struct Array

This section describes how to index into the elements of a struct array, and any arrays that are contained within a struct field.

Basic Struct and Field Indexing

The most general indexing with which to store data into or retrieve data from a struct array is

structName(sRows, sCols, ...).fieldName(fRows, fCols, ...)

If the structure is scalar, then you can omit the structure indexing as shown here:

structName.fieldName(fRows, fCols, ...)

Indexing to Inner Levels of the Struct Array

The fields of a structure contain arrays of standard MATLAB data types. These arrays use the indexing syntax appropriate to the class of the array. The table below shows examples of statements that use a combination of struct and cell array indexing:

Array ElementSyntax to Use
Access an element of an array A, where A is a field of structure S.S(3,15).A(5,25)
Access an element of cell arrayA, where A is a field of structure S.S(3,15).A{5,20}
Access an element of array B, where B is a field of struct array A, and A is a field of struct array S.S(3,15).A(5,20).B(50,5)
Access an element of array B, where B is a field of a structure that resides in cell array A, and A is a field of structure S.S(3,15).A{5,20}.B(50,5)
Access an element of cell array B, where B is a field of structure A, and A is a field of structure S.S(3,15).A.B{5,20}

Indexing Tips

Some techniques that could help you in determining how to format struct array indexing are:

Returning Data from a Struct Array

The following table shows a number of different ways of returning data from a struct array. The variable s is a 3-by-4 structure with fields a, b, and c. Each of these fields is a 2-by-5 array of class double:

Values To Be AcquiredMATLAB StatementData Structure Returned
The entire struct array ss3x4 struct array with fields a, b, and c.
The entire struct array s, as a vectors(:)12x1 struct array with fields a, b, and c.
Selected elements of struct ss(2:3,1:3)2x3 struct array with fields a, b, and c.
The full array a in selected element of s.s(2,3).a2x5 array of double.
The full array a in multiple elements of s.s(2:3,3:4).a4-item comma-separated list of 2x5 double.
The full array a in all elements of s.s.a12-item comma-separated list of 2x5 double.
Selected elements of a in one element of s. Multiple elements of s are not allowed with this syntax.s(3,4).a(2,3:5)1x3 array of double.

The first three of these indexing expressions provide no access to individual elements of the field arrays. You could use these expressions to copy, rearrange, or delete parts of the structure.

Assigning Struct Array Values to a Comma-Separated List

Accessing a single value from a field in a struct array is no different from accessing one of the elements of any other MATLAB data type. You specify the appropriate subscripts for the struct and field arrays and MATLAB returns the value stored at that location in the array.

Accessing multiple elements, however, can be quite different. Multiple elements of a struct array cannot be assigned to a single variable because they do not necessarily belong to the same class. Instead, MATLAB assigns values from a struct array to a series of separate variables called a comma-separated list.

Create a struct S, with one field, A:

S = struct('A', {5, 'Anne', @myfun, 1:5});

Examining field A for all elements of S returns a comma-separated list:

S.A
ans =
     5
ans =
     Anne
ans = 
     @myfun
ans =
     1     2     3     4     5

The potential problem with this type of output is that MATLAB overwrites the ans variable for each value returned. If you only want to display these values, then this command should suit your purpose. The next section shows how to assign to variables that you can reuse.

Assigning Struct Values to Separate Variables

If you were to assign multiple elements of a struct array to just one variable, MATLAB uses that variable to return the first value, but is unable to return all values of the array:

x = s.a
x =
     5

If you know how many values there are in the struct array elements you are trying to access, then you can provide that many outputs in the command, as shown here:

[v1 v2 v3 v4] = s.a

v1 =
     5
v2 =
     Anne
v3 = 
     @myfun
v4 =
     1     2     3     4     5

As in the previous example, this is a comma-separated list. Each return variable is of the class and size of the struct array element assigned to it:

whos v1
  Name      Size            Bytes  Class     Attributes

  v1        1x1                 8  double 

whos v2
  Name      Size            Bytes  Class    Attributes

  v2        1x4                 8  char

Assigning Struct Array Values to a Cell Array

You can assign the values of the struct array to a cell array using the following syntax:

[x{1:4}] = s.a
x = 
    [5]    'Anne'    @myfun    [1x6 double]

whos x
  Name      Size            Bytes  Class    Attributes

  x         1x4               320  cell 

Preallocating the cell array to a certain size and shape gives you control over how MATLAB returns the output:

x1 = cell(4,1);        %  Make x1 a 4-by-1 array
[x1{:}] = s.a
x1 = 
    [         5]
    'Anne'
    @myfun      
    [1x6 double]

x2 = cell(2,2);        %  Make x2 a 2-by-2 array
[x2{:}] = s.a
x2 = 
    [   5]    @myfun      
    'Anne'    [1x6 double]

x3 = cell(1,3);        %  Make x3 a 3-element array
[x3{:}] = s.a
x3 = 
    [5]    'Anne'    @myfun

Another way to do this is to use the following statements:

[x1{1:4,1}] = s.a
[x2{1:2,1:2}] = s.a
[x3{1:3}] = s.a

Using Structures with Functions

This section describes how to apply a function to data contained within a structure field using the structfun function, and also how to pass arguments to and from a function using structures.

Applying a Function to the Fields of a Structure

Use the structfun function to execute a function on each field of a scalar struct array. This example executes an anonymous function on a structure having fields that name the days of a week. The anonymous function, @(x)x(1:3), shortens each string to its first three characters. The function reference page for structfun explains the use of the UniformOutput option:

days.f1 = 'Sunday';    days.f2 = 'Monday';   
days.f3 = 'Tuesday';   days.f4 = 'Wednesday';   
days.f5 = 'Thursday';  days.f6 = 'Friday';
days.f7 = 'Saturday';

shortNames = structfun(@(x)x(1:3), days, 'UniformOutput', false)
shortNames = 
    f1: 'Sun'
    f2: 'Mon'
    f3: 'Tue'
    f4: 'Wed'
    f5: 'Thu'
    f6: 'Fri'
    f7: 'Sat'

See the reference page for structfun for additional help on using this function.

Passing Arguments in a Structure

A simple and easily maintainable way to pass arguments to or from a function is to package them in a structure, and then pass the entire structure to the function. This example passes information pertaining to four United States presidents to the function showPresInfo using only one input argument. You can also use struct arrays to return data from a function call.

Store data on the presidents in a 1-by-30 struct array:

USPres(27).name = 'William Howard Taft';   % 27th US President
USPres(27).term = [1909, 1913];            % Term
USPres(27).vp = 'James S. Sherman';        % Vice President

USPres(28).name = 'Woodrow Wilson';        % 28th
USPres(28).term = [1913, 1921];
USPres(28).vp = 'Thomas R. Marshall';

USPres(29).name = 'Warren G. Harding';     % 29th
USPres(29).term = [1921, 1923];
USPres(29).vp = 'Calvin Coolidge';

USPres(30).name = 'Calvin Coolidge';       % 30th
USPres(30).term = [1923, 1929];
USPres(30).vp = 'Charles Dawes';

Write a program to display the information passed in:

function passFullStructArray(number, info)

% Describe the INFO input.
[dim1,dim2] = size(info);   typ = class(info);
fprintf('\nInput 2 is a %d-by-%d %s array.\n', ...
    dim1, dim2, typ);

% Show the result.
fprintf('\nThe %dth element of the struct contains:\n', number)
info(number)

Call the program, passing the entire struct array:

passFullStructArray(29, USPres)

Input 2 is a 1-by-30 struct array.

The 29th element of the struct contains:
ans = 
    name: 'Warren G. Harding'
    term: [1921 1923]
      vp: 'Calvin Coolidge'

Passing Selected Fields in a Structure

You can also pass selected fields of a structure in a function call. This example passes 4 elements of the vp field of the USPres struct array in the form of a comma-separated list. In this case, the function being called, showVPInfo, receives these strings as four separate input arguments:

The value passed to this function is a list of four separate items:

USPres(27:30).vp;
ans =
    James S. Sherman
ans =
    Thomas R. Marshall
ans =
    Calvin Coolidge
ans =
    Charles Dawes

Write a program that displays the name of a selected Vice President. Use the varargin function to accept and unpack the four separate input arguments generated by the comma-separated list, USPres(27:30).vp:

function passPartialStructArray(number, varargin)

% Describe the VARARGIN input.
[dim1,dim2] = size(varargin);   typ = class(varargin);
fprintf('\nInput 2 is a %d-by-%d %s array, VARARGIN.\n', ...
    dim1, dim2, typ);

% Show the result
str = ['\nThe Vice President who served with ', ...
    'the %dth US President was %s\n'];
n = number - 26;
fprintf(str, number, varargin{n})

Call the program, passing a 4-element comma-separated list, which is internally converted to the 1-by-4 VARARGIN cell array:

passPartialStructArray(28, USPres(27:30).vp)

Input 2 is a 1-by-4 cell array, VARARGIN.

The Vice President who served with the 28th US President was 
   Thomas R. Marshall

Converting Between Struct Array and Cell Array

The struct2cell function converts a structure array to a cell array. The statement

c = struct2cell(s)

converts an m-by-n structure s that has p fields into a p-by-m-by-n cell array c:

The cell2struct function converts a cell array to a struct array. The statement

s = cell2struct(c,f,d)

converts a cell array c into a struct array s having the fields named in f and based on the d axis of the input cell array.

Conversion Example

This example converts a 1-by-2 struct array USPres_Struct with four fields to a 4-by-1-by-2 cell array USPres_Cell, and then back to a structure USPres_Struct2 that is equal to the original.

Create the original structure:

USPresStruct = struct( ...
   'name', ...
       {'Franklin D. Roosevelt', 'Harry S. Truman'}, ...
   'party', ...
       {'Democratic', 'Democratic'}, ...
   'term', ...
       {{1933, 1945}, {1945, 1953}}, ...
   'vp', ...
       {{'John Garner'; 'Henry Wallace'; 'Harry S. Truman'}, ...
        {'Alben Barkley'}});

USPresStruct(1).name = 'Franklin D. Roosevelt';
USPres_s1(1).party = 'Democratic';
USPres_s1(1).term = {1933, 1945};
USPres_s1(1).vp = ...
    {'John Garner';'Henry Wallace';'Harry S. Truman'};


USPresStruct = struct('name', 'Franklin D. Roosevelt', ...
'party', 'Democratic', 'term', {1 2 3}, 'vp', ...
{'John Garner' 'Henry Wallace' 'Harry S. Truman'})


USPres_s1(2).name = 'Harry S. Truman';
USPres_s1(2).party = 'Democratic';
USPres_s1(2).term = {1945, 1953};
USPres_s1(2).vp = 'Alben Barkley';
whos USPres_s1
  Name           Size            Bytes  Class     Attributes

  USPres_s1      1x2              1400  struct

Convert the struct array to a cell array:

USPresCell = struct2cell(USPresStruct);
whos USPresCell
  Name            Size             Bytes  Class    Attributes

  USPresCell      4x1x2             1208  cell               



USPres_c1 = struct2cell(USPres_s1);
whos USPres_c1
  Name           Size             Bytes  Class    Attributes

  USPres_c1      4x1x2             1144  cell

Convert back to a struct array and compare it with the original:

USPres_s2 = cell2struct(USPres_c1, ...
    {'name','party','term','vp'}, 1);
whos USPres_s2
  Name           Size            Bytes  Class     Attributes

  USPres_s2      1x2              1400  struct

isequal(USPresStruct, USPres_Struct2)
ans =
     1

Organizing Data in Structure Arrays

The key to organizing structure arrays is to decide how you want to access subsets of the information. This, in turn, determines how you build the array that holds the structures, and how you break up the structure fields.

For example, consider a 128-by-128 RGB image stored in three separate arrays; RED, GREEN, and BLUE.

There are at least two ways you can organize such data into a structure array: plane organization and element-by-element organization.

Plane Organization

In the plane organization, shown to the left in the figure above, each field of the structure is an entire plane of the image. You can create this structure using

A.r = RED;
A.g = GREEN;
A.b = BLUE;

This approach allows you to easily extract entire image planes for display, filtering, or other tasks that work on the entire image at once. To access the entire red plane, for example, use

redPlane = A.r;

Plane organization has the additional advantage of being extensible to multiple images in this case. If you have a number of images, you can store them as A(2), A(3), and so on, each containing an entire image.

The disadvantage of plane organization is evident when you need to access subsets of the planes. To access a subimage, for example, you need to access each field separately:

redSub = A.r(2:12,13:30);
greenSub = A.g(2:12,13:30);
blueSub = A.b(2:12,13:30);

Element-by-Element Organization

The element-by-element organization, shown to the right in the previous figure, has the advantage of allowing easy access to subsets of data. However, it has the disadvantage of being very memory-intensive. To set up the data in this organization, use

for m = 1:size(RED,1)
   for n = 1:size(RED,2)
      B(m,n).r = RED(m,n);
      B(m,n).g = GREEN(m,n);
      B(m,n).b = BLUE(m,n);
   end
end

With element-by-element organization, you can access a subset of data with a single statement:

Bsub = B(1:10,1:10);

To access an entire plane of the image using the element-by-element method, however, requires a loop:

redPlane = zeros(128, 128);
for k = 1:(128 * 128)
    redPlane(k) = B(k).r;
end

Element-by-element organization is not the best structure array choice for most image processing applications. However, it can be the best for other applications wherein you routinely need to access corresponding subsets of structure fields. The example in the following section demonstrates this type of application.

Example — A Simple Database

Consider organizing a simple database.

Each of the possible organizations has advantages depending on how you want to access the data. Typically, your data does not dictate the organization scheme you choose. Rather, you must consider how you want to access and operate on the data.

Advantages of Using Plane Organization.  Plane organization makes it easier to operate on all field values at once. If, for example, you want to find the average of all the values in the amount field,

Advantages of Using Element-By-Element Organization.  Element-by-element organization makes it easier to access all the information related to a single client. Consider a program file, client.m, which displays the name and address of a given client on screen.

Using plane organization, the client function appears as:

  function client(name,address)
  disp(name)
  disp(address)

Call this function as follows:

  client(A.name(2,:), A.address(2,:))

Using element-by-element organization, both the function and function call require less code. The client function is:

  function client(B)
  disp(B)

To call the function, use:

  client(B(2))

Element-by-element organization also makes it easier to expand the string array fields. If you do not know the maximum string length ahead of time for plane organization, you might need to frequently recreate the name or address field to accommodate longer strings.

Operator Summary

This section summarizes the following types of operators that work with structures:

Operators That Construct the Struct Array

SyntaxDescription
S = struct('f1', x, 'f2', y, 'f3', z)Builds a 1-by-1 struct array S with fields f1, f2, and f3, which can contain data of unlike types. Field f1 contains the value of x, field f2 contains the value of y, etc.
S = struct('f1', {x, y, z})Builds a 1-by-3 struct array S where each element of S has one field f1, which can contain data of unlike types. S(1).f1 contains the value of x, S(2).f1 contains the value of y, etc.

Operators That Concatenate Structures

SyntaxDescription
S3 = [S1 S2]Concatenates struct arrays S1 and S2 into a two-element struct array.
S3 = [S1.F; S2.F]Concatenates the fields of struct arrays S1 and S2 into an array of the same data type. S3 is not necessarily a struct.

Operators Used for Struct Array Indexing

SyntaxDescription
X = S(s)Returns the elements of struct array S specified by subscripts s.
X = S(s).FReturns all elements of field F for elements of S specified by s.
X = S(s).F(f)
Returns selected elements of field F for structure elements specified by subscript s.
X = S1(s1).S2(s2).FReturns the contents of a nested struct array. Multiple elements of S1 are not allowed with this syntax.
X = S(s).F{c}Returns the specified elements of a cell array that reside in a field of struct array S.

Function Summary

This section summarizes the following types of functions that work with structures:

Functions Related to Constructing the Struct Array

FunctionDescription
catConcatenate arrays along specified dimension.
horzcatConcatenate arrays horizontally.
lengthLength of vector.
ndimsNumber of array dimensions.
numelNumber of elements in array or subscripted array expression.
repmatReplicate and tile array.
reshapeReshape array.
sizeSize of array.
structCreate structure array.
vertcatConcatenate arrays vertically.

Functions Related to the Type of the Struct Array

FunctionDescription
cell2structConvert cell array to structure array.
classCreate object or return class of object.
isstructDetermine whether input is structure array.
struct2cellConvert structure to cell array.
whosList variables in workspace.

Functions Related to Struct Fields

FunctionDescription
fieldnamesGet all field names of specified structure.
getfieldGet contents of the specified field.
isemptyDetermine whether array is empty.
isfieldDetermine if input is a structure field.
orderfieldsOrder fields of a structure array.
rmfieldRemove structure field.
setfieldSet structure field contents, returning the modified structure.
Dynamic FieldnamesGenerate field name strings at run time.

Functions Related to Applying Functions to a Struct Array

FunctionDescription
structfunApply function to each field of scalar structure.
vararginVariable length input argument list.
varargoutVariable length output argument list.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2010- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS