How to evaluate a function that has been saved to a variable

1 回表示 (過去 30 日間)
Eth
Eth 2021 年 5 月 13 日
コメント済み: Walter Roberson 2021 年 5 月 13 日
I have a function:
f = @(x) 2*tanh(x/2)
I'm taking the 1,2,3 derivatives of
d1 = diff(f(x))
d2 = diff(f(x),2)
d3 = diff(f(x),3)
I want to plot them now but not sure how to do this. If I try the following it gives me an error:
x = -1:0.01:1;
plot(x, d1(x))
How do you plot them if they are stored in a variable? or evaluate them?
  2 件のコメント
Adam Danz
Adam Danz 2021 年 5 月 13 日
> How do you plot them if they are stored in a variable? or evaluate them?
Your example uses values stored in a variable so I'm not sure what you're asking.
Don't forget that d1 will have 1 less value than x since you're differentiating, d2 will have 2 less values, etc.
Eth
Eth 2021 年 5 月 13 日
編集済み: Eth 2021 年 5 月 13 日
Hi @Adam Danz I can plot the function with no issues as:
plot(x,f(x))
But when I try to plot the the derivatives as:
plot(x,d1(x))
I get the error:
Array indices must be positive integers or logical values.
Error in sym/subsref (line 909)
R_tilde = builtin('subsref',L_tilde,Idx);

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

採用された回答

Walter Roberson
Walter Roberson 2021 年 5 月 13 日
%provided that x is symbolic
d1(x) = diff(f(x))
d2(x) = diff(f(x),2)
d3(x) = diff(f(x),3)
  2 件のコメント
Eth
Eth 2021 年 5 月 13 日
Thank You!
Walter Roberson
Walter Roberson 2021 年 5 月 13 日
f = @(x) 2*tanh(x/2)
f = function_handle with value:
@(x)2*tanh(x/2)
syms x
d1(x) = diff(f(x))
d1(x) = 
d2(x) = diff(f(x),2)
d2(x) = 
d3(x) = diff(f(x),3)
d3(x) = 
simplify(d2(2))
ans = 
Looks fine to me.
If you are expecting decimal values, then use vpa()

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

その他の回答 (1 件)

David Hill
David Hill 2021 年 5 月 13 日
syms x;
f = 2*tanh(x/2);
d1 = diff(f);
d2 = diff(f,2);
d3 = diff(f,3);
fplot(f,[-1,1]);
hold on;
fplot(d1,[-1,1]);
fplot(d2,[-1,1]);
fplot(d3,[-1,1]);

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by