Indexing arrays by observed variablesBesides ranges, VariableArrays can be indexed by integer variables. This allows you to create complex dependencies between array elements. For example, suppose you have an array of boolean variables, and you want to constrain one of them to be true. This can be accomplished as follows:
The observed value of index can be set and changed at any time. This immediately changes the effect of the constraint. For example:
Besides applying constraints, you can also use bools[index] in a factor, or basically anywhere you would use an ordinary variable. Indexing by observed variables is currently supported for one-dimensional arrays (including jagged arrays). To index by an unobserved (i.e. random) integer variable, use a Switch block. Indexing by observed variable arraysThe index can be an array element, allowing you to compactly access many elements of a VariableArray. For example, suppose you want to constrain several elements of bools to be true. You can do this as follows:
Here we have made a variable (numIndices) for the size of the indexed_item range, so that we can vary the number of indices at runtime. For example:
Efficient access to subarraysA speed-up is possible when you know that the indices are all distinct. In other words, you are extracting a subarray of the original variable array. The function Variable.Subarray handles this case efficiently, taking a VariableArray and an array of indices, and returning a smaller VariableArray. We can apply this transformation to the above example, to get:
During inference, this model gives the same answers as above, however it runs a bit faster since Infer.NET does not have to check for the case that two indices might be equal.
|


