how to plot from input (function)

1 view (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
figure('MenuBar','none','Name','test','NumberTitle','off','Position',[200,200,800,500]);
Text1 = uicontrol('Style','Text','String','Enter a function to draw','Position',[590,300,120,20],...
'HorizontalAlignment','left');
GUI.h1 = uicontrol('style','Edit','string','','Units','normalized','Position',[0.6 0.5 0.38 0.08],...
'backgroundcolor','w',...
'Tag','EditField');
Draw = uicontrol('Style','PushButton','String','Draw','Position',[620,200,60,20],...
'CallBack',{@func_compute,GUI.h1,gca});
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);
plot(x,y(x));
end
Note how the @(x) is prepended to the string that we obtain from the edit field (see anonymous functions for details).

Community Treasure Hunt

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

Start Hunting!