Reputation: 329
I have this function which takes a string as an input.
for example it takes handles.f = 'x^2'
but I want handles.f = x^2 so that later I'll be able to do f(x) = handles.f
function edit1_Callback(hObject, eventdata, handles)
handles.f = (get(hObject,'String'))
handles.f
area = rect(handles.f,handles.u,handles.l,handles.n)
guidata(hObject,handles)
Function:
function [ s ] = rect( f,u,l,n )
syms x;
f(x) = f;
h =(u-l)/n
z = l:h:u;
y = f(z)
s = 0;
for i=1:n
s = s+y(i);
end
s = h*s;
end
When i call this function from command prompt like this: rect(x^2,5,1,4)
It works fine But it gives error when I call this from gui.
This is the error I get:
Error using sym/subsindex (line 1558)
Indexing input must be numeric, logical or ':'.
Error in rect (line 8)
f(x) = f;
Upvotes: 0
Views: 107
Reputation: 104493
This goes against any advice I give myself, but if you want to do what you're asking, you'll need to use eval
. This converts any string that you input into it and it converts it into a command in MATLAB for you to execute. If I am interpreting what you want correctly, you want to make an anonymous function that takes in x
as an input.
Therefore, you would do this:
handles.f = eval(['@(x) ' get(hObject,'String')]);
This takes in the string stored in hObject
, wraps it into an anonymous function, and stores it into handles.f
. As such, you can now do:
out = handles.f(x);
x
is an input number. This is one of the few cases where eval
is required. In general, I would not recommend using it because when code gets complicated, placing a complicated command as a string inside eval
reduces code readability. Also, code evaluated in eval
is not JIT accelerated... and it's simply bad practice.
Luis Mendo recommends doing str2func
to avoid eval
... which is preferable (whew!).
So do:
handles.f = str2func(['@(x) ' get(hObject,'String')]);
Upvotes: 1