Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

How can I prevent the user to use a word (like Hello) in the function?

1 vue (au cours des 30 derniers jours)
Charles
Charles le 18 Avr 2014
Clôturé : MATLAB Answer Bot le 20 Août 2021
How can I prevent the user to use a word (like Hello) in the function? the function is a string (numbers and words) so... How can I prevent them to use other words?
thanks!
e.x.:
function x = false_position(f,a,b,kmax,tol)
for i=1:kmax
x0=a;
x1=b;
x2(i)=x0-(x1-x0)/(f(x1)-f(x0))*f(x0);
if (f(x2(i))>0)
b=x2(i);
else a=x2(i);
end
fprintf('\n x2=%.4f \n, f(x2)=%.4f',x2 (i), f(x2(i)))
x=x2(i);
end
for i=1:kmax
erro(i)=x-x2(i);
end

Réponses (1)

Walter Roberson
Walter Roberson le 18 Avr 2014
You should do that kind of validation before you call false_position.
If the function is a string then your reference to f(x1) is going to be a string access. If you want to evaluate the string given a value, you should be switching to function handles (see str2func()) or you should use feval()
It is not clear that you should be forcing the user to avoid all strings other than the variable name: suppose the user wants to use sin() or other similar operations?
Perhaps you should be looking at try/catch instead.
But if you insist... have a look at symvar()

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by