Tutorial: Arrays/es

This page is a translated version of the page Tutorial: Arrays and the translation is 24% complete.



Release:

4.6  •  5.0  •  5.1  •  5.2

Esta sección (página) le introduce a Intelligent Arrays, que es un fuente de gran parte de la potencia y flexibilidad de Analytica. Un array es una tabla de valores, con una, dos o más dimensiones. Incluso si a menudo omite los tutoriales, puede que le resulte útil repasar esta sección, ya que los arreglos de Analytica tienen algunos aspectos únicos diferentes de otras herramientas de modelado y lenguajes de computadora. Y es esencial comprender los conceptos básicos de arrays antes de poder usar Analytica de manera efectiva.


Este capítulo le muestra cómo:

  • Crear y definir un index
  • Definir una variable de tipo array como una tabla
  • Comprender los principios de la abstracción de arrays al combinar arrays en una expresión
  • Use expresiones condicionales y valores lógicos al definir una array
  • Definir variables utilizando la sintaxis de expresión.
  • Usa valores locales para simplificar una expresión.
  • Analizar un resultado multidimensional mediante indexes pivotantes.
  • Reducir un array utilizando subscripts (subíndices).
  • Utilice funciones de reducción de arrays como Sum () y NPV ()

En el capítulo anterior, definió una sola variable, Millas por galón, como una lista de valores. Este es un ejemplo de un array unidimensional simple. Cuando definió Costo de combustible usando la variable de array Millas por galón como un input, también se convirtió en un array. Esto demuestra el concepto de abstracción de array. Las variables de array se pueden usar como variables ordinarias en expresiones. ¡Cuando extiende un index del array para incluir más valores, o incluso añadir un index completamente nuevo a lo largo de una nueva dimensión, todas las variables dependientes en sentido descendente se extenderán automáticamente! Arrays inteligentes le permite escalar su modelo sin realizar cambios en el diseño.

Esta sección cubre mucho terreno. El modelo de ejemplo es simple, pero demuestra muchos conceptos importantes de arrays. El enfoque se simplifica para que pueda aprender las ideas clave sin tener que atascarse con detalles de procedimientos. Ya debe estar familiarizado con los mecanismos básicos de la interfaz de usuario de Analytica y saber cómo:

Resumir variables usando la sintaxis de expresión

Deberá saber cómo ingresar definiciones directamente como Expresiones. Cada tipo de variable y cada expresión funcional se pueden representar de esta manera. Además de su utilidad para construir modelos, la sintaxis de expresión es una forma conveniente y eficiente de resumir ejemplos en la documentación. Por ejemplo, esto resume el modelo Car cost (Costo del automóvil) de la sección anterior:

Variable MPA := 12K
Variable MPG := Sequence(20, 50, 5)
Variable Precio_de_gas := 3
Variable Costo_de_gas := MPA*Pricio_de_gas/MPG

Resumimos nuevas variables de esta forma en esta sección. También es ampliamente utilizado en todo el Wiki:

  • El primer término indica la Clase del objeto que se está definiendo. Las clases incluyen Decisión, Variable, Chance, Objetivo, Módulo, Index, Constante y Función.
  • El segundo término es el Identifier para el objeto. (Los identificadores no pueden contener espacios).
  • : = a veces conocido como operador de asignación.
  • La definición es una expresión, que podría ser un número, una llamada de función, una distribución de probabilidad, una tabla u otra expresión. Puede referirse a otras variables (las "Entradas" de esta variable). Incluso podría copiar la expresión directamente en la Definición de una variable o función. Las expresiones están marcadas como <code> < / codigo>.

Las ruedas genéricas rápidas de Tony

En este capítulo, usted extiende el modelo Car cost (Costo del automóvil) para abordar un escenario de decisión importante: la compra de un automóvil nuevo. Hay tres autos para elegir: Estándar, SUV y Hybrid.

También hay tres opciones de financiamiento: Compra en efectivo, Arrendamiento o Préstamo. Fast Tony le ha presentado una variedad de posibilidades de decisión, un array de 3 x 3 para ser exactos. Su objetivo es determinar la opción con el flujo de efectivo total más bajo en un período de 24 meses, incluido el combustible. (Los costos de mantenimiento están cubiertos por la garantía, siempre y cuando el primo de Fast Tony, Greasy Tony, esté de pie ese día). El patrimonio de propiedad se representará como un flujo de caja positivo en el último período.

