Search code examples
matlabgraphplotreal-timesimulink

Plotting inside Matlab Function Block for real time signals in Simulink


I have a simulation running on Simulink and output signals change during simulation. I want to plot them at every step. What I can do is to use to Workspace blocks to transfer them to Matlab, but then I can only plot after the simulation finishes. I would like to plot the value at every instant of the simulation.

What I tried:

Create a figure in advance as: figure(1) and plot a static graph on it. Then I use

Matlab function inside Simulink :

function fcn(x,y)
coder.extrinsic('plot')
plot(x,y,'s','Markersize',8,'MarkerFaceColor','g','erasemode','background')

Where x and y are my signals as input to matlab function block. However this results in plotting x and y in every timestep, but I would like to plot only the last value of the signal on the figure and delete the previous ones, in other words refresh the plot so that it is going to act as an animation. How can I achieve that? Thanks in advance


Solution

  • I think your code should work, with a few minor modifications:

    I would do the following if I were you:

    In the model callbacks, define your figure in the InitFcn callback:

    fig_h = figure;
    ax_h = axes;
    set(ax_h,'Xlim',[0 12],'YLim',[0 12]) % or whatever axes limits you want
    

    Then in your MATLAB Function block:

    function fcn(x,y)
    %#codegen
    coder.extrinsic('plot')
    plot(x,y,'s','Markersize',8,'MarkerFaceColor','g','erasemode','background')
    set(gca,'XLim',[0 12],'Ylim',[0 12]) % or whatever axes limits you want