Minimize array of functions witn multiple variables

17 次查看(过去 30 天)
Hello, I am new in Matlab. I have array y with size 3 x 3, and in each cell of this array I have function y(i, j) ( i = 1, 2, 3; j = 1, 2, 3) that depends on 3 variables: a, b, c
I would like minimize function myfun=@(a, b, c)(D - y); D is numerical array like D = [ 1 1 1; 1 1 1; 1 1 1;]
I tried that:
syms a b c;
y=zeros(3,3);
y=sym(y);
t = [ 1 ; 2; 3;];
D = [ 1 1 1; 1 1 1; 1 2 3; ]
for i=1:1:3
for j=1:1:3
y(i,j)=@(a, b, c)a.*t(j)+ b + c;
y(i,j)=@(a, b, c)a + b.*t(j) + c;
y(i,j)=@(a, b, c)b.*t(j) + c.*t(j).*t(j) + a;
end
end
f0 = [1, 1, 1];
myfun=@(a, b, c)(D - y);
a = fminsearch(@myfun,f0)
But fminsearch doesn't work in this case
Thanks for the help!

回答(1 个)

Deepak
Deepak 2024-11-4,14:17
From my understanding, you have written MATLAB Code to optimize the parameters (a), (b), and (c) to minimize the difference between a 3x3 matrix of functions and a constant matrix (D) using “fminsearch”. However, you are facing difficulty in defining unique functions in each matrix cell and formulating a scaler objective function for optimization.
To resolve the issue, we can uniquely define each element of the function matrix(y) within the loop, preventing overwriting. Also, we can convert symbolic expressions to a function handle using “matlabFunction”, allowing numerical evaluations. Finally, the objective function can be modified to return a scalar by calculating the sum of squared differences between the evaluated function matrix and the constant matrix (D).
Please find below the update MATLAB code with the required changes:
syms a b c;
t = [1; 2; 3];
D = [1 1 1; 1 1 1; 1 2 3];
y = sym(zeros(3, 3));
for i = 1:3
for j = 1:3
if i == 1
y(i, j) = a * t(j) + b + c;
elseif i == 2
y(i, j) = a + b * t(j) + c;
else
y(i, j) = b * t(j) + c * t(j)^2 + a;
end
end
end
% Convert symbolic matrix to function handle
y_func = matlabFunction(y, 'Vars', [a, b, c]);
% Objective function
myfun = @(params) sum(sum((D - y_func(params(1), params(2), params(3))).^2));
f0 = [1, 1, 1];
% Use fminsearch to minimize the objective function
a = fminsearch(myfun, f0);
disp('Optimized parameters:');
disp(a);
Please find attached the documentation of functions used for reference:
I hope this assists in resolving the issue.
  1 个评论
Walter Roberson
Walter Roberson 2024-11-4,19:03
If you use
y_func = matlabFunction(y, 'Vars', {[a, b, c]});
then you can use
myfun = @(params) sum(sum((D - y_func(params)).^2));

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by