Documentation

Distribute Visual Basic Application

Calling Compiled MATLAB Functions from Microsoft Excel

In order to call compiled MATLAB® functions from within a Microsoft® Excel® spreadsheet, perform the following from the Development and Deployment machines, as specified.

Note

In order for a function to be called using the Microsoft Excel function syntax (=myfunction(input)), the MATLAB function must return a single scalar output argument.

Perform the following steps on the Development machine:

  1. Create the following MATLAB functions in three separate files named doubleit.m, incrementit.m, and powerit.m, respectively:

     function output = doubleit(input)
       output = input * 2;
    function output = incrementit(input1, input2)
       output = input1 + input2;
     function output = powerit(input1, input2)
       output = power(input1, input2);
    
  2. Start the Library Compiler.

  3. Use the following information as you work through this example using the instructions in Create Excel Add-In from MATLAB:

    Application Namemyexcelfunctions
    Class Namemyexcelfunctionsclass
    Exported Functions

    doubleit.m incrementit.m powerit.m

Perform the following steps on the Deployment machine:

  1. Copy the contents of for_redistribution_files_only to the deployment machine(s). Copy the file to a standard place for use with Microsoft Excel, such as Office_Installation_folder\Library\MATLAB where Office_Installation_folder is a folder such as C:\Program Files\Microsoft Office\OFFICE11.

  2. Install the MATLAB Runtime.

  3. Register myexcelfunctions_1_0.dll.

    Caution

    You need to re-register your DLL file if you move it following its creation. Unlike DLL files, Excel files can be moved anywhere at anytime.

  4. Start Microsoft Excel. The spreadsheet Book1 should be open by default.

  5. In Excel, select Tools > Visual Basic Editor. The Microsoft Visual Basic® Editor starts.

  6. In the Microsoft Visual Basic Editor, select File > Import File.

  7. Browse to myexcelfunctions.bas and click Open. In the Project Explorer, Module1 appears under the Modules node beneath VBAProject (Book1).

  8. In the Microsoft Visual Basic Editor, select View > Microsoft Excel. You can now use the doubleit, incrementit, and powerit functions in your Book1 spreadsheet.

  9. Test the functions, by doing the following:

    1. Enter =doubleit(2.5) in cell A1.

    2. Enter =incrementit(11,17) in cell A2.

    3. Enter =powerit(7,2) in cell A3.

    You should see values 5, 28, and 49 in cells A1, A2, and A3 respectively.

  10. To use the doubleit, powerit, and incrementit functions in all your new Microsoft Excel spreadsheets, do the following:

    1. Select File > Save As.

    2. Change the Save as type option to .xlt (Template).

    3. Browse to the Office_Installation_folder\XLSTART folder.

    4. Save the file as Office_Installation_folder\XLSTART\Book.xlt.

    Note

    Your Microsoft Excel Macro Security level must be set at Medium or Low to save this template.

Where Is the Example Code?

For more information about accessing the example code from within the product ,see Example File Copying.

Improve Data Access Using the MATLAB Runtime User Data Interface and COM Components

Overview

This feature provides a lightweight interface for easily accessing the MATLAB Runtime data. It allows data to be shared between the MATLAB Runtime instance, the MATLAB code running on that the MATLAB Runtime, and the wrapper code that created the MATLAB Runtime. Through calls to the MATLAB Runtime User Data interface API, you access the MATLAB Runtime data by creating a per MATLAB Runtime instance associative array of mxArrays, consisting of a mapping from string keys to mxArray values. Reasons for doing this include, but are not limited to:

  • You need to supply run-time profile information to a client running an application created with the Parallel Computing Toolbox™. Profile information may be supplied (and change) on a per-execution basis. For example, two instances of the same application may run simultaneously with different profiles.

  • You want to initialize the MATLAB Runtime with constant values that can be accessed by all your MATLAB applications.

  • You want to set up a global workspace — a global variable or variables that the MATLAB and your client can access.

  • You want to store the state of any variable or group of variables.

