Info

この質問は閉じられています。 編集または回答するには再度開いてください。

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

1 回表示 (過去 30 日間)
Charles
Charles 2014 年 4 月 18 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
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

回答 (1 件)

Walter Roberson
Walter Roberson 2014 年 4 月 18 日
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()

製品

Community Treasure Hunt

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

Start Hunting!

Translated by