_________________________________________________________________
Vectors are common data structures for many applications. For example, a graph may use two vectors to represent the x and y coordinates of the data plotted. By using vectors, you separate data analysis from the graph widget. This makes it easier, for example, to add data transformations, such as splines. It's possible to plot the same data to in multiple graphs, where each graph presents a different view or scale of the data.
You could try to use Tcl's associative arrays as vectors. Tcl arrays are easy to use. You can access individual elements randomly by specifying the index, or the set the entire array by providing a list of index and value pairs for each element. The disadvantages of associative arrays as vectors lie in the fact they are implemented as hash tables.
# Create a new vector.
vector y(50)
This creates a new vector named y. It has fifty components, by default, initialized to 0.0. In addition, both a Tcl command and array variable, both named y, are created. You can use either the command or variable to query or modify components of the vector.
# Set the first value.
set y(0) 9.25
puts "y has [y length] components"
The array y can be used to read or set individual components of the vector. Vector components are indexed from zero. The array index must be a number less than the number of components. For example, it's an error if you try to set the 51st element of y.
# This is an error. The vector only has 50 components. set y(50) 0.02
You can also specify a range of indices using a colon (:) to separate the first and last indices of the range.
# Set the first six components of y set y(0:5) 25.2
If you don't include an index, then it will default to the first and/or last component of the vector.
# Print out all the components of y puts "y = $y(:)"
There are special non-numeric indices. The index end, specifies the last component of the vector. It's an error to use this index if the vector is empty (length is zero). The index ++end can be used to extend the vector by one component and initialize it to a specific value. You can't read from the array using this index, though.
# Extend the vector by one component. set y(++end) 0.02
The other special indices are min and max. They return the current smallest and largest components of the vector.
# Print the bounds of the vector puts "min=$y(min) max=$y(max)
To delete components from a vector, simply unset the corresponding array element. In the following example, the first component of y is deleted. All the remaining components of y will be moved down by one index as the length of the vector is reduced by one.
# Delete the first component
unset y(0)
puts "new first element is $y(0)"
The vector's Tcl command can also be used to query or set the vector.
# Create and set the components of a new vector vector x
x set { 0.02 0.04 0.06 0.08 0.10 0.12 0.14 0.16 0.18 0.20 }
Here we've created a vector x without a initial length specification. In this case, the length is zero. The set operation resets the vector, extending it and setting values for each new component.
There are several operations for vectors. The range operation lists the components of a vector between two indices.
# List the components
puts "x = [x range 0 end]"
You can search for a particular value using the search operation. It returns a list of indices of the components with the same value. If no component has the same value, it returns "".
# Find the index of the biggest component set indices [x search $x(max)]
Other operations copy, append, or sort vectors. You can append vectors or new values onto an existing vector with the append operation.
# Append assorted vectors and values to x x append x2 x3 { 2.3 4.5 } x4
The sort operation sorts the vector. If any additional vectors are specified, they are rearranged in the same order as the vector. For example, you could use it to sort data points represented by x and y vectors.
# Sort the data points
x sort y
The vector x is sorted while the components of y are rearranged so that the original x,y coordinate pairs are retained.
There also are operations to perform arithmetic. They second operand can be either another vector or a scalar value.
# Add the two vectors and a scalar puts "x+y=[x + y]"
puts "x*2=[x * 2]"
When a vector is modified, resized, or deleted, it may trigger call-backs to notify the clients of the vector. For example, when a vector used in the graph widget is updated, the vector automatically notifies the widget that it has changed. The graph can then redrawn itself at the next idle point. By default, the notification occurs when Tk is next idle. This way you can modify the vector many times without incurring the penalty of the graph redrawing itself for each change. You can change this behavior using the notify operation.
# Make vector x notify after every change x notify always
...
# Never notify
x notify never
...
# Force notification now
x notify now
To delete a vector, simply unset its variable or delete its command. When the variable is unset, both the vector and its corresponding Tcl command are destroyed.
# Remove vector x
unset x
If the array variable isn't global (i.e. local to a Tcl procedure), the vector is automatically destroyed when the procedure returns.
proc doit {} {
# Temporary vector x
vector x(10)
set x(9) 2.0
...
}
When doit returns, the vector x is automatically removed as the variable is unset. To prevent this, simply make the variable x global before the vector is created, using the global command.
proc doit {} {
global x
# Permanent vector x
vector x(10)
set x(9) 2.0
...
}
The vector command creates a new vector vecName. Both a Tcl command and array variable vecName are also created. The name vecName must be unique, so another Tcl command or array variable can not already exist in that scope. You can access the components of the vector using its variable. If you change a value in the array, or unset an array element, the vector is updated to reflect the changes. When the variable vecName is unset, the vector and its Tcl command are also destroyed.
A vector can be specified in one of three forms:
vector vecName
This creates a new vector vecName which initially has no components.
vector vecName(size)
This second form creates a new vector which will contain size number of components. The components will be indexed starting from zero (0). The default value for the components is 0.0.
vector vecName(first:last)
The last form creates a new vector of indexed first through last. First and last can be any integer value so long as first is less than last.
Vectors can be indexed by integers. The index must lie within the range of the vector, otherwise an an error message is returned. Typically the indices of a vector are numbers from zero. But you can use the offset operation to change the indices, on the fly, for a vector.
puts $vecName(0)
vecName offset -5
puts $vecName(-5)
Vectors can also be indexed by numeric expressions. The result of the expression must be an integer.
set n 21
set vecName($n+3) 50.2
There are special non-numeric indices; min, max, end, and ++end.
puts "min = $vecName($min)"
set vecName(end) -1.2
The indices min and max will return the minimum and maximum values of the vector. The index end returns the value of the last component in the vector. The index ++end is for appending new components onto the vector. It automatically extends the vector by one component and sets its value.
# Append an new component to the end set vecName(++end) 3.2
A range of indices can be indicated by a colon (:).
# Set the first six components to 1.0 set vecName(0:5) 1.0
If no index is supplied the first or last component is assumed.
# Print the values of all the components puts $vecName(:)
vecName operation ?arg?...
Both operation and its arguments determine the exact behavior of the command. The operations available for vectors are listed below.
vecName append item ?item?...
Appends the component values from item to vecName. Item can be either the name of a vector or a list of numeric values.
vecName clear
Clears the element indices from the array variable associated with vecName. This doesn't affect the components of the vector. By default, the number of entries in the Tcl array doesn't match the number of components in the vector. This is because its too expensive to maintain decimal strings for both the index and value for each component. Instead, the index and value are saved only when you read or write an element with a new index. This command removes the index and value strings from the array. This is useful when the vector is large.
vecName delete index ?index?...
Deletes the indexth component from the vector vecName. Index is the index of the element to be deleted. This is the same as unsetting the array variable element index. The vector is compacted after all the indices have been deleted.
vecName dup destName
Copies vecName to destName. DestName is the name of a destination vector. If a vector destName already exists, it is overwritten with the components of vecName. Otherwise a new vector is created.
vecName length ?newSize?
Queries or resets the number of components in vecName. NewSize is a number specifying the new size of the vector. If newSize is smaller than the current size of vecName, vecName is truncated. If newSize is greater, the vector is extended and the new components are initialized to 0.0. If no newSize argument is present, the current length of the vector is returned.
vecName merge srcName ?srcName?...
Returns a list of the merged vector components.
The list is formed by merging the components of each vector at each index.
vecName notify keyword
Controls how vector clients are notified of changes to the vector. The exact behavior is determined by keyword.
always Indicates that clients are to be notified immediately whenever the vector is updated.
never Indicates that no clients are to be notified.
whenidle
Indicates that clients are to be notified at the next idle point whenever the vector is updated.
pending
Returns 1 if a client notification is pending, and 0 otherwise.
vecName offset ?value?
Shifts the indices of the vector by the amount specified by value. Value is an integer number. If no value argument is given, the current offset is returned.
vecName populate destName ?density?
Creates a vector destName which is a superset of vecName. DestName will include all the components of vecName, in addition the interval between each of the original components will contain a density number of new components, whose values are evenly distributed between the original components values. This is useful for generating abscissas to be interpolated along a spline.
vecName range firstIndex ?lastIndex?...
Returns a list of numeric values representing the vector components between two indices. Both firstIndex and lastIndex are indices representing the range of components to be returned. If lastIndex is less than firstIndex, the components are listed in reverse order.
vecName search value ?value?
Searches for a value or range of values among the components of vecName. If one value argument is given, a list of indices of the components which equal value is returned. If a second value is also provided, then the indices of all components which lie within the range of the two values are returned. If no components are found, then "" is returned.
vecName set item
Resets the components of the vector to item. Item can be either a list of numeric expressions or another vector.
vecName sort ?-reverse? ?argName?...
Sorts the vector vecName in increasing order. If the -reverse flag is present, the vector is sorted in decreasing order. If other arguments argName are present, they are the names of vectors which will be rearranged in the same manner as vecName. Each vector must be the same length as vecName. You could use this to sort the x vector of a graph, while still retaining the same x,y coordinate pairs in a y vector.
vecName * item
Returns a list representing the product of vecName and item. If item is the name of a vector, vector multiplication is performed. The vectors must be the same length. Otherwise, item must be a scalar value and each component of vecName is multiplied by that value. The component values of vecName do not change.
vecName + item
Returns a list representing the sum of vecName and item. If item is the name of a vector, vector addition is performed. The vectors must be the same length. Otherwise, item must be a scalar value and each component of vecName is added by that value. The component values of vecName do not change.
vecName - item
Returns a list representing the subtraction of item from vecName. If item is the name of a vector, vector subtraction is performed. The vectors must be the same length. Otherwise, item must be a scalar value and the list will contain each component of vecName is subtracted by that value. The component values of vecName do not change.
vecName / item
Returns a list representing the product of vecName and item. If item is the name of a vector, vector division is performed. The vectors must be the same length. Otherwise, item must be a scalar value and each component of vecName is divided by that value. The component values of vecName do not change.
typedef struct {
double *valueArr;
int numValues;
int arraySize;
double min, max;
} Blt_Vector;
The field valueArr points to memory holding the vector components. The components are stored in a double precision array, whose size size is represented by arraySize. NumValues is the length of vector. The size of the array is always equal to or larger than the length of the vector. Min and max are minimum and maximum component values.
Blt_CreateVector
Synopsis:
int Blt_CreateVector (interp, vecName, length) Tcl_Interp *interp;
char *vecName;
int length;
Description:
Creates a new vector vecName with a length of length. Blt_CreateVector creates both a new Tcl command and array variable vecName. Neither a command nor variable named vecName can already exist.
Results: Returns TCL_OK if the vector is successfully created. If length is negative, a Tcl variable or command vecName already exists, or memory cannot be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message.
Blt_DeleteVector
Synopsis:
int Blt_DeleteVector (interp, vecName) Tcl_Interp *interp;
char *vecName;
Description:
Removes the vector vecName. VecName is the name of a vector which must already exist. Both the Tcl command and array variable vecName are destroyed. All clients of the vector will be notified immediately that the vector has been destroyed.
Results: Returns TCL_OK if the vector is successfully deleted. If vecName is not the name a vector, then TCL_ERROR is returned and interp->result will contain an error message.
Blt_GetVector
Synopsis:
int Blt_GetVector (interp, vecName, vecPtr) Tcl_Interp *interp;
char *vecName;
Blt_Vector *vecPtr;
Description:
Retrieves the vector vecName. The fields of the structure vecPtr are filled with the current values from the vector. VecName is the name of a vector which must already exist.
Results: Returns TCL_OK if the vector is successfully retrieved. If vecName is not the name of a vector, then TCL_ERROR is returned and interp->result will contain an error message.
Blt_ResetVector
Synopsis:
int Blt_ResetVector (interp, vecName, vecPtr, freeProc) Tcl_Interp *interp;
char *vecName;
Blt_Vector *vecPtr;
Tcl_FreeProc *freeProc;
Description:
Resets the components of the vector vecName. The fields of the vecPtr contain the updated values. Calling Blt_ResetVector will trigger the vector to dispatch notifications. VecName is the name of a vector which must already exist. FreeProc indicates how the storage for the vector component array (valueArr) was allocated. It is used to determine how to reallocate memory when the vector is resized or destroyed. It must be TCL_DYNAMIC, TCL_STATIC, TCL_VOLATILE, or a pointer to a function to free the memory allocated for the vector array. If freeProc is TCL_VOLATILE, it indicates that valueArr must be copied and saved. If freeProc is TCL_DYNAMIC, it indicates that valueArr was dynamically allocated and that Tcl should free valueArr if necessary. Static indicates that nothing should be done to release storage for valueArr.
Results: Returns TCL_OK if the vector is successfully resized. If newSize is negative, a vector vecName does not exist, or memory cannot be allocated for the vector, then TCL_ERROR is returned and interp->result will contain an error message.
Blt_ResizeVector
Synopsis:
int Blt_ResizeVector (interp, vecName, newSize) Tcl_Interp *interp;
char *vecName;
int newSize;
Description:
Resets the length of the vector vecName to newSize. If newSize is smaller than the current size of vecName, vecName is truncated. If newSize is greater, the vector is extended and the new components are initialized to 0.0. VecName is the name of a vector which must already exist. Calling Blt_ResetVector will trigger the vector to dispatch notifications.
Results: Returns TCL_OK if the vector is successfully resized. If newSize is negative, a vector vecName does not exist, or memory can not be allocated for the vector. then TCL_ERROR is returned and interp->result will contain an error message.
Blt_VectorExists
Synopsis:
int Blt_VectorExists (interp, vecName) Tcl_Interp *interp;
char *vecName;
Description:
Indicates if a vector named vecName exists in interp.
Results: Returns 1 if a vector vecName exists and 0 otherwise.
If your application needs to be notified when a vector changes, it can allocate a unique client identifier for itself. Using this identifier, you can then register a call-back to be made whenever the vector is updated or destroyed. By default, the call-backs are made at the next idle point. This can be changed to occur at the time the vector is modified. An application can allocate more than one identifier for any vector. When the client application is done with the vector, it should free the identifier.
The call-back routine must of the following type.
typedef void (Blt_VectorChangedProc) (Tcl_Interp *interp, ClientData clientData, Blt_VectorNotify notify);
ClientData is passed to this routine whenever it is called. You can use this to pass information to the call-back. The notify argument indicates whether the vector has been updated of destroyed. It is an enumerated type.
typedef enum {
BLT_VECTOR_NOTIFY_UPDATE=1,
BLT_VECTOR_NOTIFY_DESTROY=2
} Blt_VectorNotify;
Blt_AllocVectorId
Synopsis:
Blt_VectorId Blt_AllocVectorId (interp, vecName) Tcl_Interp *interp;
char *vecName;
Description:
Allocates an client identifier for with the vector vecName. This identifier can be used to specify a call-back which is triggered when the vector is updated or destroyed.
Results: Returns a client identifier if successful. If vecName is not the name of a vector, then NULL is returned and interp->result will contain an error message.
Blt_SetVectorChangedProc
Synopsis:
void Blt_SetVectorChangedProc (clientId, proc, clientData); Blt_VectorId clientId;
Blt_VectorChangedProc *proc; ClientData *clientData;
Description:
Specifies a call-back routine to be called whenever the vector associated with clientId is updated or deleted. Proc is a pointer to call-back routine and must be of the type Blt_VectorChangedProc. ClientData is a one-word value to be passed to the routine when it is invoked. If proc is NULL, then the client is not notified.
Results: The designated call-back procedure will be invoked when the vector is updated or destroyed.
Blt_FreeVectorId
Synopsis:
void Blt_FreeVectorId (clientId); Blt_VectorId clientId;
Description:
Frees the client identifier. Memory allocated for the identifier is released. The client will no longer be notified when the vector is modified.
Results: The designated call-back procedure will be no longer be invoked when the vector is updated or destroyed.
Blt_NameOfVectorId
Synopsis:
char *Blt_NameOfVectorId (clientId); Blt_VectorId clientId;
Description:
Retrieves the name of the vector associated with the client identifier clientId.
Results: Returns the name of the vector associated with clientId. If clientId is not an identifier or the vector has been destroyed, NULL is returned.
Blt_Vector vecInfo;
/* Create new vector "x" of 50 elements */ if (Blt_CreateVector(interp, "x", 50) != TCL_OK) { return TCL_ERROR;
}
/* Get the vector */
if (Blt_GetVector(interp, "x", &vecInfo) != TCL_OK) { return TCL_ERROR;
}
/* Print the min and max component values */ printf("min=%g max=%g\n", vecInfo.min, vecInfo.max);
/* Allocate new storage for the vector */ newArr = (double *)malloc(sizeof(double) * 10000); ...
vecInfo.numValues = 10000;
vecInfo.valueArr = newArr;
/* Reset the vector. Clients get notified */ if (Blt_ResetVector(interp, "x", &vecInfo, TCL_DYNAMIC) != TCL_OK) { return TCL_ERROR;
}