Borrar filtros
Borrar filtros

Evalaute a string left to right

2 visualizaciones (últimos 30 días)
Bob Whiley
Bob Whiley el 19 de Feb. de 2015
Editada: James Tursa el 19 de Feb. de 2015
Given an input string that represents a function (like 'f(x) = x^2 +2/2x+3') and a input value (like x=2), how can I evaluate something of this form from left to right (ignoring the pemdas rules). I think I should use some loop for this

Respuestas (1)

James Tursa
James Tursa el 19 de Feb. de 2015
Editada: James Tursa el 19 de Feb. de 2015
If you will accept evaluating this all at once, here is one way to do it (only works if the rhs is legit MATLAB syntax, which your example isn't):
>> s = 'f(x) = x^2 + 2/(2*x) + 3'
s =
f(x) = x^2 + 2/(2*x) + 3
>> e = find(s=='=',1)
e =
6
>> p = find(s=='(',1)
p =
2
>> f = str2func(['@' s(p:e-1) s(e+1:end)])
f =
@(x)x^2+2/(2*x)+3
>> f(2)
ans =
7.5000
If you really need to evaluate it piecemeal for some reason, that is going to be much more involved because you will need to code up a parser with operator precedences etc.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by