changing expression to function
1 次查看(过去 30 天)
显示 更早的评论
i have the values for a=[],b=[],reg1=[],reg2=[], i want to change the expr = expr + w(r2) * (sqrt((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) - w(r1) * (sqrt((x(r2)-a(i))^2 + (y(r2)-b(i))^2)) into a function.
expr = optimexpr;
for i = 1:numel(a)
r1 = reg1(i);
r2 = reg2(i);
%syms expr x y w
disp(expr)
expr = expr + w(r2) * (sqrt((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) - w(r1) * (sqrt((x(r2)-a(i))^2 + (y(r2)-b(i))^2));
is the following method is correct:
syms expr x y w
disp(expr)
ht=matlabFunction(expr);
Also, if I want to perform minimization of the expr = expr + w(r2) * (sqrt((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) - w(r1) * (sqrt((x(r2)-a(i))^2 + (y(r2)-b(i))^2)), after changing into a function, please suggest a way
0 个评论
回答(1 个)
Dyuman Joshi
2024-1-15
You will have to define x and y as symbolic variables first -
%Random values for example
a = rand(1,10);
b = rand(1,10);
reg1 = randperm(n);
reg2 = randperm(n);
w = randperm(n);
n = numel(a);
syms x y [1 n]
size(x)
size(y)
expr = 0;
for i = 1:numel(a)
r1 = reg1(i);
r2 = reg2(i);
expr = expr + w(r2) * (sqrt((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) - w(r1) * (sqrt((x(r2)-a(i))^2 + (y(r2)-b(i))^2));
end
%display the expression
disp(expr)
%Convert the expression to a function handle with vector inputs arguments
F = matlabFunction(expr, "Vars", {x, y})
2 个评论
Dyuman Joshi
2024-1-15
Do you have the Symbolic Math Toolbox licensed and installed?
Type "ver" and see if you have it installed
ver
If you don't have it installed, run this code and see if you have the Toolbox licensed or not -
[status,errmsg] = license('checkout','Symbolic_Toolbox')
If status is 1, you have it licensed. You can download and install the toolbox from the Add-ons.
If status is 0, you will need to purchase the toolbox.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Assumptions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!