How to use plot3 function inside Matlab function block used in Simulink ?

5 次查看(过去 30 天)
I am using Simulink to model my system. I want to visualise my model in a 3D plot. I see people generally transport data from Simulink to Matlab to visualise. Is it possible to use inbuilt Matlab functions like plot3 to visualise the system in Simulink environment ?

回答(1 个)

Tejas
Tejas 2024-9-23
Hello Vignesh,
To use the plot3 function within a MATLAB Function block in Simulink, it must first be declared as an extrinsic function. This informs the code generator to bypass generating code for these functions and instead use the MATLAB engine to execute them. For more details on extrinsic functions, refer to this documentation: https://www.mathworks.com/help/releases/R2021b/coder/ref/coder.extrinsic.html
Additionally, other functions used alongside plot3, such as hold, grid, xlabel, ylabel, zlabel, and title, should also be declared as extrinsic.
Here are the steps to use the plot3 function within a MATLAB Function block in Simulink:
  • Declare plot3 and the other necessary functions as extrinsic.
  • Declare a persistent variable to refer to the figure. This ensures that each simulation of the model uses the same figure, preventing the creation of different figures for each simulation. More information on persistent variables can be found in this documentation: https://www.mathworks.com/help/releases/R2021b/matlab/ref/persistent.html
  • Use the hold function so that the signal data from each time step accumulates on the plot instead of overwriting the previous data.
Below is an example code snippet illustrating these steps:
function plot3D(x, y, z)
% Specify the functions to be run in MATLAB
coder.extrinsic('plot3');
coder.extrinsic('hold');
coder.extrinsic('grid');
coder.extrinsic('xlabel');
coder.extrinsic('ylabel');
coder.extrinsic('zlabel');
coder.extrinsic('title');
persistent h;
if isempty(h)
h = figure('Name', '3D Plot', 'NumberTitle', 'off');
end
% Plot the data
figure(h);
plot3(x, y, z, 'b.-');
hold on; % Keep the plot for subsequent data
grid on;
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('3D Trajectory');
end
Here is a screenshot of the result from an example model, showing the expected output:

类别

Help CenterFile Exchange 中查找有关 Simulink Functions 的更多信息

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by