0

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;

1 Answer 1

1

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.


Edit

Luis Mendo recommends doing str2func to avoid eval... which is preferable (whew!).

So do:

handles.f = str2func(['@(x) ' get(hObject,'String')]);
Sign up to request clarification or add additional context in comments.

9 Comments

Works here. @rayryeng, you could avoid eval by using str2func: handles.f = str2func(['@(x) ' handles.f])
@Luis Mendo I've tried that as well :( . but its not working.
@LuisMendo - Ah very nice. Thanks for the tip!
@user4129542 - This statement is nonsense: f(x) = f; What exactly are you trying to do at this line?
I've given an example of how i call this function from command window
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.