Continuar con el modelo

En este capítulo, continuará con el modelo que desarrolló en Tutorial: Crear un modelo. El modelo del final de Tutorial: Crear un modelo se puede encontrar en el directorio Modelos de tutoriales. Seleccione Abrir en el menú Archivo.


Chapter 5.1-updated.png


1. Toca el botón Example Models.


2. Entra la carpeta Tutorial Models.


3. Abre el modelo from end of Chapter 4.

Crear una variable de index

Las variables de tipo index (índice) definen las categorías a lo largo de una dimensión de un array. Están representados por nodos de index (formas de paralelogramo) en el diagrama de influencia. En este ejemplo, su decisión será organizada por Tipo de automóvil y Opción de financiamiento, por lo que deberá definir un index para cada una de estas dimensiones. Las variables de index generalmente se definen como una "lista de texto" o una "lista de valores" que representan categorías en el array.

(Para las opciones de financiamiento, dejará de lado "Préstamo" por ahora. Se añadirá más tarde.)

<code>Index Tipo_de_auto := ['Estándar', 'SUV', 'Híbrida']
Index Opcion_de_fondos := ['Comprar', 'Arriendo']


TutChap5CreateIndexes.png


Para cada uno de los nodos de indexes listados arriba, haga lo siguiente:
1. Elije el Edit tool
2. Arrastra el ícono de index hacia abajo al diagrama
3. Entra un título para el nodo
4. Abre el campo Definition y elije List of text en el menú emergente de expresión
5. Entra etiquetas como así
Tip
Como alternativo a elijir List of Text en the Expression popup menu, se puede eligir Expression y entrar la definición directamente usando Sintaxis de expresiones. Simplemente enumere los valores separados por comas y enciérrelos entre corchetes [ ]. Tenga en cuenta que todos los valores de texto en la sintaxis de expresión deben incluirse entre comillas (soltera o doble).

Defining a variable as a table

Each of the cars has a unique purchase price. You will define Car price as a Table indexed by Car type. In this context, a "table" does not necessarily have two dimensions. It can have one (as in this case), two, three or more.

Variable Precio_del_auto  := Table(Tipo_de_auto)(22K, 40K, 24K)


Chapter 5.3-updated.png


1. Create a new variable titled Car price.
2. Open the Definition field, then open the Expression popup menu. Select Table.
3. The Indexes dialog appears. Select the Car type index and click the transfer button to move it to the selected indexes list. Click OK.

After you close the Indexes dialog an Edit table will appear.

Enter the following values for Car price:

Standard: '22K'
SUV: 40K'
Hybrid: '24K'


Chapter 5.4-updated.png


Click the index button if you want to go back to the Indexes dialog.
Index categories appear as table headings.
Press Tab or Shift+Tab to move through the cells.
Tip

You can draw influence arrows from index nodes to table variables to pre-populate the Indexes dialog with the chosen indexes. Influence arrows from index nodes are invisible by default but can be made visible by choosing the Diagram menu and selecting Set diagram style.

Next you will create a variable for lease payments. Fast Tony lists the following monthly payments for the two-year lease option:

Standard: '$400'
SUV: $700'
Hybrid: '$500'

Lease Payment is similar to the Car price variable. But this time you will enter the definition directly using expression syntax instead of using the edit table.

Variable Lease_payment := Table(Car_type)(400, 700, 500)


Chapter 5.5-updated.png


4. Create a new variable titled Lease payment
5. Open the definition field and select ExprExpression menu item.png from the Expression popup menu. (This will not change the definition of an existing variable.)
6. Enter the definition directly as shown

As you can see, Table definitions follow a specific syntax. The Table declaration is followed by two lists enclosed in parentheses. The first list contains the indexes by which the table will be arrayed. (In this simple example there is only one index but there can be many.) The second list contains the values.

It is important for the values to be in the same order as the index categories. Recall that the Car type index was defined as:

Index Car_type := ['Standard', 'SUV', 'Hybrid']

which matches the respective order of values in the Lease payment variable. The same principle applies when there is more than one index. For example, a two dimensional array might look like:

Table (Index_abc, Index_123)
('a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3')

It is generally easier to use an edit table when multiple dimensions are involved.

