Main Content

generateCode

Generate C code to run kinematic analysis on KinematicsSolver object

Since R2019a

Description

example

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

To use the model files, open the Assembling Parts into a Double Pendulum example and into memory. At the MATLAB command prompt enter:

openExample("sm/DoublePendulumExample");
mdl = "DoublePendulum";
load_system(mdl);
  • Set up the inverse kinematics problem for the double pendulum model.

ks = simscape.multibody.KinematicsSolver(mdl);
addFrameVariables(ks, "LowerLinkPeg", "translation",...
                 "DoublePendulum/World Frame/W",...
                 "DoublePendulum/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);
  • Create a standalone solve function and a directory with source files.

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

codegen -config:mex DoublePendulum_solveKinematics
Code generation successful.
  • Solve the inverse kinematics problem using the MEX function.

[outputVals, status, targetSuccess, actTargetVals] =...
 DoublePendulum_solveKinematics_mex([0.3, 0], 120)
outputVals = 2×1

  124.0477
  -57.1217

status = 1
targetSuccess = 2x1 logical array

   1
   1

actTargetVals = 2×1

    0.3000
    0.0000

Input Arguments

collapse all

Kinematics solver object, specified as a KinematicsSolver object that is the representation of the Simscape™ Multibody™ model used for kinematic analysis.

Example: ks = simscape.multibody.KinematicsSolver("DoublePendulumExample​'​')

Version History

Introduced in R2019a