Use MATLAB Global Variables in Visual Basic
Class properties allow an object to retain an internal state between method calls.
Global variables are variables that are declared in the
MATLAB® product with the
global keyword. MATLAB
Compiler SDK™ automatically converts all global variables shared by the MATLAB files that make up a class to properties on that class.
Properties are useful when you have a large array containing values that do not change often, but are operated on frequently. In such cases, setting the array as a property saves the overhead required to pass it to a method every time it is called.
The following example shows how to use a class property in a matrix factorization class. The example develops a class that performs Cholesky, LU, and QR factorizations on the same matrix. It stores the input matrix as a class property so that it is not passed to the factorization routines.
Consider these three MATLAB files.
function [L] = Cholesky() global A; if (isempty(A)) L = ; return; end L = chol(A);
function [L,U] = LUDecomp() global A; if (isempty(A)) L = ; U = ; return; end [L,U] = lu(A);
function [Q,R] = QRDecomp() global A; if (isempty(A)) Q = ; R = ; return; end [Q,R] = qr(A);
These three files share a common global variable
A. Each function
performs a matrix factorization on
A and returns the results.
To build the class:
Create a compiler project named
mymatrixwith a version of 1.0.
Add a single class called
myfactorto the component.
Add the above three MATLAB files to the class.
Build the component.
Use the following Visual Basic® subroutine to test the
Sub TestFactor() Dim x(1 To 2, 1 To 2) As Double Dim C As Variant, L As Variant, U As Variant, _ Q As Variant, R As Variant Dim factor As myfactor On Error GoTo Handle_Error Set factor = New myfactor x(1, 1) = 2# x(1, 2) = -1# x(2, 1) = -1# x(2, 2) = 2# factor.A = x Call factor.cholesky(1, C) Call factor.ludecomp(2, L, U) Call factor.qrdecomp(2, Q, R) Exit Sub Handle_Error: MsgBox (Err.Description) End Sub
Run the subroutine, which does the following:
Creates an instance of the
Assigns a double matrix to the property
Calls the three factorization methods