Lesson 18-MATLAB Source Code and Runtime Mechanism Analysis

MATLAB Interaction with External Languages

MATLAB Engine API Development

C++ Engine API Example:

#include "engine.h"
#include <iostream>

int main() {
    // Start MATLAB engine
    Engine *ep = engOpen(nullptr);
    if (!ep) {
        std::cerr << "Unable to start MATLAB engine" << std::endl;
        return 1;
    }

    // Execute MATLAB commands
    engEvalString(ep, "x = 1:10;");
    engEvalString(ep, "y = sin(x);");
    
    // Get variable
    mxArray *result = engGetVariable(ep, "y");
    if (result) {
        double *data = mxGetPr(result);
        int length = mxGetNumberOfElements(result);
        
        // Print results
        std::cout << "MATLAB computation result: ";
        for (int i = 0; i < length; ++i) {
            std::cout << data[i] << " ";
        }
        std::cout << std::endl;
        
        // Release memory
        mxDestroyArray(result);
    }

    // Close engine
    engClose(ep);
    return 0;
}

Python Interface Advanced Application:

import matlab.engine

# Start MATLAB engine (shared session)
eng = matlab.engine.start_matlab('-desktop')

# Pass numpy array to MATLAB
import numpy as np
np_array = np.random.rand(1000, 1000)
matlab_array = matlab.double(np_array.tolist())

# Call MATLAB function
result = eng.svd(matlab_array)

# Get return results
U, S, V = result
print("Singular values:", S[:5])  # Print first 5 singular values

# Asynchronous call
future = eng.eig(matlab_array, background=True)
# Perform other operations...
result = future.result()  # Get result

# Close engine
eng.quit()

MEX File Optimization Techniques

Multi-threaded MEX Implementation:

#include "mex.h"
#include <omp.h>

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    // Check input parameters
    if (nrhs != 1 || !mxIsDouble(prhs[0])) {
        mexErrMsgIdAndTxt("MyToolbox:invalidInput", "Requires one double type array");
    }

    // Get input data
    double *input = mxGetPr(prhs[0]);
    mwSize n = mxGetNumberOfElements(prhs[0]);
    
    // Create output array
    plhs[0] = mxCreateDoubleMatrix(1, n, mxREAL);
    double *output = mxGetPr(plhs[0]);

    // OpenMP parallel computation
    #pragma omp parallel for
    for (mwSize i = 0; i < n; ++i) {
        output[i] = input[i] * 2.0;  // Simple example: multiply by 2
    }

    // More complex computation example (matrix operations)
    /*
    #pragma omp parallel for collapse(2)
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            output[i + j * rows] = input[i + j * rows] * 2.0;
        }
    }
    */
}

Memory Management Optimization Example:

#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    // Pre-allocate large memory block (avoid frequent allocation)
    const mwSize blockSize = 1000000;
    double *buffer = (double *)mxMalloc(blockSize * sizeof(double));
    
    if (buffer == nullptr) {
        mexErrMsgIdAndTxt("MyToolbox:memoryError", "Memory allocation failed");
    }

    // Use buffer for computation
    for (mwSize i = 0; i < blockSize; ++i) {
        buffer[i] = i * 0.1;
    }

    // Create output array (from pre-allocated memory)
    plhs[0] = mxCreateNumericMatrix(1, blockSize, mxDOUBLE_CLASS, mxREAL);
    double *output = mxGetPr(plhs[0]);
    
    // Copy data from buffer to output
    memcpy(output, buffer, blockSize * sizeof(double));

    // Release buffer memory
    mxFree(buffer);
}

MATLAB Kernel Mechanism Analysis

Function Call Underlying Implementation

Parameter Passing Mechanism Analysis:

% Example function (observe parameter passing)
function y = parameterPassingDemo(x)
    % View input parameter address (requires MEX coordination)
    % Actual implementation needs MEX function support
    y = x * 2;
end

% Call example
a = rand(1000);
b = parameterPassingDemo(a);  % Observe memory changes

Return Value Handling Mechanism:

% Multiple return values example
function [sum_val, prod_val] = computeStats(x)
    sum_val = sum(x);
    prod_val = prod(x);
end

% Call analysis
data = 1:10;
[s, p] = computeStats(data);  % Observe return value memory allocation

Memory Management Mechanism

mxArray Lifecycle Management:

% Memory allocation example
A = rand(1000);  % Allocate memory on MATLAB heap
B = A;           % Reference count increases (no data copy)

% Explicit memory release
clear A;         % Decrease reference count, release when count is 0

% Large memory operation notes
largeData = rand(1e6);  % Allocate about 8MB memory
% ...process data...
clear largeData;        % Release promptly

Garbage Collection Trigger Conditions:

% Force garbage collection
gc();  % Manually trigger garbage collection

% Monitor memory usage
memory;  % Display memory usage

% Memory management in loops
for i = 1:1000
    temp = rand(1000);  % Allocate memory each iteration
    process(temp);      % Process data
    clear temp;         % Release promptly
end

JIT Compilation Mechanism

JIT Acceleration Effect Comparison:

% Disable JIT for performance comparison
feature('jit', 'off');
tic;
sum(rand(1e6,1));  % No JIT acceleration
no_jit_time = toc;

