使用
x=-10:0.1:10
f=x+2
在基本的m文件中工作很好。
但是现在我试图用GUI绘制一个图,并输入一个函数。这会给我带来很多错误。当我有x集的范围时,有人能解释我如何给出y的值吗?
% --- Executes on button press in zimet.
function zimet_Callback(hObject, eventdata, handles)
% hObject handle to zimet (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
x=-10:0.1:10;
f=inline(get(handles.vdj,'string'))
y(x)=f
axes(handles.axes)
plot(x,y)
color=get(handles.listbox, 'value')
switch color
case 2
set(plot(x,y),'color', 'r')
case 3
set(plot(x,y),'color', 'g')
case 4
set(plot(x,y),'color', 'b')
end
style=get(handles.popupmenu, 'value')
switch style
case 2
set(plot(x,y), 'linestyle','--')
case 3
set(plot(x,y), 'linestyle','-.')
case 4
set(plot(x,y), 'linestyle',':')
end
rezgis=get(handles.grid, 'value')
switch rezgis
case 1
grid on
case 2
grid off
end
发布于 2017-04-01 15:37:02
注意,根据内联函数文档,这个函数将在以后的版本中删除;您可以使用anonymous functions
(参见下面)。
inline
函数需要输入一串字符,而get
函数以cellarray
的形式返回编辑框的文本,因此您必须使用char
函数来转换它。
而且,一旦生成了inline
对象,它就是您的函数,所以您必须直接使用它。
使用内联
您必须以这样的方式更改代码:
x=-10:0.1:10;
% f=inline(get(handles.vdj,'string'))
% y(x)=f
f=inline(char(get(handles.vdj,'string')))
y=f(x)
axes(handles.axes)
ph=plot(x,y)
使用匿名函数
通过这样使用匿名函数,您可以获得相同的结果:
x=-10:0.1:10;
% Get the function as string
f_str=char(get(handles.vdj,'string'))
% add @(x) to the string you've got
f_str=['@(x) ' f_str ];
% Create the anonymous function
fh = str2func(f_str)
% Evaluate the anonymous function
y=fh(x)
axes(handles.axes)
ph=plot(x,y)
编辑
您可以通过设置线条的颜色和样式来解决这个问题:
plot
的调用(它是绘图的句柄(参见上面的:ph=plot(x,y)
)set
的调用替换为绘图本身的句柄(如上面所示的ph
变量)来避免调用因此,要更改颜色和线条样式,请在switch
部分中:
set(ph,'color','r')
set(ph,'linestyle','--')
希望这能帮上忙
卡普拉
https://stackoverflow.com/questions/43158488
复制相似问题