【问题标题】:Graphing with GUI使用 GUI 绘图
【发布时间】:2017-04-01 15:10:59
【问题描述】:

使用

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

【问题讨论】:

    标签: matlab graphing


    【解决方案1】:

    请注意,根据inline function documentation,此功能将在以后的版本中删除;你可以改用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)
    

    使用匿名函数

    这样使用anonymous functions也可以达到同样的效果:

    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,方法是将调用 plot 替换为绘图本身的句柄(ph 变量如上)

    因此,要更改颜色和线条样式,请在您的 switch 部分:

    set(ph,'color','r')
    set(ph,'linestyle','--')
    

    希望这会有所帮助,

    卡普拉'

    【讨论】:

    • 谢谢!但是,例如,如果我输入 x^2 ,它就不再起作用了。我必须把它理解为 .^2 我假设。有没有办法代替自己输入?
    • 我认为唯一的方法是您以正确的方式在文本框中定义函数。您可以在回调中添加一些代码来对字符串执行一些检查以验证它。
    • 我还编辑了答案:inline 函数将在 MatLab 的未来版本中删除。我使用anonymous functions 添加了一个可行的解决方案。
    • 谢谢!如果你不介意..也许你也知道为什么使用列表框、弹出菜单等。我已经设置了一个来设置图形的样式,另一个用于颜色。最后一个覆盖第一个。例如,我检查绿色和虚线样式。它将是蓝色(默认)和点。我怎样才能阻止它覆盖?
    • 不清楚您所说的“覆盖”是什么意思。您应该发布这部分代码,否则很难识别可能的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 2021-12-27
    相关资源
    最近更新 更多