Finally, re-define the existing Miles per gallon variable as a table indexed by Car type. The MPG values for Standard, SUV and Hybrid are 28, 23, and 45 respectively.

Variable Mpg := Table(Car_type)(28, 23, 45)

Select the Miles per gallon variable.

Open the Definition field and select Chapter 5.6-updated.png from the Expression popup menu. Enter the new definition as shown above.

Combinar arrays

Ahora que ha establecido los pagos de compra y arrendamiento, puede combinarlos en una variable. Esta vez el index será 'Opción Financiera' .

Variable Payments := Table (Finance_option)(Car_price, Lease_payment)

Cree una nueva variable titulada 'Pagos' .

Abra el campo de definición y seleccione Table en el menú emergente Expresión.

Aparece el Indexes dialog. Seleccione el index de opción de Finanzas y transfiéralo a la lista de índices seleccionados. Haga clic en OK. Aparecerá una tabla de editar (Edit table).


Chapter 5.7-updated.png


1. Ingrese Car_price junto a Purchase
2. Ingrese Lease_payment junto a Lease
3. Toca GreenCheck.png

Es posible que haya notado una diferencia importante entre esta tabla y las tablas anteriores. En las tablas anteriores, ingresó valores numéricos en las celdas de la tabla, ¡pero esta vez está ingresando expresiones! Las expresiones son entradas válidas para celdas de tabla. Con muy pocas excepciones, pueden ser tan complejas como cualquier cosa que pueda ingresar en una línea de definición estándar, incluidas fórmulas, expresiones lógicas y expresiones condicionales. Verás más ejemplos de esto más adelante en el capítulo.

Ahora mira el resultado de esta nueva variable.

Seleccione la variable 'Payments' (pagos) y haga clic en el botón 'Results' (Resultados)

¡Algo interesante ha sucedido! Observe que el array contiene dos dimensiones, aunque solo se menciona un index en la definición de la array:

Variable Payments := Table (Finance_option)(Car_price, Lease_payment)

¿Por qué se incluye 'Tipo de auto' en el resultado cuando 'Finance_option' es el único index incluido en la definición de la tabla?

El index 'Tipo de automóvil' se incluye porque es un index de las variables de entrada 'Precio del automóvil' y 'Pago de arrendamiento' .

Acaba de encontrar una de las características más poderosas de la abstracción de arrays en Analytica: las dimensiones de las variables de entrada de array se incorporarán automáticamente en la salida resultante de una expresión. El principio general de la abstracción de arrays se puede resumir de la siguiente manera:

En Analytica, el resultado de una expresión está ordenado por el conjunto de dimensiones' 'unión' 'de todas las variables de entrada y la definición de la expresión en sí misma.

Añadir una dimensión a una matriz

Hasta ahora, la variable Pagos no es muy útil para comparar las opciones de compra y arrendamiento. Los pagos de arrendamiento se pagan todos los meses en lugar de solo una vez, y aún hay capital de propiedad que se debe considerar. Para representar los pagos como una corriente de flujos de efectivo a lo largo del tiempo, deberá agregar una nueva dimensión a la array de Pagos:

Crea y define un nuevo índice titulado Período. Definirlo como una secuencia de meses de 0 a 24.

Index Periodo := Sequence(0, 24)

Hay una sintaxis de atajo especial para las secuencias que tienen un valor de paso de uno: Escriba el valor de inicio, seguido de dos puntos (..), seguido del valor final. Por ejemplo, el index 'Periodo' se puede definir como: Index Periodo: = 0..24

A continuación, editará la definición de Pagos para incluir el nuevo index. Trate de usar la tabla de edición para esto:


Chapter 5.8-updated.png


1. Seleccione la variable Pagos y abra el campo de definición (Definition).
2. Haga un clic en el botón Edit Table.

Hay un botón en la esquina superior izquierda de la tabla de edit, etiquetado con un paralelogramo. Haga clic en este botón para abrir la ventana de indexes. Luego añadir Período a la lista de indexes seleccionados.


Chapter 5.9-updated.png


3. Haga clic en el Botón de index en la esquina superior izquierda de la tabla de edit.
4. Seleccione el index Período y añadirlo a la lista de indexes seleccionados.
Nota: de forma predeterminada, Analytica copiará los valores actuales en todos los nuevos segmentos a lo largo del index adicional.


