主要内容

Root Mean Square Code Replacement

This example shows how to replace the code generated from the rms function with a custom root mean square (RMS) function. Replacing the generated code with a custom function can optimize the generated code for your target execution environment.

RMS Function Configurations

When you define a code replacement entry for the rms function, you must specify a conceptual representation function prototype that corresponds to these characteristics of the function:

  • The syntax of the function, which determines the dimension over which the function calculates the RMS value.

  • The data type of the input, which can be single or double and real or complex.

  • The dimensions of the input, which can be scalar, vector, or a matrix. You can specify the dimensions as either:

    • A range of sizes by using a two-row matrix, for example, [1 1 1; inf inf inf].

    • A specific size by using a vector, for example, [20, 30, 40].

This table shows the function prototype to use according to the rms function syntax.

SyntaxConceptual Function SignatureArgumentsExample Function Prototypes
rms(x,"all") — RMS of all elementsy1 = rms(u1)
  • y1 — output, specified as a single or double

  • u1 — input, specified as a matrix of the data type and dimension of the function input argument

single y1 = rms(single u1[1 1 1; inf inf inf]) matches rms functions that calculate the value over all elements of a three-dimensional matrix.
rms(x) — RMS for a column vector, row vector, or matrix xy1 = rms(u1, u2)
  • y1 — output, specified as a scalar or matrix of the data type and dimension that matches the output of the rms function

  • u1 — input, specified as a matrix of the data type and dimension of the first rms function input argument. If the input is a column vector, u1 must specify a two-dimensional matrix with the second dimension as size 1.

  • u2 — input, specified as a single or double representing the dimension to calculate the RMS over. The default data type for a numeric value is double.

  • single y1 = rms(single u1[1 1; 1 inf], double u2) matches rms functions that calculate the value over a row vector.

  • single y1 = rms(single u1[1 1; inf 1], double u2) matches rms functions that calculate the value over a column vector.

  • single y1[1 1 1; 1 inf inf] = rms(single u1[1 1 1; inf inf inf]) matches rms functions that calculate the value for a three-dimensional matrix.

rms(x,dim) — RMS calculated over the specified dimensionsingle y1[1 1 1; inf 1 inf] = rms(single u1[1 1 1; inf inf inf], single u2) matches rms functions that calculate the value over the second dimension (each row) of a three-dimensional matrix.
rms(x,vecdim) — RMS calculated over multiple dimensions specified by a vectorNot supportedNot supportedNot supported
rms(__,nanflag) — Whether to include or omit NaN values

Replace Code From rms Functions

Create and register a code replacement library that replaces code generated from rms functions.

  1. Open the programmatic interface from the MATLAB menu by selecting New > Function.

  2. Create a table.

    1. Create a function with the name of your code replacement library table that does not have arguments and returns a table object. You can use this function to call your code replacement library table.

    2. Create a table object by calling RTW.TflTable.

    function hTable = crl_rms_func
    % Create a function to call the code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
  3. Create an entry by calling the function createCRLEntry. Specify these arguments:

    • The code replacement table object.

    • A function prototype for the conceptual representation of the rms functions to replace.

    • A function prototype for the implementation function that replaces the rms function calls.

    For this example, replace the code for rms functions that perform the calculation over the entire input of a three-dimensional matrix with the custom function rms_all.

    function hTable = crl_rms_func
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = createCRLEntry(hTable,...
                          "single y1 = rms(single u1[1 1 1; inf inf inf])",...
                          "single y1 = rms_all(single* u1)");
  4. Create entry parameters. Because this example replaces a function, create entry parameters by calling the function setTflCFunctionEntryParameters. For this example, specify the implementation header file rms_all.h.

    function hTable = crl_rms_func
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = createCRLEntry(hTable,...
                          "single y1 = rms(single u1[1 1 1; inf inf inf])",...
                          "single y1 = rms_all(single* u1)");
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters("ImplementationHeaderFile","rms_all.h");
  5. Add the entry to the table by calling addEntry.

    function hTable = crl_rms_func
    % Create a code replacement library table 
    
    %% Create a table object
    hTable = RTW.TflTable;
    
    %% Create an entry
    hEntry = createCRLEntry(hTable,...
                          "single y1 = rms(single u1[1 1 1; inf inf inf])",...
                          "single y1 = rms_all(single* u1)");
    
    %% Create entry parameters
    hEntry.setTflCFunctionEntryParameters("ImplementationHeaderFile","rms_all.h");
    
    %% Add entry to the table
    addEntry(hTable,hEntry);
  6. Validate and save the customization file. From the MATLAB menu, save this customization file by selecting File > Save. From the command line, validate the code replacement library table by calling it:

    hTable = crl_rms_func
  7. Register the code replacement library. Registration creates a code replacement library by defining the library name, code replacement tables, and other information. Create a registration file (a new function file) with these specifications:

    function rtwTargetInfo(cm)
     
    cm.registerTargetInfo(@loc_register_crl);
    end
     
    function this = loc_register_crl 
     
    this(1) = RTW.TflRegistry; 
    this(1).Name = 'CRLRMSFunc';
    this(1).TableList = {'crl_rms_func.m'}; % table created in this example
    this(1).TargetHWDeviceType = {'*'};
    this(1).Description = 'Example code replacement library';
    
    end

    To use your code replacement library, refresh your current MATLAB session with the command:

    RTW.TargetRegistry.getInstance('reset');

  8. Verify the code replacement library. From the MATLAB command line, open the library by using the Code Replacement Viewer and verify that the table and entry are correctly specified. For more information, see Verify Code Replacement Library. Configure your model to use the code replacement library, generate code, and verify that code replacement occurs as expected. If unexpected behavior occurs, examine the hit and miss logs to troubleshoot the issues.

