how to plot from input (function)

9 Ansichten (letzte 30 Tage)
Anwar Alm
Anwar Alm am 12 Apr. 2022
Beantwortet: Geoff Hayes am 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 ?

Antworten (1)

Geoff Hayes
Geoff Hayes am 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).

Community Treasure Hunt

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

Start Hunting!

Translated by