La tabla de edit ahora debería verse así:


Chapter 5.10-updated.png


El index Período se ha agregado a la array Pagos.
5. Cambie los indexes verticales y horizontales si es necesario para girar la tabla como se muestra.

El subconjunto de una array que corresponde a un valor de index único se denomina slice. Cuando expandió la array de Pagos para incluir un nuevo index, los valores originales (expresiones en este caso) se copiaron en todos los nuevos segmentos a lo largo del index Periodo.

La array de Pagos todavía no es precisa. Debajo de la columna Compra, debe tener valores cero para todos los periodos, excepto el Período 0. Los pagos de arrendamiento deben incluirse en los periodos 1 al 24, pero no en el Período 0. No le costará demasiado esfuerzo editar todas las celdas para que sean de la forma que desea. ser. La definición final de la array sería algo así:

Chapter 5.11-updated.png

Aunque esto funcionaría, no sería un enfoque muy eficiente. En general, siempre que se encuentre editando tablas de la misma manera que editaría una hoja de cálculo, no se beneficiará de las ventajas de la abstracción de arrays.

Usar expresiones condicionales

Las expresiones pueden incluir sentencias condicionales usando la sintaxis If ... then ... else. La condición puede basarse en una variable o un valor de index. Esta es una forma muy útil de definir variables de array. Por ejemplo, el flujo de caja para los compradores se puede representar como:

If Periodo = 0 Then Pricio_del_auto Else 0

Del mismo modo, el flujo de efectivo de los arrendatarios puede representarse como:

If Periodo = 0 Then 0 Else pago_de_arriendo

Specifying a condition based on Period will automatically add the Period index to the array. This would have been a better way to add a new dimension to the Payments variable, compared to the example above.

Let’s revert the Payments variable to the way it was before adding the Period index:

Variable Payments := Table(Finance_option)(Car_price, Lease_payment)

As you did in the section above, Select the Payments variable, open the edit table, and click the Index button in the top left corner.

Select the Period index in the Selected Indexes list and transfer it back to left hand box. Click OK. Answer Yes when the warning appears:

Chapter 5.12-updated.png


Chapter 5.7-updated.png


The edit table should be back to its original one-dimensional form.

This time you will add the Period index by including it in a conditional expression. Edit the cells to include conditional expressions:

Variable Payments := Table(Finance_option)
(If Period = 0 Then Car_price Else 0,
 If Period = 0 Then 0 Else Lease_payment)


Chapter 5.14-updated.png


Enter conditional expressions in the edit table cells as shown.

Let’s take a step back to consider how many indexes are now included in the Payments array:

  • Finance_option is called out specifically as a table index
  • Period is the basis for a condition statement within an expression
  • Car_type is an index of the Car price and Lease payment input variables. Therefore, you can expect that Payments will be a three-dimensional array.

Conditional expressions can have nested If-Then-Else statements. In fact, it would be possible to define the Payments array using only one conditional expression:

Variable Payments :=
If Finance_Option = 'Purchase' Then
    If Period = 0 Then Car_price Else 0
Else If Period = 0 Then 0
Else Lease_payment

This would be equivalent to the table definition above.

Logical statements can also be used to specify a condition. They are enclosed in parentheses and include an equal sign. When used in a mathematical expression, a logical statement assumes a value of one if true, or zero if false. For example:

24*(2 + 2 = 4) → 24
24*(2 + 2 = 5) → 0

Hence another equivalent to the previous table definition is

If Finance_Option = 'Purchase' Then (Period=0) * Car_price
Else (Period>0) * Lease_payment

View the results of a multi-dimensional array

Representing a multi-dimensional array on a two-dimensional screen presents a challenge. When viewing results in tabular form, Analytica will display only a two-dimensional slice of the data. You can change the orientation and selection of data by pivoting the table. To do this, select the desired row and column indexes from the row and column pop-up menus. Any leftover indexes become slicer indexes for which only slice of data (corresponding to a single index value) can be displayed at a time.

Select the Payments variable and click the Results button (Chapter 4.54-updated.png).

Select the table view button (Chapter 4.58-updated.png).

You can experiment by selecting different row and column indexes, and by changing the value of the slicer index.


Chapter 5.15-updated.png
The slicer menu button displays a pop-up menu of all slicer index values.
Slicer steppers change the value of the slicer index sequentially.


