Strrep doesn't work in Matlab to enable String function

Hello I'm new to MATLAB, I wanted to know how can I render my string in a function . I want to access a function as a string from a user in standard Matlab format (for example exp(-10*X)-sin(pi*X)-2*tanh(X)

). Here X is a variable. Then I want to replace "X" with "low" and "high" variables in order to calculate the value of the function within those limits. I have used 'strrep' for this purpose. I am getting the following errors: 1) Undefined function or variable 'X'. 2) I can't see if "X" is replaced with "low" and "high".

Any help would 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



source to share

3 answers

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

Here's 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





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 it evaluates the expression by default. You need to add the second argument 's' so that it will just store the string.

2) I can't see if I replaced "X" with "low" and "high"

You must enter sprintf(Flow)

instead sprintf('Flow')

. The latter will simply print "Stream" to the screen, while the former will output the stream value.

Finally, the function eval

can be used later when you really want to evaluate your expression.



All Articles