Jump to content

MATLAB Programming/Advanced Topics/Object Oriented Programming/Struct arrays

From Wikibooks, open books for an open world



A struct as defined and used in Octave

[edit | edit source]

A structure in Octave groups different data types called fields in a single object. Fields are accessed by their names.

Declaring a structure

[edit | edit source]

A structure is declared by assigning values to its fields. A period (.) separates the name of the field and the name of the structure:

 >> city.name = 'Liege';
 >> city.country = 'Belgium';
 >> city.longitude = 50.6333;
 >> city.latitude = 5.5666;

The fields of a structure and their values can be displayed by simply entering the name of the struct:

>> city
city =
{
  name = Liege
  country = Belgium
  longitude =  50.633
  latitude =  5.5666
}

Manipulating structures

[edit | edit source]

A structure can be copied as any objects:

 >> city_copy = city;

In most circumstance, the fields of a structure can be manipulated with the period operator. The value of a field can be overwritten by:

 >> city.name = 'Outremeuse';

In the same way, the value of a field can be retrieved by:

 >> city.name
 ans = Outremeuse

The function isstruct can be used to test if object is a structure or not. With the function fieldnames all field names are returned as a cell array:

>> fieldnames(city)
ans =
{
  [1,1] = name
  [2,1] = country
  [3,1] = longitude
  [4,1] = latitude
}

To test if a structure contains the a given field named, the function isfield can be used:

>> isfield(city,'name')
ans =  1

The value of a field can be extract with getfield:

 >> getfield(city,'name')
 ans = Liege

or using

>> city.('name')
ans = Liege

In a similar way, the value of a field can be set with setfield:

 >> setfield(city,'name','Outremeuse')

The functions isfield, getfield and setfield are useful when the names of a structure are determined during execution of the program.

You can remove a field of a struct array with the rmfield function.

 >> city = rmfield(city, 'name');

would remove the 'name' field from the city struct and copy the result back onto the original structure.