Borrar filtros
Borrar filtros

Building symbolic expression with vars from vector

1 visualización (últimos 30 días)
ludolfusexe
ludolfusexe el 13 de Mayo de 2024
Comentada: ludolfusexe el 14 de Mayo de 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.

Respuesta aceptada

Paul
Paul el 13 de Mayo de 2024
Editada: Paul el 13 de Mayo de 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 comentario
ludolfusexe
ludolfusexe el 14 de Mayo de 2024
Thank you for your reply, your solution is much more elegant than mine!

Iniciar sesión para comentar.

Más respuestas (1)

ludolfusexe
ludolfusexe el 13 de Mayo de 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.

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by