Search code examples
matlabgraphing

Graphing with GUI


Using

x=-10:0.1:10
f=x+2

in basic m-file works fine.

But now I am trying to draw a plot using GUI, and by inputing a function. It gives me bunch of errors. Could anyone explain how I can give values to the y when I have the range of x set?

% --- 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

Solution

  • Notice that according to the inline function documentation this function will be removed in future release; you can use, instead, anonymous functions (see below).

    The inline function require, as input a string of characters while the get function returns the text of the edit box as a cellarray, therefore you have to convert it using the char function.

    Also, once you have generated the inline object, it is you function, so you have to use it directly.

    Using inline

    You have to change your code this way:

    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)
    

    Using an anonymous function

    You can achieve the same result by using anonymous functions this way:

    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)
    

    Edit

    You can fix the problem with the setting of the line color and style this way:

    • modify the call to plot by adding the return value (it is the handle to the plot (see above: ph=plot(x,y))
    • chance the calls to set by replacing the call to plot with the handle of the plot itself (the ph variable as above)

    So, to change the color and the line style, in your switch section:

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

    Hope this helps,

    Qapla'