Script Example: Manipulating a Matrix

A very common application of the Script element is to construct and/or manipulate arrays.  This is typically facilitated by using one of the Script element’s looping constructs to assign values to rows, columns and/or individual items. The simple example described here illustrates how the Script element can be used to carry out array operations such as these. It can be found in a file (Script.gsm) that is located in the General Examples folder of your GoldSim directory (accessed by selecting File | Open Example... from the main menu).

The example starts with an input matrix.  In the input matrix, each column represents a variable, and each row represents an observation of the variable.  The script computes the correlations among the various columns (variables) of the matrix, producing a symmetric correlation matrix (rows and columns both indexed by variable). The correlation coefficient, Cxy, between two columns of data (i.e., the correlation between two variables) is given by the following equation:

In this equation, x and y are the variables. xi and yi are the ith observations of variable x and y, respectively.  mx and my are the means of the observations for those variables (i.e., the means of all values in a particular column). sx and sy are the standard deviations for those observations. n is the number of observations (i.e., the number of rows).

The script used for this simple example is shown below:

At the top of the script (lines 2 and 4), Variable Definition statements (with expressions as the assignments) compute the means and standard deviations of each column.

The calculation of the correlation coefficient for each column pair is then carried out using two Variable Assignment statements.  The first (line 11) is in the middle of three nested DO loops.  The second (line 14) is at the bottom of the second nested loop.

Related Topics…

Learn more about: