How to perform double summation using lsqnonlin
Show older comments
I understand that lsqnonlin does the sum of squares of a vector defined. BUt how exactly does it perform a double summation?
I am trying to obtain the min for two 3D vectors. the vector defined isn't getting optmized as I would expect.
14 Comments
Askic V
on 14 Dec 2022
You could start by providing code with example and expected result. There is a better chance to get help that way.
Akella Kartik
on 14 Dec 2022
Edited: Akella Kartik
on 14 Dec 2022
Askic V
on 14 Dec 2022
Ok, so you need to minimize a cost function defined in the following way:
function cost = cost_func(x)
m = 5;
n = 3;
A(:,:,1:n)= rand(m, 2, n);
B(:,:,1:n) = rand(m, 2, n);
% some processing with x, A,B
% x is a vector 2x1
cost = 0;
for i = 1:n
for j = 1:m
cost = cost + norm(A(j,:,i)-B(j,:,i))^2;
end
end
end
Akella Kartik
on 14 Dec 2022
Torsten
on 14 Dec 2022
For lsqnonlin:
function f = cost_func(x)
for i = 1:n
for j = 1:m
f((i-1)*m + j) = A(j,:,i)-B(j,:,i);
end
end
end
@Torsten, can you please elaborate this part?
f((i-1)*m + j) = A(j,:,i)-B(j,:,i);
lsqnonlin minimizes sum_i f_i^2 where the f_i are (nonlinear) functions of a parameter vector x to be optimized. Since A(j,:,i) and B(j,:,i) are vectors, my previous answer will let MATLAB throw an error.
But instead, simply do
function f = cost_func(x)
A = ...;
B = ...;
f = A(:)-B(:);
end
Askic V
on 14 Dec 2022
Now, it is more clear to me. Thank you.
Akella Kartik
on 14 Dec 2022
Both settings
f = A(:)-B(:)
and
f((i-1)*m + j) = norm(A(j,:,i)-B(j,:,i))
come out the same for lsqnonlin.
lsqnonlin squares norm(A(j,:,i)-B(j,:,i)) for all i and j and sums them.
But
sum_ij (norm(A(j,:,i)-B(j,:,i)))^2 = sum_ijk (A(j,k,i)-B(j,k,i))^2 = sum (A(:)-B(:)).^2
Of course, if your "norm" is not the usual Euclidian norm, the results will be different.
Akella Kartik
on 14 Dec 2022
Torsten
on 14 Dec 2022
Then both formulations are equivalent - choose the one you like best.
I suggest to take
f = A(:)-B(:)
because there are no square roots in it when the solver takes derivatives with respect to the parameters.
Akella Kartik
on 14 Dec 2022
Torsten
on 14 Dec 2022
We don't know the underlying problem - so it's hard to say anything useful.
Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!