Octave Programming Tutorial/Struct Arrays
Chapter 1: A Tutorial Introduction
Chapter 2: Basic Octave Concepts
Chapter 3: Data Storage and Manipulation
Data Types and Operations on Point Values
Arrays and Matrices
- What is an array?
- Introduction to array operations
- Vectors and basic vector operations
- Struct Arrays
- Cell Arrays
- Sparce Matrices
Chapter 4: M File Programming
- Scripts
- Comments
- The Input Function
- Control Flow
- Loops and Branches
- Error Messages
- Octave Caveats
- Debugging M Files
Chapter 5: Graphics
Chapter 6: Mathematical Manipulations
Linear Algebra
Differential Equations
Chapter 7: Examples
A structure in Octave groups different data types called fields in a single object. Fields are accessed by their names.
Declaring a structure
editA 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 value can by displayed by simply entering the name of the struct:
>> city city = { name = Liege country = Belgium longitude = 50.633 latitude = 5.5666 }
Manipulating structures
editA 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
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.