Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

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

1 Ansicht (letzte 30 Tage)
Charles
Charles am 18 Apr. 2014
Geschlossen: MATLAB Answer Bot am 20 Aug. 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

Antworten (1)

Walter Roberson
Walter Roberson am 18 Apr. 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()

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by