% Enable JIT (default state)
feature('jit', 'on');
tic;
sum(rand(1e6,1));  % JIT acceleration
jit_time = toc;

fprintf('JIT acceleration ratio: %.2fx\n', no_jit_time/jit_time);

JIT Optimization Limitation Examples:

% Cases where JIT cannot optimize
% 1. Using eval function
eval('sum(rand(1e6,1))');  % Cannot JIT accelerate

% 2. Dynamic field access
data = struct('value', rand(1e6,1));
field = 'value';
sum(data.(field));  % Dynamic field access

% 3. Certain function calls
sum(customFunction(rand(1e6,1)));  % Custom functions may not be optimized

Custom Toolbox Development

Creating .mltbx Toolbox

Toolbox Packaging Process:

% 1. Create toolbox directory structure
toolboxDir = 'MyCustomToolbox';
mkdir(toolboxDir);
mkdir(fullfile(toolboxDir, 'functions'));
mkdir(fullfile(toolboxDir, '+mypkg'));  % Package directory

% 2. Add function files
fid = fopen(fullfile(toolboxDir, 'functions', 'myFunction.m'), 'w');
fprintf(fid, ['function y = myFunction(x)\n' ...
              '    %% MYFUNCTION Example function\n' ...
              '    y = x * 2;\n']);
fclose(fid);

% 3. Create package function
fid = fopen(fullfile(toolboxDir, '+mypkg', 'mypkgFunc.m'), 'w');
fprintf(fid, ['function z = mypkgFunc(y)\n' ...
              '    %% MYPKGFUNC Package function example\n' ...
              '    z = y + 1;\n']);
fclose(fid);

% 4. Create info.xml (toolbox metadata)
infoXML = ['<?xml version="1.0" encoding="utf-8"?>\n' ...
           '<toolbox name="MyCustomToolbox" version="1.0">\n' ...
           '    <summary>Custom toolbox example</summary>\n' ...
           '    <description>Includes example functions and packages</description>\n' ...
           '    <helpLocation>html</helpLocation>\n' ...
           '</toolbox>'];
fid = fopen(fullfile(toolboxDir, 'info.xml'), 'w');
fprintf(fid, infoXML);
fclose(fid);

% 5. Package as .mltbx file
matlab.addons.toolbox.packageToolbox(toolboxDir, 'MyCustomToolbox.mltbx');

Toolbox Dependency Management:

% Add dependencies in info.xml
depsXML = ['<dependencies>\n' ...
           '    <matlab version="9.10"/>  <!-- R2021a -->\n' ...
           '    <toolbox name="Signal Processing Toolbox"/>\n' ...
           '</dependencies>'];
% Insert into <toolbox> tag in info.xml

Model Compilation and Simulation Process

Compilation Process Visualization:

% Enable detailed compilation log
set_param('myModel', 'Verbose', 'on');
set_param('myModel', 'SimulationMode', 'normal');

% Compile model (view compilation stages)
sim('myModel');

% Use Simulink Profiler for analysis
profile on;
sim('myModel');
profile viewer;

% Model compilation stage breakdown
% 1. Model loading
% 2. Parameter validation
% 3. Data type propagation
% 4. Signal attribute resolution
% 5. Code generation (simulation engine)
% 6. Simulation execution

S-Function Development

C-MEX S-Function Example:

#define S_FUNCTION_NAME  mySFunction
#define S_FUNCTION_LEVEL 2

#include "simstruc.h"

static void mdlInitializeSizes(SimStruct *S) {
    ssSetNumSFcnParams(S, 0);  // No parameters
    if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
        return; /* Parameter mismatch */
    }

    ssSetNumContStates(S, 0);
    ssSetNumDiscStates(S, 0);

    if (!ssSetNumInputPorts(S, 1)) return;
    ssSetInputPortWidth(S, 0, 1);
    ssSetInputPortDirectFeedThrough(S, 0, 1);

    if (!ssSetNumOutputPorts(S, 1)) return;
    ssSetOutputPortWidth(S, 0, 1);

    ssSetNumSampleTimes(S, 1);
    ssSetOptions(S, 0);
}

static void mdlInitializeSampleTimes(SimStruct *S) {
    ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
    ssSetOffsetTime(S, 0, 0.0);
}

static void mdlOutputs(SimStruct *S, int_T tid) {
    real_T *y = ssGetOutputPortRealSignal(S, 0);
    real_T *u = ssGetInputPortRealSignal(S, 0);

    y[0] = u[0] * 2.0;  // Simple example: multiply by 2
}

static void mdlTerminate(SimStruct *S) {
    /* No termination operations */
}

#ifdef MATLAB_MEX_FILE
#include "simulink.c"
#else
#include "cg_sfun.h"
#endif

S-Function Interaction with MATLAB:

// Call MATLAB function in mdlOutputs
static void mdlOutputs(SimStruct *S, int_T tid) {
    mxArray *input = mxCreateDoubleScalar(ssGetInputPortRealSignal(S, 0)[0]);
    mxArray *output = NULL;
    
    // Call MATLAB function
    mexCallMATLAB(1, &output, 1, &input, "myMatlabFunction");
    
    // Get result
    real_T *y = ssGetOutputPortRealSignal(S, 0);
    y[0] = mxGetScalar(output);
    
    // Release memory
    mxDestroyArray(input);
    mxDestroyArray(output);
}
Share your love