I need help using the strrep for this code.
显示 更早的评论
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
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Code Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!