how to plot from input (function)

조회 수: 9 (최근 30일)
Anwar Alm
Anwar Alm 2022년 4월 12일
답변: Geoff Hayes 2022년 4월 19일
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 ?

답변 (1개)

Geoff Hayes
Geoff Hayes 2022년 4월 19일
@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).

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by