The row index pop-up menu selects the index of rows.
The column index pop-up selects the index of columns.

Now click on the graph view button (Chapter 4.56-updated.png)

The vertical axis of the graph represents data values. The graph indexes can be pivoted to select the desired horizontal axis, key, and slicer index. You can experiment with various graph configurations and slicer values.


Chapter 5.16-updated.png


The graph displays data for only one value of the slicer index.
The Horizontal Axis pop-up menu selects the index for the horizontal axis.
Key index categories are divided by color.
Tip

You can explore various chart types and options by selecting Graph Setup... from the Result menu. For more details about graphs reference Tutorial: Reviewing a model.

Add a new value to an index

Fast Tony’s loan financing terms require 10% down and 2% of the purchase price per month for 60 months. His financing manager, Big Anthony, explains that at a 12% nominal interest rate (1% per month compounded monthly), the load will be paid off in 60 months. There are severe penal- ties for delinquency but none of them are expressed in dollar values.

One of the advantages of intelligent arrays is that they are easily expandable. So far, you have set up cash flows for purchasers and lease holders. Adding a third financing option is a simple matter of adding a new value to the Finance option index.

Index Finance_option := ['Purchase','Lease','Loan']

Select the Finance option index and open the Definition field. Select List of Textfrom the Expression popup menu. You will see a list of current values in the definition field. Select the bottom value (Lease) and press the down-arrow key. A new box appears at the bottom of the list. By default the previous label is copied down. Change the new value to Loan.




Chapter 5.17-updated.png


1. Select List of Text from the Expression pop-up menu.
2. Select the bottom category and press Enter.
3. Enter Loan as the new value.

Now select the Payments variable and click the Results button (Chapter 4.54-updated.png).

A new column appears with zero values by default.


Chapter 5.18-updated.png
A new column appears for Loan.


4. Click the table view button.
5. Pivot the table as shown.

Now you will need to add an expression for loan payments in the edit table:

Car_price*(If Period = 0 then 10% else 2%)

Select the Payments variable. Open the Definition field, then click the Edit table button.


Chapter 5.19-updated.png


6. Enter the new expression for Loan payments as show.

Recall that the input variable Car price is indexed by Car type. Therefore, your new expression will be evaluated separately for the Standard car, the SUV and the Hybrid. The new expression also references the Period index, so it will be evaluated separately for each period as well.


Chapter 5.20-updated.png


Loan payments have been added for all values of Car type and Period.

Using local values and indexes in an expression

Now that you have established all the cash outflows, you can start thinking about how much ownership equity you will have at the end of the 24-month period. Unavoidably you will need to calculate the remaining loan balance at that time. The financial dynamics of a typical loan include compound interest offset by fixed payment amounts. Although the formula for loan balances can be derived fairly easily, this section will focus on how to apply the formula rather than explaining the formula itself. Readers are invited to verify on their own if they wish:

Assuming that a constant amount is paid and nominal interest is compounded every month:

B0 = Starting balance of the loan
12% = Nominal interest rate
60 = The total number of periods required to pay off the loan
Period = A number from 0 to 24 representing the current period
B(Period) = The remaining loan balance for the current period
Let A = (1 + 12% / 12)
B(Period) = B0 * (A^60 - A^Period) / (A^60 - 1)

It is easy to verify that B(0) = B0 and B(60)=0 as required.

The quantity A appears several times in this formula so it makes sense to define it as an intermediate variable. To do the same thing in Analytica, you could define a new variable called A and use it as an input to the loan balance variable. But this would clutter your diagram with an unnecessary node.

Analytica allows local values and indexes to be used temporarily within a definition. In this case you will define a local identifier.

Create a new variable titled Loan balance and enter the following definition:

Variable Loan_balance :=
Local A := (1 + 12%/12);
Car_price(1 - 10%) (A^60 - A^Period)/(A^60 - 1)

Syntax rules for local objects are as follows:

  • The instruction line starts with Local or LocalIndex to declare a local value or index.
  • The declaration is followed by an identifier. This can be anything you choose but it must not be identical to any other input contained in the expression.
  • The assignment operator := comes next (colon followed by an equal sign), followed by an expression defining the object.
  • A semicolon (;) is required to end the instruction line. You may choose to have a visual break (Enter key) after the semicolon for appearance purposes but this is optional. Analytica only looks at semicolons to mark line breaks in code. Each local identifier declaration must be on a separate code line.
  • The final line of instruction contains the definition as usual. All declared local values and indexes will be available to use in expressions.

