Building symbolic expression with vars from vector

3 ビュー (過去 30 日間)
ludolfusexe
ludolfusexe 2024 年 5 月 13 日
コメント済み: ludolfusexe 2024 年 5 月 14 日
Is it possible, to build a symbolic expression with symbolic parameters/variables like in the minimal example below?
syms x y
syms j % index var
m = 10 % max index
p_j = sym('p', [m 2]) % symbolic parameter vector
phi = sym('phi', [m,1]) % symbolic vars
syms J_j(j) % helper expression
J_j(j) = sqrt((x-p_j(j,1))^2+(y-p_j(j,1))^2)*phi(j); % <-fails
J = symsum(J_j(j), j, 1, m) % final expression
The error is probably due to accessing a matrix.
I very much appreciate any response.
Many thanks in advance.

採用された回答

Paul
Paul 2024 年 5 月 13 日
編集済み: Paul 2024 年 5 月 13 日
Hi ludolfusexe,
It looks like the original code was attempting to use j as a index into an array, but symbolic variables are never allowed to be used as indices.
Here's the working code (I made m smaller to more easily see the final result)
syms x y p_jx p_jy phi_j
%m = 10;
m = 4;
p_j = sym('p', [m 2]);
phi = sym('phi', [m,1]);
J_j = sqrt((x-p_jx)^2+(y-p_jy)^2)*phi_j;
J = 0;
for j=1:m
tmp = subs(J_j,p_jx, p_j(j,1));
tmp = subs(tmp,p_jy, p_j(j,2));
tmp = subs(tmp,phi_j, phi(j) );
J = J + tmp;
end
J
J = 
Symbolic arrays support elementwise and other basic operations, which also support scalar expansion, just like standard numerical arrays. Hence, we can construct J as
J1 = sum(phi.*sqrt((x - p_j(:,1)).^2 + (y - p_j(:,2)).^2))
J1 = 
Check
isAlways(J1 == J)
ans = logical
1
  1 件のコメント
ludolfusexe
ludolfusexe 2024 年 5 月 14 日
Thank you for your reply, your solution is much more elegant than mine!

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

その他の回答 (1 件)

ludolfusexe
ludolfusexe 2024 年 5 月 13 日
syms x y p_jx p_jy phi_j
m = 10
p_j = sym('p', [m 2])
phi = sym('phi', [m,1])
J_j = sqrt((x-p_jx)^2+(y-p_jy)^2)*phi_j;
J = 0;
for j=1:m
tmp = subs(J_j,p_jx, p_j(j,1));
tmp = subs(tmp,p_jy, p_j(j,2));
tmp = subs(tmp,phi_j, phi(j) );
J = J + tmp;
end
J
That works.

カテゴリ

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

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by