MATLAB Compiler™ supports per the MATLAB Runtime instance state access through an object-oriented API. Unlike MATLAB Compiler, access to per the MATLAB Runtime instance state is optional, rather than on by default. You can access this state by adding setmcruserdata.m and getmcruserdata.m to your deployment project or by specifying them on the command line. Alternately, you use a helper function to call these methods, as shown in Supply Run-Time Profile Information for Parallel Computing Toolbox Applications.

For more information, see the MATLAB Compiler User's Guide.

Supply Run-Time Profile Information for Parallel Computing Toolbox Applications

Following is a complete example of how you can use the MATLAB Runtime User Data Interface as a mechanism to specify a profile for Parallel Computing Toolbox applications.

Note

Standalone executables and shared libraries generated from MATLAB Compiler or MATLAB Compiler SDK™ for parallel applications can now launch up to twelve local workers without MATLAB Parallel Server™.

Step 1: Write Your Parallel Computing Toolbox Code

  1. Compile sample_pct.m in MATLAB.

    This example code uses the cluster defined in the default profile.

    The output assumes that the default profile is local.

    function speedup = sample_pct (n)
    warning off all;
    tic
    if(ischar(n))
        n=str2double(n);
    end
    for ii = 1:n
       (cov(sin(magic(n)+rand(n,n))));
    end
    time1 =toc;
    parpool;
    tic
    parfor ii = 1:n
       (cov(sin(magic(n)+rand(n,n))));
    end
    time2 =toc;
    disp(['Normal loop times: ' num2str(time1) ...
        ',parallel loop time: ' num2str(time2) ]);
    disp(['parallel speedup:  ' num2str(1/(time2/time1)) ...
        ' times faster than normal']);
    delete(gcp);
    disp('done');
    speedup = (time1/time2);
    
  2. Run the code as follows after changing the default profile to local, if needed.

    a = sample_pct(200)

  3. Verify that you get the following results:

    Starting parallel pool (parpool) using the 'local' profile ... connected to 4 workers.
    Normal loop times: 0.7587,parallel loop time: 2.9988
    parallel speedup:  0.253 times faster than normal
    Parallel pool using the 'local' profile is shutting down.
    done
    
    a =
    
        0.2530

Step 2: Set the Parallel Computing Toolbox Profile.  In order to compile MATLAB code to a COM component and utilize the Parallel Computing Toolbox, the mcruserdata must be set directly from MATLAB. There is no API available to access the MCRUserdata as there is for C and C++ applications built with MATLAB Compiler.

To set the mcruserdata from MATLAB, create an init function in your COM class. This is a separate MATLAB function that uses setmcruserdata to set the Parallel Computing Toolbox profile once. You then call your other functions to utilize the Parallel Computing Toolbox functions.

Create the following init function:

function init_sample_pct
% Set the Parallel Profile:
if(isdeployed)
    [profile] = uigetfile('*.settings'); 
                          % let the USER select file
    setmcruserdata('ParallelProfile',[profile]);
end

Step 3: Compile Your Function with the Deploytool or the Command Line.  You can compile your function from the command line by entering the following:

mcc -B 'cexcel:exPctComp,exPctClass,1.0' init_sample_pct.m sample_pct.m

Alternately, you can use the deploytool as follows:

  1. Follow the steps in Create Excel Add-In from MATLAB to compile your application.

    When the compilation finishes, a new folder (with the same name as the project) is created.

    Project NameexPctComp
    Class NameexPctClass
    File to compile sample_pct.m and init_sample_pct.m

    Note

    If you are using the GPU feature of Parallel Computing Toolbox, you need to manually add the PTX and CU files.

    If you are using the Library Compiler app, click Add files/directories on the Build tab.

    If you are using the mcc command, use the -a option.

  2. To deploy the compiled application, copy the for_redistribution_files_only folder, which contains the following, to your end users.

    • exPctComp.dll

    • VBA module (.bas file)

    • MATLAB Runtime installer

    • Cluster profile

    Note

    The end-user's target machine must have access to the cluster.

Step 4: Modify the generated VBA Driver Application (the BAS File).   After registering the COM DLL on the deployment machine and importing the BAS file into Excel, modify the generated BAS file code as needed.

Dim MCLUtil As Object
Dim bModuleInitialized As Boolean
Dim exPctClass As Object
 