Local variables are used temporarily and then forgotten after the expression is evaluated. Therefore, the same local identifier (i.e. A) can be used in any number of nodes without conflict.

Chapter 5.21-updated.png

A final note about the expression for Loan Balance:

Although Period is an index, you have used it here as a variable in a mathematical expression. This is possible because Period is a list of numerical values. It would not have been possible to use Car type or Finance option in a mathematical formula since they are lists of labels (although they could be used in logical or conditional statements). In general, you can think of an index as a one-dimensional array that uses its own values as an index.

By the principles of array abstraction, you should expect Loan Balance to be a two-dimensional array indexed by Car type (an index of Car price) and Period.

Chapter 5.22-updated.png
Tip

The Future Value function Fv is a convenient way to calculate loan balances and annuity values without using formulas. Arguments in order are: Interest rate per period, Future period, Payments (negative for payouts), Initial value. For example, Loan Balance could be defined as: Fv(1%, Period, -Car_price*2%, Car_price*90%) See Financial functions in the Analytica User Guide.

Reduce an array using subscripts

Sometimes you may want to reference part of an array variable without using all of its available indexes. Subscripts allow you to reference a slice of an array, effectively eliminating one or more dimensions. The subscript specifies indexes and their desired values for the slice. It is enclosed in square brackets placed immediately after the identifier for the array. For example:

The subscript has reduced a two-dimensional array to a one-dimensional array

Variable Final_period_balance := Loan_balance[Period = 24]

This refers only to the Loan Balance values that correspond to Period 24. Recall that Loan Balance is a two-dimensional array indexed by Period and Car Type. The subscripted reference above will eliminate the Period dimension and return a one-dimensional array indexed only by Car_type.

Chapter 5.23-updated.png

It is possible to eliminate multiple dimensions by including multiple indexes in the subscript, separated by commas. For example:

Variable Final_period_balance := Loan_balance[Period = 24, Car_type = 'SUV']

The result of this expression will be a single value corresponding to the loan balance at Period 24 for the SUV: 24.11K

An Index value can also be selected according to its position in the index rather than the actual value. To make a positional reference, place the "at" symbol (cat) in front of the index identifier. For example, 'SUV' is second in the order of values for the Car type index.

The following subscript references are equivalent:

Loan_balance[Car_type = 'SUV']
Loan_balance[@Car_type = 2]

The verbal terminology for this reference would be: "Loan_balance sliced at position of Car_type equal to 2".

Complete cash flows

Now you can add a variable to represent the amount of ownership equity you will have after 24 months. Of course this will depend on the finance option.

Assume that the value of every car depreciates by 35% over two years.

  • Cash purchasers’ equity will be: Car_price (1 - 35%)
  • Lease holders’ equity will be zero
  • Loaners’ equity will be the difference between car value and the loan balance at Period 24: Car_price (1 - 35%) - Loan_balance[Period = 24]

The Equity variable has only two dimensions: Car type and Finance option.

It refers to a single slice of the Period index.

You can define the Equity variable as a table indexed by Finance option. Each of the expressions above can be entered into the appropriate cell in the edit table:

Variable Equity := Table(Finance_option)
(Car_price*(1 - 35%), 0, (Car_price*(1 - 35%) - Loan_balance[Period = 24]))

Alternatively, you can use conditional and logical statements as follows:

Variable Equity := If Finance_option = 'Lease' then 0 else
Car_price*(1 - 35%) - (Finance_option = 'Loan')*Loan_balance[Period = 24]

Once again, consider how many dimensions your new variable will have. At first you might be tempted to list the indexes as follows:

Finance option (Specified as a table index or used in a conditional expression)
Car type (Index of the input variables Car price and Loan balance)
Period (Index of the input variable Loan balance)

But Loan balance is not an input to this expression; only a slice of it is used. The slice is arrayed only by Car type. Therefore, the Equity variable will be indexed by Finance option and Car type but not by Period.

Chapter 5.24-updated.png

Combine dissimilar arrays

Now that you have established payments and ownership equity, you can combine them into a single cash flow variable. Payments will be represented as negative cash flows. Equity will be represented as a positive cash flow on the last period.

