MATLAB: Plotting external function in App GUI graph

appapp designerbuttonexternal functionguiMATLABplot

I've got a function which plots a simple sine wave called testgraph.m
I'd like to plot this function when a button is pressed in the app designer GUI i've made. I've managed to call up testgraph.m when the button is pressed (generating the plot in a separate figure window) but i'm struggling to find a way to link the UI axes graph within the GUI to the plotted graph by the function in my .m file.
I'd prefer not to include the code from the function itself in the app designer script as i'd like to keep it as clean as possible and just call in the external functions as needed.
Would anyone be able to point me in the right direction to solve this please?

Best Answer

Pass the axis handle into your testgraph() function so your external plotting function knows what axes to plot on.
It would look something like this
function ButtonPressFunction(app, event)
testgraph(app.UIAxes, . . .)
end
and in your external function,
function testgraph(h, . . .)
plot(h, . . .)
end
Update:
Without using axis handles
Make the app's axes handle accessible and current so that any newly plotted objects will be plotted to the App's axes.
1) Open the app in appdesigner. In Design View, from the Component Browser, select the main app figure at the top. In the Inpsector section below, go to Parent/Child and set HandleVisibility to 'on' or 'callback'. This step can also be done from within the code (see warning below).
2) Do the same for the axes within your app if needed (the default value may already indicate HandleVisibility 'on').
3) From within any callback function within the app, prior to plotting set the app's axes to current
axes(app.UIAxes)
% ^^^^^^^^^^ axis handle
4) call plotting function immediately afterward so that it uses the current axis.
Warning: Now your UIAxes will the accessible by any plotting function which may lead to accidentally clear the axes or making unintended changes to it.
To minimize that problem, set the app handle visibility programmatically before and after plotting.
% app.MyApp is the handle to your app figure
% app.UIAxes is the handle to your app axes
app.MyApp.HandleVisibility = 'on'; % or 'callback'

axes(app.UIAxes)
[ DO PLOTTING ]
app.MyApp.HandleVisibility = 'off'; % or 'callback'