Effacer les filtres
Effacer les filtres

Building symbolic expression with vars from vector

1 vue (au cours des 30 derniers jours)
ludolfusexe
ludolfusexe le 13 Mai 2024
Commenté : ludolfusexe le 14 Mai 2024
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.

Réponse acceptée

Paul
Paul le 13 Mai 2024
Modifié(e) : Paul le 13 Mai 2024
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 commentaire
ludolfusexe
ludolfusexe le 14 Mai 2024
Thank you for your reply, your solution is much more elegant than mine!

Connectez-vous pour commenter.

Plus de réponses (1)

ludolfusexe
ludolfusexe le 13 Mai 2024
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.

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by