I need help using the strrep for this code.

1 view (last 30 days)
here are the three test cases. My question is how do I use strrep to replace the x of that function. The thing is it doesn't have to be x it can be anything but the basic layout is alway going to be functionName(varName) =
[val1] = ugaFunc('f(x) = 2*x^3', 5)
[val2] = ugaFunc('veloc(pos) = 2 / pos ^ 2 - 3', 0.5)
[val3] = ugaFunc('f(var_name) = 4 * (3 / var_name)^var_name-10*var_name',3.14)
function answer = hat(str, val)
% replace the input function with the value you want
a = strrep(str, ' ', 'val');
[b c] = strtok(a, '=');
[d e] = strtok(c, '0123456789 ');
% first number
[answer rest]= strtok(, '+-*/^');
answer = str2num(answer);
% a while loop to get a number and an operator each time
while (length(rest) ~= 0)
[operator rest]= strtok(rest, '0123456789 ');
[num rest] = strtok(rest, '+-*/^ ');
num = str2num(num);
% do the math
switch operator
case '+'
answer = answer + num;
case '-'
answer = answer - num;
case '*'
answer = answer .* num;
case '/'
answer = answer ./ num;
case '^'
answer = answer .^ num;
end
end
end

Accepted Answer

Guillaume
Guillaume on 19 Feb 2015
Edited: Guillaume on 19 Feb 2015
You haven't said what you want to replace it with. The value specified in the second argument of your hat function?
In any case, to find the name of the variable, use regular expressions. For example, assuming a simple grammar where the function name is exclusively letters, the following would extract the variable name:
varname = regexp(str, '(?<=[A-Za-z]+\().*?(?=\))', 'match', 'once')
Note that there are many possible expression leading to the same result. The above looks for the shortest (lazy match) sequence of any characters (the .*?) immediately following (the (?<=....) one or more letters (the [A-Za-z]+) plus a bracket (the \(|) and immediately preceding (the |(?=...)) a closing bracket (the \)).
You can then replace the varname in the rest of the expression by the value with strrep or regexprep
newexpr = strrep(str, varname, num2str(val)); %is this what you want?
  7 Comments
Guillaume
Guillaume on 19 Feb 2015
Oh, for Pete's sake, try the code. It makes no assumption on what's inside the brackets.
replacevar = @(expr, value) strrep(expr, regexp(expr, '(?<=[A-Za-z]+\().*?(?=\))', 'match', 'once'), num2str(value));
>>replacevar('f(x) = 2*x^3', 5)
ans =
f(3) = 2*3^3
>>replacevar('veloc(pos) = 2 / pos ^ 2 - 3', 0.5)
ans =
veloc(0.5) = 2 / 0.5 ^ 2 - 3
>>replacevar('f(var_name) = 4 * (3 / var_name)^var_name-10*var_name',3.14)
ans =
f(3.14) = 4 * (3 / 3.14)^3.14-10*3.14
Kratos
Kratos on 19 Feb 2015
It worked. Thank you for your time.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!