how take a mathematical function from user

3 ビュー (過去 30 日間)
Ahmed Amin
Ahmed Amin 2021 年 5 月 8 日
コメント済み: Ahmed Amin 2021 年 5 月 8 日
How can i take F and G from the user to use them in a function if i have F=@(x,y) x./y;
and G=@(x) sqrt(x.^2+1); ?
  4 件のコメント
Ahmed Amin
Ahmed Amin 2021 年 5 月 8 日
i mean that in my origina code it is me who wite the function F and G in File.m like that but i wnat the user to enter the F and G insted of me to use them in Function
Ahmed Amin
Ahmed Amin 2021 年 5 月 8 日
ok but how can i use feval in my case ?

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

回答 (1 件)

Steven Lord
Steven Lord 2021 年 5 月 8 日
What do you mean when you say you want "the user to enter" the function in your comment?
Do you want the user to have to pass some thing into your function that lets your function call a function of their choosing? If so you want your user to define a function handle (which could be an anonymous function.)
f1 = @(x, y) x./y; % anonymous function
z1 = integral2(f1, 0, 1, 1, 2) % integral2 will call the function f with inputs of its choice
z1 = 0.3466
f2 = @sin; % regular function handle
z2 = integral(f2, 0, pi)
z2 = 2.0000
Or do you want to have the user enter the text of a function in say an edit box in a dialog or UI? In that case you should use str2func.
s = 'x./y';
f3 = str2func(['@(x, y)' s]); % make an anonymous function which is a function handle
z3 = integral2(f3, 0, 1, 1, 2)
z3 = 0.3466
% or
f4 = str2func('sin'); % make a regular function handle
z4 = integral(f4, 0, pi)
z4 = 2.0000
Or did you have a different meaning in mind? In this case, please explain what you want to do in more detail.

カテゴリ

Help Center および File ExchangeScope Variables and Generate Names についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by