Array Manipulation Examples and Challenge Problems
This page is a place to collect array-manipulation examples and challenge problems.
If you are learning to use Analytica, try these challenge problems before looking at the solutions.
If you have an example that might be helpful to others, post it!
These should be problems that can be described concisely, and are focused on manipulations of arrays. Beyond the scope would be questions like how to model some particular problem, or how to structure a problem.
List and 1-D manipulations
Re-indexing
Flattening and Un-flattening
Flattening a 2-D Matrix to a 1-D vector
Given: Array A[I,J], indexed by I and J.
Compute: 1-D Array B[K], where K has length size(I)*size(J), containing the elements of A.
Model file: Flattening 2-D to 1-D.ana (contains setup and solutions)
The need to flatten a matrix into 1-D occurs in several contexts. When setting up an optimization, for example, the decision variables must be collected into a single 1-D vector. If you are finding the optimal weight-matrix, for example, you may need to "flatten" your initial guess, in order to pass it to NlpDefine. Similarly, you may have a 2-D array of coefficients identified in a Regression problem, that must be flattened into a 1-D basis index.
Solution 1
- Add Library..., Concatentation.ana
- Define K as: K := 1..size(I)*size(J)
- Define B as ConcatRows(A,I,J,K)
Solution 2
(This is the more general solution, in that it generalized to flattening N-D arrays )
- Define K as: K := 1..size(I)*size(J)
- Define L := ['I','J','A']
- Define B := MdArrayToTable(A,K,L)[L='A']
Flattening a Symmetrical 2-D matrix into a 1-D vector
Given: Array A[I,J], indexed by I and J.
Compute:1-D Array B[K], containing the elements of the upper-half triangle of the matrix, but without their duplicate lower-half elements.
Enable comment auto-refresher