0

I'm trying to calculate the derivative of a an edit text box (edit1) and display the answer in a static text box (text1). But it is just displaying numbers. What am I doing wrong?

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=-10:.1:10;
equation = get(handles.edit1, 'String');
y = eval(equation);
derive_func = diff(y);
set(handles.text1, 'String', derive_func);
plot(y);

GUI Image - As you can see, it plots the function, but returns with 3 lines of numbers when it tries to differentiate:

1 Answers1

1

You are seeing a conflict between two different uses of the overloaded function diff. The default builtin use is numeric differentiation, and you are applying the function to numeric variable y so you are getting numeric output.

What you seem to want to do is use diff from the symbolic math toolbox to diplay 5*x^4 and that requires that you tell matlab that you want to use the symbolic math toolbox by providing diff with the right input, usually a string.

I am using matlab R14 and a lot has changed in the sym toolbox with newer versions, but the following should work for you.

str = 'x^5';
diff(str,'x')

where str is the expression you want to differentiate symbolically. Note that in my version the sym toolbox is unhappy with the notation x.^5 and prefers x^5, I don't know how it might work on MuPad, but you may have to find a workaround to make sure that you feed MuPad (or whichever sym engine you are using) with a string it can handle.

edit

Earlier suggestions on the use of cd or addpath to control which version of overloaded function diff is used have been removed.

Buck Thorn
  • 5,024
  • 2
  • 17
  • 27
  • 1
    Don't tell people that they need to cd to a MATLAB toolbox directory to use it! This is very poor programming style. The search path is there for a reason. Learn to use it. –  Aug 17 '13 at 20:14
  • @woodchips Some clarification would be nice: what is the alternative you are suggesting. I attempted str2fun using the full path to the function but on my system it did not work as posted in the answer I link to. – Buck Thorn Aug 17 '13 at 20:50
  • You need to learn to use the path in matlab. Thus pathtool, addpath, rmpath, savepath, etc. –  Aug 17 '13 at 20:51