Basic Matrix and Vector Functions Written With VBA/Excel: Finaquant Analytics LTD
Basic Matrix and Vector Functions Written With VBA/Excel: Finaquant Analytics LTD
com
Introduction
This release (October 2012) includes about 60 matrix and vector functions for excel users and macro
(VBA) programmers. All these functions are written with the native VBA (Visual Basic for
Applications) language of excel.
You want to implement complex calculations, simulations and optimizations easily with
macros (VBA) in excel.
You want to translate the functions and scripts written with mathematical applications like
matlab into the excel VBA environment, to profit from built
in functions of excel like charting, reporting and data
storage.
Finaquant makes no claims about the precision and performance of this software; feel free to use it
at your own risk. The publisher of this software assumes no responsibility for errors or omissions, or
for damages resulting from the use of this code.
Contents
Basic Matrix and Vector Functions written with VBA/Excel ................................................................... 1
Introduction......................................................................................................................................... 1
Getting started .................................................................................................................................... 5
Your first VBA procedures with matrix and vector functions.......................................................... 6
What is a matrix, and what is a vector for VBA functions ............................................................... 8
How to generate vectors ................................................................................................................. 8
How to generate matrices ............................................................................................................... 9
Getting and setting element values in VBA code (macro) ............................................................ 10
Alias names for functions and procedures .................................................................................... 10
Next steps ...................................................................................................................................... 10
List of functions ................................................................................................................................. 11
1. Matrix-scalar addition - matlab: M2 = M1 + x ........................................................................... 11
2. Customized message box .......................................................................................................... 11
3. Get array dimension .................................................................................................................. 11
4. Check if array ............................................................................................................................. 11
5. Check if empty array.................................................................................................................. 11
6. Check if matrix ........................................................................................................................... 11
7. Check if vector ........................................................................................................................... 12
8. Convert variant array to matrix ................................................................................................. 12
9. Convert variant array to vector ................................................................................................. 12
10. Format matrix for print............................................................................................................ 12
11. Format vector for print ............................................................................................................ 12
12. Convert 1-dimensional matrix to vector ................................................................................. 12
13. Convert vector to a 1-dimensional matrix............................................................................... 12
14. Transpose matrix – matlab: M2 = M1’ .................................................................................... 12
16. Read a worksheet range into variant array ............................................................................. 13
17. Write variant array values into a worksheet range ................................................................. 13
18. Write values of a matrix into a worksheet range .................................................................... 13
19. Write values of a vector into a worksheet range .................................................................... 13
20. Read worksheet range into a matrix ....................................................................................... 13
21. Read worksheet range into a vector ....................................................................................... 13
Getting started
All the matrix and vector functions reside in Module1 section of the excel file you have downloaded
(BasicMatrixAndVectorFunctionsInVBA-V1_1.xlsm). You can refer to all these functions in your own
VBA procedures and functions in other modules and sections (like ThisWorkbook) of your excel file.
Module2 contains some very useful test procedures (sub in VBA) that test all the functions and
procedures residing in Module1.
You can see the whole list of matrix and vector functions by tipping “module1.” in any VBE window.
Note that all function names begin with “FQ_” (FQ for FinaQuant).
The VBA section of the excel file is initially password protected. You can download the password
from the central download page for free in order to view and edit the VBA code in all modules. We
recommend you strongly however, to make no changes in the original code unless it is absolutely
necessary due to an urgent bug. You can always make your own corrections and extensions in other
modules and sections. We would very much appreciate if you inform us about your corrections,
improvements and extensions in the related forum at finaquant.com.
Sub mytest1()
Dim Vin() As Double, Vout() As Double, Vind() As Double
' initiate vector Vin to be sorted in ascending order
Vin = FQ_var_to_vector([{5,2,8,10,4,5,8,1}])
' call sort procedure; Vout is the sorted vector
Call FQ_vector_sort(Vin, Vout:=Vout, ind:=Vind, SortOpt:=nAscending)
' print sorted vector Vout to immediate window
Debug.Print "Sorted vector Vout = " & Chr(10) &
FQ_vector_format(Vout)
End Sub
This procedure creates first a vector with 8 elements, sorts them in ascending order, and prints the
resultant sorted vector into the immediate window (press F5 to execute the procedure).
'******************************************************************
' Procedure for testing FQS_matrix_inverse()
' Author: Finaquant Analytics Ltd. - www.finaquant.com
'******************************************************************
Sub TEST_FQS_matrix_inverse()
Dim r_in As Range, r_out As Range, WorkBookName As String
' define input and output ranges
Set r_in = ThisWorkbook.Sheets("examples").Range("A4:D7")
Set r_out = ThisWorkbook.Sheets("examples").Range("F4:G5")
' call worksheet function
Call FQS_matrix_inverse(r_in, r_out)
End Sub
'******************************************************************
' Example worksheet procedure (name starting with FQS_)
' Write inverse of the matrix to the given output range
' to illustrate general steps 1 (read), 2 (calculate) and 3 (write)
' Author: Finaquant Analytics Ltd. - www.finaquant.com
'******************************************************************
Sub FQS_matrix_inverse(InputRange As Range, OutputRange As Range)
Dim M() As Double, Minv() As Double
On Error GoTo EH1 ' for capturing possible errors
The procedure FQS_matrix_inverse illustrates the general pattern of a high-level function based on
matrices and vectors. First, get all the relevant data as input parameters, second, make all the matrix
and vector calculations without any reference to the data in sheets (or database), third write the
results into sheets (or database). We recommend you to stick to this pattern in your own worksheet
functions:
Use prefix “FQ_” for procedures with matrices and vectors as input and output parameters, without
any reference to worksheets in the excel file.
Use prefix “FQS_” for procedures that read input data from worksheets, and writes results (i.e.
outputs) back to worksheets, like the example above: FQS_matrix_inverse()
Declaring a matrix with N rows and M columns (NxM) in VBA for excel:
Dim M(1 to N, 1 to M) as double
Similarly, a vector is defined as a one-dimensional array of type double, with indices starting from 1:
There are two functions in Module1 whose only task is checking whether the given parameter is a
real matrix or vector:
You can easily convert a matrix into a vector, or vice versa, with the available conversion functions.
Please check the function list.
Note that the semicolon character is here the row separator (delimiter).
‘ Create a 3x4 matrix with random element values between 0 and 100
M2 = FQ_matrix_scalar_multiply(M1, 100)
Vectors:
V1(3) = 4.5 ‘ Set value of vector element with index 3
X = V1(3) ‘ Get value of vector element with index) 3
You don’t need to cancel the password protection for Modul1 and change the name of the function
there. As mentioned at the beginning, we strongly recommend not to make any changes in the
original code unless it is strictly necessary due to a bug.
You can easily create an alias name in a third Module (remember: there are test functions in
Module2). Just enter following lines in Module3:
You can also add new matrix and vector functions to the available list in Module3, in order to use
them in other sections of the VBE (Visual Basic Editor), for example in ThisWorkbook.
Next steps
For updates and supplementary information visit the central download page:
http://finaquant.com/download/matrixvectorvba
For interesting VBA code examples, suggestions and questions see the related finaquant forum:
http://finaquant.com/forum/matrixvectorvba
Can you use the VBA functions presented here for your personal and commercial projects? Do you
want to contribute for the continuity and quality of the project? Yes, you can contribute by:
List of functions
4. Check if array
Function FQ_CheckIfArray(Arr As Variant) As Boolean
' Returns True if the argument is an array; otherwise False
6. Check if matrix
Function FQ_CheckIfMatrix(Arr As Variant) As Boolean
' Returns True if the argument is an matrix; otherwise False
' A matrix must be:
' - 2-dimensional array of data type Double
' - lowest element index must be 1 (lower bound)
7. Check if vector
Function FQ_CheckIfVector(Arr As Variant) As Boolean
' Returns True if the argument is a vector; otherwise False
' - A vector must be:
' - 1-dimensional array of data type Double or Long
' - lowest element index must be 1 (lower bound)
' Writes the values of a vector (1-dim double) into a range in excel
starting from the upper left corner of the range (Cells(1,1))
' - error if V is not vector
' Writes the values of a vector into a matrix either row by row, or
' column by column.
' - matrix row/column size is given by parameters nrow and ncol
' - vector elements are recycled with mod() function, if matrix have
' more elements than the vector
' - error if V is not a vector
' - error of nrow < 1 or ncol < 1
' - error if invalid fill option
41. Sum of two equal sized vectors – matlab: V3 = V1 + V2 (V: 1xN or Nx1 matrix)
Function FQ_vector_vector_sum(V1() As Double, V2() As Double) As
Double()
' Adds up the elements of two vectors with identical lengths
' i.e. element-wise sum of two equal-sized vectors
' - error if V1 and/or V2 is not a vector
' - error if lengths of vectors V1 and V2 are not identical
48. Apply mathematical function on matrix elements – matlab: sin(M), abs(M), fix(M), etc.
Function FQ_matrix_operation(M() As Double, OperationName As String)
As Double()
' Applies the given mathematical operation like abs(), fix(), sin()
etc.
' on all elements of the matrix M (all available single-argument VBA
functions)
' - error if input argument M is not a matrix
49. Apply mathematical function on vector elements – matlab: sin(V), abs(V), fix(V), etc.
Function FQ_vector_operation(V() As Double, OperationName As String)
As Double()
' Applies the given mathematical operation like abs(), fix(), sin()
etc.
' on all elements of the vector V (all available single-argument VBA
functions)
' - error if input argument V is not a vector
' - Example: Return all indices ind of vector elements such that
' V(i) >= SearchValue
' - ComparisonOperator is a string from set {'=', '<>', '>', '>=',
'<', '<='}
' - error if V is not a vector
' - error of undefined comparison operator not in the set above
' - error if a worksheet with the given name does not exist