How to define a function?

12 ビュー (過去 30 日間)
Pauline Li
Pauline Li 2017 年 11 月 2 日
コメント済み: Rik 2017 年 11 月 2 日
I am trying to define DY, which is the derivative of Y by using the "diff" command and "matlabFunction()" in order to evaluate Y(0)=1 and DY(0)=2 by using "dsolve". I am having trouble with the "diff" command, the message "Undefined function 'diff' for input arguments of type 'function_handle'." keeps coming up. I have already tried rewriting this multiple ways. Any help would be greatly appreciated. Thank you.
DE = D2y + 4*Dy + 4*y == 0
Y = matlabFunction(y)
DY = diff(Y)
DY = matlabFunction(DY)
y = dsolve(DE, Y(0)==1,DY(0)==2)

採用された回答

Star Strider
Star Strider 2017 年 11 月 2 日
編集済み: Star Strider 2017 年 11 月 2 日
Take the derivative as a symbolic object, not a function handle:
syms y(t)
Dy = diff(y,t); D2y = diff(y,t,t);
DE = D2y + 4*Dy + 4*y == 0
y = dsolve(DE, y(0)==1, Dy(0)==2)
Y = matlabFunction(y)
DY = diff(y)
You can then use matlabFunction to create an anonymous function from ‘DY’.
EDIT
This code:
syms y(t)
Dy = diff(y,t); D2y = diff(y,t,t);
DE = D2y + 4*Dy + 4*y == 0;
y = dsolve(DE, y(0)==1, Dy(0)==2);
Y_fcn = matlabFunction(y)
DY = diff(y);
DY_fcn = matlabFunction(DY)
produces these anonymous functions:
Y_fcn = @(t)exp(t.*-2.0)+t.*exp(t.*-2.0).*4.0
DY_fcn = @(t)exp(t.*-2.0).*2.0-t.*exp(t.*-2.0).*8.0;

その他の回答 (1 件)

Rik
Rik 2017 年 11 月 2 日
What are you trying to do? If you don't convert the symbolic function to an anonymous function, it works just fine.
%clear is just for education purposes, use functions to keep your workspace clean.
%Needing clear is a sign of bad programming.
clear D2y DE Dy DY sol t y Y
syms y(t)
Dy = diff(y,t); D2y = diff(y,t,t);
DE = D2y + 4*Dy + 4*y == 0;
sol = dsolve(DE, y(0)==1, Dy(0)==2);
Y=y;%Y =matlabFunction(y);
DY = diff(Y);
%DY = matlabFunction(DY);
y = dsolve(DE, Y(0)==1,DY(0)==2);
disp(y)
disp(sol)
  2 件のコメント
Pauline Li
Pauline Li 2017 年 11 月 2 日
I have revised the code given, what I am trying to do is evaluate Y(0)=1 and DY(0)=2 using matlabFunction. The part I have trouble with is the DY=diff(Y) and DY=matlabFunction(DY).
Rik
Rik 2017 年 11 月 2 日
If you want to run dsolve(DE, Y(0)==1,DY(0)==2) or diff(Y), Y and DY must be symbolic functions. It is as simple as that. If that is not what you are trying to solve, you need to explain what function it is you want to solve.
Conversion to anonymous function is something you can do, but afterwards you can't differentiate it.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by