Main Content


Generate C code to run kinematic analysis on KinematicsSolver object



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.


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.


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:

mdl = "DoublePendulum";
  • 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";...
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.

  • Create a MEX function for the MATLAB function.

codegen -config:mex DoublePendulum_solveKinematics
Warning: C Compiler produced warnings. See the build log for further details.

Code generation successful (with warnings): To view the report, open('codegen/mex/DoublePendulum_solveKinematics/html/report.mldatx')
  • Solve the inverse kinematics problem using the MEX function.

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


status = 1
targetSuccess = 2x1 logical array


actTargetVals = 2×1


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