Main Content

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.

Cholesky.m

function [L] = Cholesky()
    global A;
    if (isempty(A))
        L = [];
        return;
    end
    L = chol(A);

LUDecomp.m

function [L,U] = LUDecomp()
    global A;
    if (isempty(A))
        L = [];
        U = [];
        return;
    end
    [L,U] = lu(A);

QRDecomp.m

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:

  1. Create a compiler project named mymatrix with a version of 1.0.

  2. Add a single class called myfactor to the component.

  3. Add the above three MATLAB files to the class.

  4. Build the component.

Use the following Visual Basic® subroutine to test the myfactor class:

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:

  1. Creates an instance of the myfactor class

  2. Assigns a double matrix to the property A

  3. Calls the three factorization methods