Private Sub InitModule()
  If Not bModuleInitialized Then
    On Error GoTo Handle_Error
    If MCLUtil Is Nothing Then
      Set MCLUtil = CreateObject("MWComUtil.MWUtil7.10")
    End If
    Call MCLUtil.MWInitApplication(Application)
    bModuleInitialized = True
    Exit Sub
Handle_Error:
    bModuleInitialized = False
  End If
End Sub
 
Function init_sample_pct() As Variant
 
  On Error GoTo Handle_Error
  Call InitModule
  If exPctClass Is Nothing Then
    Set exPctClass = CreateObject("exPctComp.exPctClass.1_0")
  End If
  Call exPctClass.init_sample_pct
  init_sample_pct = Empty
 
  Exit Function
Handle_Error:
  init_sample_pct = "Error in " & 
                         Err.Source & ": " & Err.Description
End Function
 
 
Function sample_pct(Optional pelle As Variant) As Variant
  Dim speedup As Variant
 
  On Error GoTo Handle_Error
  Call InitModule
  If exPctClass Is Nothing Then
    Set exPctClass = CreateObject("exPctComp.exPctClass.1_0")
  End If
  Call exPctClass.sample_pct(1, speedup, pelle)
  sample_pct = speedup
 
  Exit Function
Handle_Error:
  sample_pct = "Error in " & Err.Source 
                         & ": " & Err.Description
End Function

The output is as follows:

MATLAB Runtime Component Cache and Deployable Archive Embedding

deployable archive data is automatically embedded directly in MATLAB Compiler components by default and extracted to a temporary folder.

Automatic embedding enables usage of MATLAB Runtime Component Cache features through environment variables.

These variables allow you to specify the following:

  • Define the default location where you want the deployable archive to be automatically extracted

  • Add diagnostic error printing options that can be used when automatically extracting the deployable, for troubleshooting purposes

  • Tuning the MATLAB Runtime component cache size for performance reasons.

Use the following environment variables to change these settings.

Environment VariablePurposeNotes
MCR_CACHE_ROOTWhen set to the location of where you want the deployable archive to be extracted, this variable overrides the default per-user component cache location. This is true for embedded .ctf files only.Does not apply
MCR_CACHE_SIZEWhen set, this variable overrides the default component cache size.The initial limit for this variable is 32M (megabytes). This may, however, be changed after you have set the variable the first time. Edit the file .max_size, which resides in the file designated by running the mcrcachedir command, with the desired cache size limit.

You can override this automatic embedding and extraction behavior by compiling with the -C option. See Overriding Default Behavior for details.

Note

If you run mcc specifying conflicting wrapper and target types, the deployable archive will not be embedded into the generated component. For example, if you run:

mcc -W lib:myLib -T link:exe test.m test.c
the generated test.exe will not have the deployable archive embedded in it, as if you had specified a -C option to the command line.

Caution

Do not extract the files within the.ctf file and place them individually under version control. Since the .ctf file contains interdependent MATLAB functions and data, the files within it must be accessed only by accessing the .ctf file. For best results, place the entire .ctf file under version control.

Overriding Default Behavior

To extract the deployable archive in a manner prior to R2008b, alongside the compiled COM component, compile using the mcc -c option.

You can also implement this override by adding the -c flag in the Settings section of the compiler app.

You might want to use this option to troubleshoot problems with the deployable archive, for example, as the log and diagnostic messages are much more visible.

For More Information

For more information about the deployable archive, see Deployable Archive.

MATLAB Runtime Options

What MATLAB Runtime Options are Supported by MATLAB Compiler?

  • -logfile — Creates a named log file.

How Do I Specify MATLAB Runtime Options?

If You Compiled the Add-In in MATLAB or used mcc.  If you are building your add-in using the MATLAB Library Compiler, select Create log file under Additional Runtime Settings.

If you are building your add-in using mcc, simply specify -logfile with the mcc -R command

If You Created a Function From Scratch Using the Function Wizard.  If you created a function from scratch using the Function Wizard, and want to specify MATLAB Runtime options, you have to manually modify the .bas file code.

You do this by invoking the following MWUtil API calls, detailed with examples in Class MWUtil: