Frage

Hello I am new to MATLAB , I wanted to know how can I make my string into function . I want to access the function as a string from user in standard Matlab format (e.g exp(-10*X)-sin(pi*X)-2*tanh(X) ) Here X is the variable. Then I want to replace 'X' with 'low' and 'high' variables to calculate value of function at these limits. I have used 'strrep' for this purpose. I am getting the following errors 1)Undefined function or variable 'X'. 2) I cannot see whether 'X' was replaced with 'low' and 'high'.

Any help will be truly appreciated. Below is my code.

    high=input('Upper Limit of the Interval : ');

    low=input('\nLower Limit of the interval : ');

    usr_funct=input('Enter The Function in standard Matlab Format.\nEnter "X" for the
    variable and * for multiply \n');    % Example exp(-10*X)-sin(pi*X)-2*tanh(X);

    middle = (low+high)/2;

    Flow =strrep(usr_funct, 'X', 'low');
    Fhigh =strrep(usr_funct, 'X', 'high');

   sprintf('Flow '); % This was to check if 'X' was replaced with 'low'. It is not printing anything
War es hilfreich?

Lösung

I think that you are looking for the eval function. That will evaluate a string as matlab code.

Here is an example:

str = 'exp(-10*X)-sin(pi*X)-2*tanh(X)' ; % let str be your math expression
high = 10; % Ask the user
low = -5; % Ask the user

% Now we evaluate for High and Low
X = low; % We want to evaluate for low
ResultLow = eval(str); % That will return your value for X = low
X = high; % We want to evaluate for low
ResultHigh = eval(str); % That will return your value for X = high

Andere Tipps

Use:

usr_funct=input('Enter The Function...', 's');

This will return the entered text as a MATLAB string, without evaluating expressions.

1) Undefined function or variable 'X'

If you look at the documentation for input, it says that by default, it evaluates the expression. You need to add a second argument of 's' for it to just save a string.

2) I cannot see whether 'X' was replace with 'low' and 'high'

You should type sprintf(Flow) instead of sprintf('Flow'). The latter will just output "Flow" onto the screen while the former will output the value of Flow.

Finally, the eval function may be of use later on when you actually want to evaluate your expression.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top