Example rms Functions Code Replacement

This example shows code replacement for a function that calls the rms function using a variety of data types and dimensions.

function [all,dim1,dim2,dim3] = rmswrapper(in1)

in_single = single(in1);
in_double = double(in1);
in_complex_double = complex(in_double,in_double);

all = rms(in_single,"all");
dim1 = rms(in_single,1);
dim2 = rms(in_double,2);
dim3 = rms(in_complex_double,3);

end

This code replacement library replaces the RMS code with custom RMS functions.

function hLib = crl_rms_func
    %   Copyright 2025 The MathWorks, Inc.

    hLib = RTW.TflTable;
    % 3 Dimensional Single Matrix, Calculate Over Entire Input 
    hEnt = hLib.createCRLEntry('single y1 = rms(single u1[1 1 1; inf inf inf])', ...
        'single y1 = rms_all(single* u1)');
    hEnt.setTflCFunctionEntryParameters('ImplementationHeaderFile', 'rms_all.h');
    hLib.addEntry(hEnt);

    % 3 Dimensional Single Matrix, Calculate Over Dimension 1 (Each Column)
    hEnt = hLib.createCRLEntry('single y1[1 1 1; 1 inf inf] = rms(single u1[1 1 1; inf inf inf], double u2)', ...
        'void rms_dim1(single* y1, single* u1, double u2)');
    hEnt.setTflCFunctionEntryParameters('ImplementationHeaderFile', 'rms_dim1.h');
    hLib.addEntry(hEnt);
    
    % 3 Dimensional Double Matrix, Calculate Over Dimension 2 (Each Row)
    hEnt = hLib.createCRLEntry('double y1[1 1 1; inf 1 inf] = rms(double u1[1 1 1; inf inf inf], double u2)', ...
        'void rms_dim2(double* y1, double* u1, double u2)');
    hEnt.setTflCFunctionEntryParameters('ImplementationHeaderFile', 'rms_dim2.h');
    hLib.addEntry(hEnt);
    
    % 3 Dimensional Complex Double Matrix, Calculate Over Dimension 3
    hEnt = hLib.createCRLEntry('double y1[1 1; inf inf] = rms(cdouble u1[1 1 1; inf inf inf], double u2)', ...
        'void rms_dim3(double* y1, cdouble* u1, double u2)');
    hEnt.setTflCFunctionEntryParameters('ImplementationHeaderFile', 'rms_dim3.h');
    hLib.addEntry(hEnt);

end

This registration file registers the code replacement library.

function rtwTargetInfo(cm)
 
cm.registerTargetInfo(@loc_register_crl);
end
 
function this = loc_register_crl 
 
this(1) = RTW.TflRegistry; 
this(1).Name = 'CRLRMSFunc';
this(1).TableList = {'crl_rms_func.m'};
this(1).TargetHWDeviceType = {'*'};
this(1).Description = 'Example code replacement library';

end

To generate code that uses the custom RMS functions:

  1. Refresh the current MATLAB® session to make the code replacement library available by entering RTW.TargetRegistry.getInstance('reset'); at the command line.

    RTW.TargetRegistry.getInstance('reset');

  2. Create a code generation configuration that uses the code replacement library. You can also configure the code generator to generate a report that includes information on the code replacements.

    cfg = coder.config('lib');
    cfg.GenerateCodeReplacementReport = true;
    cfg.CodeReplacementLibrary = "CRLRMSFunc";
    cfg.GenCodeOnly = true;
    cfg.GenerateReport = true;
    cfg.InstructionSetExtensions="None";
  3. Create an example three-dimensional input argument matrix.

    A = rand(4,5,6);
  4. Generate code for the wrapper function by using the configuration.

    codegen -config cfg rmswrapper -args {A};

This generated code contains calls to custom replacement functions.

void rmswrapper(const double in1[120], float *all, float dim1[30],
                double dim2[24], double dim3[20])
{
  creal_T dcv[120];
  float in_single[120];
  int i;
  for (i = 0; i < 120; i++) {
    in_single[i] = (float)in1[i];
  }
  *all = rms_all(&in_single[0]);
  rms_dim1(&dim1[0], &in_single[0], 1.0);
  rms_dim2(&dim2[0], (double *)&in1[0], 2.0);
  for (i = 0; i < 120; i++) {
    dcv[i].re = in1[i];
    dcv[i].im = in1[i];
  }
  rms_dim3(&dim3[0], &dcv[0], 3.0);
}

See Also

| |

Topics