Building symbolic expression with vars from vector

3 次查看(过去 30 天)
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-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 CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by