How do I evaluate a user-input trigonometric function?

3 ビュー (過去 30 日間)
Carolyn Rafael
Carolyn Rafael 2017 年 11 月 21 日
編集済み: Stephen23 2023 年 1 月 8 日
I'm not entirely sure how to explain this but here is the question:
My main issue is I don't know how to use eval when using a user-input trigonometric function. (I don't really need help with the graphing part).
This is my attempt:
n = input('Enter a positive number n: ');
x = linspace(0, n, 1000)
trigfunc = input('Enter a trigonometric function: ', 's');
eval('trigfunc(x)')
  1 件のコメント
Stephen23
Stephen23 2017 年 11 月 21 日
編集済み: Stephen23 2023 年 1 月 8 日
"Then, by using the function eval..."
Ugh, why teach impressionable students such awful programming practices?
Why not simply use a basic look-up, or str2func() or feval() ?

サインインしてコメントする。

採用された回答

Birdman
Birdman 2017 年 11 月 21 日
n=input('enter a pos num\n');
x=linspace(0,n,1000);
trigfunc=input('Enter 1=sin(x), 2=cos(x), 3=tan(x), 4=cot(x)\n');
if(trigfunc==1)
y=sin(x);
plot(x,y);title(['sin(x) from [0 ' ,num2str(n), ']'])
elseif(trigfunc==2)
y=cos(x);
plot(x,y);title(['cos(x) from [0 ' ,num2str(n), ']'])
elseif(trigfunc==3)
y=tan(x);
plot(x,y);title(['tan(x) from [0 ' ,num2str(n), ']'])
elseif(trigfunc==4)
y=cot(x);
plot(x,y);title(['cot(x) from [0 ' ,num2str(n), ']'])
end

その他の回答 (2 件)

Stephen23
Stephen23 2017 年 11 月 21 日
編集済み: Stephen23 2017 年 11 月 21 日
It is simpler to use str2func:
num = str2double(input('End value of vector: ','s'));
fun = str2func(input('Trig function (e.g. sin, cos, etc.): ','s'));
x = linspace(0,num,1000);
y = fun(x);
plot(x,y)
To which it is also easy to add input checking, etc.

Prathap
Prathap 2022 年 12 月 26 日
Plot the trigonometric curve as a function of time. Hint: Use ‘eval’ function within the script to accept different trigonometric functions (e.g., sin, cos, tan, etc.).
  1 件のコメント
Stephen23
Stephen23 2022 年 12 月 26 日
Much Better Hint: Use STR2FUNC() function within the script to accept different trigonometric functions:

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by