Structure

From VLECK
Jump to: navigation, search

An NSM structure is an object consisting of an ordered collection of objects known as its elements. There is no particular need for the components to be of the same mode or type, and, for example, a structure could consist of a numeric vector, a logical value, a matrix, a complex vector, a character array, a function, and so on. Here is a simple example of how to make a structure:

Lst = {name="Fred"; wife="Mary"; no_children=3; child_ages=(4,7,9)}

Elements are always numbered and may always be referred to as such. Thus if Lst is the name of a structure with four components, these may be individually referred to as Lst[1], Lst[2], Lst[3] and Lst[4]. If, further, Lst[4] is a vector subscripted array then Lst[4][1] is its frst entry.

If Lst is a structure, then the function DimStructure(Lst) gives the number of (top level) components it has.

Components of structures may also be named, and in this case the component may be referred to either by giving the component name as a character string in place of the number in square brackets, or, more conveniently, by giving an expression of the form

 name:component_name

for the same thing. This is a very useful convention as it makes it easier to get the right component if you forget the number. So in the simple example given above:

Lst:name is the same as Lst[1] and is the string "Fred", Lst:wife is the same as Lst[2] and is the string "Mary", Lst:child.ages[1] is the same as Lst[4][1] and is the number 4.

Additionally, one can also use the names of the structure components in square brackets, i.e., Lst["name"] is the same as Lst:name. This is especially useful, when the name of the component to be extracted is stored in another variable as in

x = "name"; 
Lst[x];

The vector of names (Lst[1#4]) is in fact simply an attribute of the structure like any other and may be handled as such. Other structures besides structures may, of course, similarly be given a names attribute also.

Constructing and modifying structures

New structures may be formed from existing objects by the function structure(). An assignment of the form>

Lst = structure(name_1=object_1, ..., name_m=object_m)

or

Lst = {name_1=object_1, ..., name_m=object_m}

sets up a structure Lst of m components using object 1, . . . , object m for the components and giving them names as specifed by the argument names, (which can be freely chosen). If these names are omitted, the components are numbered only. The components used to form the structure are copied when forming the new structure and the originals are not afected. Structures, like any subscripted object, can be extended by specifying additional components. For example

Lst = AppendStructure(Lst; matrix=Mat)

See also