Main Content

generateCode

Generate C code to run kinematic analysis on KinematicsSolver object

Description

generateCode(ks) creates a standalone MATLAB® function that is equivalent to the solve function, but supports code generation. It also creates a directory called ModelName_codegen_kinematics that contains all the source files for the code generation in the current directory, where ModelName is the output string of ks.ModelName.

The created MATLAB function is called ModelName_solveKinematics and has the same signature as the solve function:

[outputs,statusFlag,targetFlags,targets] = ModelName_solveKinematics(targets, initialGuesses)

Once generated, the function is completely independent from the original object and will not reflect any changes to the object. You can generate MEX functions, static libraries (LIB), and dynamics libraries (DLL) from MATLAB code that contains the ModelName_solveKinematics function by using the codegen function, which requires a MATLAB Coder™ license.

Note

ModelName_solveKinematics is not meant to be invoked from MATLAB and an error occurs when calling it directly from the MATLAB command line or a MATLAB file. However, you can call this function directly from a MATLAB Function block in a Simulink model.

Examples

collapse all

  1. Set up the inverse kinematics problem for the double pendulum model.

    mdl = 'sm_double_pendulum';
    open_system(mdl);
    ks = simscape.multibody.KinematicsSolver(mdl);
    addFrameVariables(ks, 'LowerLinkPeg', 'translation',...
                     'sm_double_pendulum/World Frame/W',...
                     'sm_double_pendulum/Lower Link/Right Peg/R');
    targetIds = ["LowerLinkPeg.Translation.x";...
                "LowerLinkPeg.Translation.z"];
    addTargetVariables(ks, targetIds);
    initialGuessIds = "j2.Rz.q";
    addInitialGuessVariables(ks, initialGuessIds);
    outputIds = ["j2.Rz.q"; "j1.Rz.q"];
    addOutputVariables(ks, outputIds);
  2. Create a standalone solve function and a directory with source files.

    generateCode(ks);
  3. Create a MEX function for the MATLAB function.

    codegen -config:mex sm_double_pendulum_solveKinematics
    
  4. Solve the inverse kinematics problem using the MEX function.

    [outputVals, status, targetSuccess, actTargetVals] =...
     sm_double_pendulum_solveKinematics_mex([0.3, 0], 120)
  5. Outputs

    outputVals =
      124.0477
      -57.1217
    
    status =
      1
    
    targetSuccess =
      2×1 logical array
      1
      1
    
    actTargetVals =
      0.3000
      0

Input Arguments

collapse all

A KinematicsSolver object is the representation of a Simscape Multibody model used for kinematic analysis.

Example: ks = simscape.multibody.KinematicsSolver('sm_double_pendulum')

Data Types: KinematicsSolver object

Introduced in R2019a