how to plot from input (function)

13 views (last 30 days)
Anwar Alm
Anwar Alm on 12 Apr 2022
Answered: Geoff Hayes on 19 Apr 2022
This is my code so far
function gui01
Text1 = uicontrol('Style','Text','String','Enter a function to draw','Position',[590,300,120,20],...
GUI.h1 = uicontrol('style','Edit','string','','Units','normalized','Position',[0.6 0.5 0.38 0.08],...
Draw = uicontrol('Style','PushButton','String','Draw','Position',[620,200,60,20],...
set( gca, 'DataAspectRatioMode', 'auto' )
set(gca,'Position',[0.04, 0.15, 0.5 0.74]);
set(gca, 'XLim',[-2,5]);
set(gca, 'YLim',[-2,5]);
x = linspace(0,2*pi,150);
function func_compute(~,~,InHandle,OutHandle)
y = get(InHandle,'String');
n = str2double(y);
OutHandle = plot([x,n]);
what I want is to write a function like 3.*x in the text box then it will assigne the function to the varible y and finally it will plot x and y on the axes displaied after pressing draw how can I do it ?

Answers (1)

Geoff Hayes
Geoff Hayes on 19 Apr 2022
@Anwar Alm - you could use str2func to convert the function string to a function handle and then evaluate in your code. In this case, the callback would be changd to
function func_compute(~,~,hEditField,hAxes)
y = str2func(['@(x)' get(hEditField,'String')]);
n = str2double(y);
Note how the @(x) is prepended to the string that we obtain from the edit field (see anonymous functions for details).


Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!