Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

Problem

You want to declare a matrix, populate it with nonzero values, and perform several standard matrix calculations on it.

Solution

Sample code folder: Chapter 06\Matrix

This recipe demonstrates how to declare and populate a matrix in a clear, readable way. A module of matrix functions is also included, although several of the functions it contains will be presented in follow-up recipes.

Discussion

Nested braces containing comma-separated numbers can be used to fill arrays of one or more dimensions. In the case of a two-dimensional matrix, the braces can optionally be separated to show each row of numbers on its own line using the underscore (_) line-continuation character. Feel free to use whatever layout details work for you, but the following sample of a 3 x 3 matrix can provide a decent, visually appealing layout in your source code:

Dim matrixA(,) As Double = { _ {4, 5, 6}, _ {7, 8, 9}, _ {3, 2, 1}} MsgBox(MatrixHelper.MakeDisplayable(matrixA))

The last line of this code uses a function named MakeDisplayable() to return a string representation of a matrix suitable for display, as shown in Figure 6-31. This function is one of several to be presented in the code module named MatrixHelper.

Figure 6-31. The custom output of the matrix

The MatrixHelper module contains several functions to work with matrices, and the recipes that follow will describe them further. A complete listing of MatrixHelper.vb can be found at the end of this chapter.

See Also

See the full MatrixHelper.vb listing in Recipe 6.35.

Категории