Create a new variable titled Cash flow and enter the following definition:

Variable Cash_flow := If Period = 24 then Equity - Payments else -Payments

In this expression you have combined arrays with different numbers of dimensions:

Payments is indexed by Car type, Finance option and Period.
Equity is indexed only by Car type and Finance option.

There is no ambiguity here since (Equity - Payments) applies to a slice along the Period index. The slice is called out in the conditional statement.

Notice that Equity and Payments[Period = 24] have the same dimensions.

There are other situations where you may want to use a scalar variable (not an array) as an input to an array. Similarly, you may want use an array as an input to another array that has more dimensions. In this situation Analytica will repeat the values of the smaller array for each slice along the new dimensions.

For example, suppose you want to incorporate monthly fuel cost into the Cash flow variable.

Here again you are combining two dissimilar arrays:

Cash flow is indexed by Car type, Finance option and Period
Fuel cost is indexed only by Car type

Create a new variable titled Cash flow with fuel and define it as follows:

Variable Cash_flow_with_fuel :=
If Period = 0 then Cash_flow else Cash_flow - Fuel_cost/12

In this example, Fuel cost is applied to multiple slices along new dimensions:

  • All Period values except Period 0
  • All three Finance option categories.

Select Cash_flow_with_fuel and click the Results button (Chapter 4.54-updated.png)

You will notice "Totals" check boxes next to the row and column index pop-up menus. Checking the box next to Period will allow you to see totals along that index.

Chapter 5.25-updated.png

Array-Reducing Functions

A function that reduces one or more indexes of an array is referred to as an array reducing function. The output of an array reducing function will have fewer dimensions than the input array. For example, the following expression will determine the sum of cash flows over all periods:

Variable Total_cash_flow := Sum(Cash_flow_with_fuel, Period)

The input array is indexed by Car type, Finance option and Period. The output will be a two- dimensional array indexed by Car type and Finance option. In this example the Period dimension has been reduced.

Chapter 5.26-updated.png
  • The first argument of the Sum() function is the identifier of the variable to be operated on.
  • This is followed by a list of indexes separated by commas. These are the indexes over which the function will operate.

In this example you have taken a sum over a single index.

Similar examples of array-reducing functions include Max(), Min(), Product() and Average().

Net Present Value (NPV) analysis

If someone offered you a choice of receiving $100 today or receiving $100 two years from now, which would you choose? If you choose to receive it immediately, you can invest in a low risk bond with an annual return of, say, 6%. In two years the investment will be worth about $112. Clearly these two alternatives do not have equal value. Conversely, you would probably prefer to pay an obligation later rather than sooner.

Net present value (NPV) analysis is a way to compare various scenarios that involve inflows and outflows of money at different time periods. It converts a stream of cash flows to an equivalent scenario where all money is exchanged in a single transaction at the present time. The interest rate that can be achieved in a low risk investment is referred to as the discount rate. For example, given a discount rate of 6%, the NPV of $112 paid two years in the future would be $100.

By taking a simple sum of cash flows as in the example above, you have ignored the time value of money. A Net Present Value analysis is more useful in this case. The NPV() function in Analytica makes this easy. It is another example of an array reducing function.

Assume the discount rate is 0.5% per month. Create an objective node titled Cash flow NPV.

(Objective nodes are represented by the hexagon shape on the node palette.)

Apply the following definition:

Objective Cash_flow_NPV := NPV(0.5%, Cash_flow_with_fuel, Period)
  • The first argument of the NPV function is the discount rate per period.
  • The second argument is the identifier for the variable containing cash flows.
  • The third argument is the index containing period values.

The analysis is complete!

Chapter 5.27-updated.png

Summary

In this chapter you have:

  • Learned Expression syntax
  • Created and defined index variables
  • Created array variables as tables dimensioned along established indexes
  • Expanded arrays by adding new indexes
  • Expanded indexes by adding new index values
  • Created examples that demonstrate the basic principle of array abstraction: The result of an expression is arrayed by the union set of dimensions from all input variables, and the definition of the expression itself.
  • Used conditional and logical statements within an expression
  • Established local values in the definition field
  • Analyzed a multi-dimensional result by pivoting indexes
  • Reduced array variables using subscripts
  • Applied array-reducing functions to arrays

See Also


Comments


You are not allowed to post comments.