# How to find what values of a and b give the minimum value in the sum

2 ビュー (過去 30 日間)
t sizzle 2021 年 4 月 28 日
コメント済み: Star Strider 2021 年 4 月 28 日
I have programmed a function which will sum the distances from a point (a,b) to each individual point (x,y). Then it will find the minium sum. Now, I need to be able to find what value of a and b results in this minimum sum. I am unsure how to do this. Below is the function which returns the right value for the minimum sum. All the combinations that lead to sums are stored as an array called summs. The size of this array "summs" in my example is 1x10201.
function [c] = project2function(a, b, xvalue, yvalue)
t = 1;
for m = 1:numel(a)
for n = 1:numel(b)
c = 0;
for k = 1:length(xvalue)
d = sqrt((a(m) - xvalue(k)).^2 + (b(n) - yvalue(k)).^2);
c = c + d;
end
summs(t) = c;
t = t + 1;
end
end
summs
minsum = min(summs)
size(summs)
end

サインインしてコメントする。

### 回答 (1 件)

Star Strider 2021 年 4 月 28 日
This is a relatively straightforward optmisation problem.
Try this —
x = randn(20,1); % Create Data
y = randn(20,1); % Create Data
fctr = @(b,x,y) (b(1)-x).^2 + (b(2)-y).^2; % Objective Function
[Ctr,fval] = fminsearch(@(b)norm(fctr(b,x,y)), rand(2,1)*100); % Estimate Center
figure
plot(x, y, 'p')
hold on
plot(Ctr(1), Ctr(2), '+r')
hold off
grid
axis('equal')
title(sprintf('Centre: (%.4f, %.4f)',Ctr))
The loops are all internal to fminsearch, that finds the minimum of the norm of the objective function. Other functions are also appropriate, such as fmincon, fminunc, and ga, to list three of many possibilities.
##### 2 件のコメントなしを表示なしを非表示
t sizzle 2021 年 4 月 28 日
the thing is that a and b are constrained to what a user will input, and the range will always be different as will the values for x and y points. Is there a way to do this with just nested for loops?
Star Strider 2021 年 4 月 28 日
If you want to add constraints, use fmincon instead, and add the ‘constraints’ on the parameters. However, since I have no idea what ‘constraints’ means in this context, fminbnd is another option. If those don’t work, search the documentation to find an optimisation function that meets the requirements you set for it. The calling syntax for it will likely be what I wrote. (Also, if you want the exact distance, take the square root of the sum of the squared distances. I left that out because the minimum of the sum of the squares is the minimum of their square root, and taking the square root only adds computational complexity.)

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeLinear Predictive Coding についてさらに検索

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by