Differentiation with str2sym

8 ビュー (過去 30 日間)
Gabriele Ansaldo
Gabriele Ansaldo 2020 年 5 月 11 日
コメント済み: Walter Roberson 2020 年 6 月 15 日
Hello,
I am trying to differentiate usinf str2sym but i seem to get some errors.
Here is the code:
clear all
y(1) = str2sym ('x(1)');
y(2) = str2sym ('x(2)');
f = y(1) + y(2);
diff(f, y(1))
This is the error i get
Error using sym/diff (line 70)
Second argument must be a variable or a nonnegative integer specifying the number of
differentiations.
Error in prove (line 8)
diff(f, y(1))

回答 (1 件)

Walter Roberson
Walter Roberson 2020 年 5 月 12 日
The error message is correct. You can only differentiate with respect to an entire variable, not with respect to a function call like x(1)
x = sym('x', [1 2]);
y(1) = str2sym ('x(1)');
y(2) = str2sym ('x(2)');
y = mapSymType(y, 'x', @(e) x(children(e)));
f = y(1) + y(2);
diff(f, y(1))
  2 件のコメント
Gabriele Ansaldo
Gabriele Ansaldo 2020 年 5 月 12 日
Thanks! However, its not exactly what I meant. If I run the code you wrote and for instance i set f = y(1)^2 +y(1) this happens:
clear all
x = sym('x', [1 2]);
y(1) = str2sym ('x(1)');
y(2) = str2sym ('x(2)');
y = mapSymType(y, 'x', @(e) x(children(e)));
f = y(1)^2+ y(2);
diff(f, y(1))
This is the result
ans =
2*x1
where i actually expected it to be
ans =
2*x(1)
with the brackets around the one.
Walter Roberson
Walter Roberson 2020 年 6 月 15 日
x = sym('x', [1 2]);
y(1) = str2sym ('x(1)');
y(2) = str2sym ('x(2)');
Y = mapSymType(y, 'x', @(e) x(children(e)));
f = Y(1)^2 + Y(2);
df = diff(f, Y(1));
df = subs(df, x, y);

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by