Apply diff to function handle

5 ビュー (過去 30 日間)
William Alberg
William Alberg 2020 年 5 月 9 日
コメント済み: William Alberg 2020 年 5 月 10 日
Hello!
I have a string input that i transform into a symbolic equation. I need to translate "D(___)" into differentiation, but i can't make it work
syms t x x(t) D(x)
eq_str = 'D(x)'; % input string equation
eq_sym = str2sym(eq_str); % transform equation to symbolic
eq_sym2 = subs(eq_sym,x,x(t)) % make x into a function of time
Dif = @(f) diff(f,t) % make Dif into a function handle
subs(eq_sym2,D,Dif) % returns 0, i want "diff(x(t),t)"
I dont think that "subs" is the correct way to do it, but i have not been able to find any other way
Thanks!

採用された回答

Walter Roberson
Walter Roberson 2020 年 5 月 10 日
syms t x(t) D(x) x1(t) x2(t)
eq_str = '0 == x1 + D(x2)'; % example of input string equation
eq_sym = subs(str2sym(eq_str)); % transform equation to symbolic
eq_str2 = '0 == x1 + D(D(x2))'; % example of input string equation
eq_sym2 = subs(str2sym(eq_str2)); % transform equation to symbolic
eq_sym = mapSymType(eq_sym, 'D_Var', @fixD);
disp(eq_sym);
eq_sym2 = mapSymType(eq_sym2, 'D_Var', @fixD);
disp(eq_sym2)
function in = fixD(in)
syms t
if hasSymType(in, 'D_Var')
in = diff(mapSymType(children(in), 'D_Var', @fixD),t);
end
end
  1 件のコメント
William Alberg
William Alberg 2020 年 5 月 10 日
This solves all my problems. Thank you!

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2020 年 5 月 9 日
>> syms x t x(t)
>> dxdt = diff(x, t)
dxdt(t) =
diff(x(t), t)
To substitute a function in for x(t):
>> subs(dxdt, x, sin(t))
ans(t) =
cos(t)
  7 件のコメント
Walter Roberson
Walter Roberson 2020 年 5 月 10 日
ch1 = children(eq_sym);
ch2 = children(eq_sym(2));
symFunType(ch2(2))
ch2(2) displays as D(x2) but symFunType shows that it is D_Var that is the function.
Walter Roberson
Walter Roberson 2020 年 5 月 10 日
I am running into some difficulties in generalizing the solution. Something like this cries out for a recursive function, but you have to be able to do the subs() at arbitrary nesting level then, which is a problem because the subs() has to be done in the current workspace...

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

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by