Error with using fminsearch

1 回表示 (過去 30 日間)
Berenice Oseguera
Berenice Oseguera 2019 年 12 月 22 日
コメント済み: Berenice Oseguera 2019 年 12 月 23 日
I am working on finding the point that is the closest to 15 locations (minimum distance from all). The x- and y-coordinates are stored in 2 variables. I created the function and extracted the scalar variables from the vector but I am getting an error stating that there are not enough input arguments. The function definition and code are below:
function distance=mindistance(xv)
x=xv(1);
y=xv(2);
% extracting scaler variables from vector in fminsearch
sources = readtable('Data.xlsx','Sheet','PROJECT');
xcoordinates=table2array(sources(:,3));
ycoordinates=table2array(sources(:,4));
distance=sqrt(((x-xcoordinates).^2)+((y-ycoordinates).^2));
end
point to start with for fminsearch
xvg=[-2000 1500];
[xvmin,minD]=fminsearch(mindistance,xvg);

採用された回答

Walter Roberson
Walter Roberson 2019 年 12 月 22 日
編集済み: Walter Roberson 2019 年 12 月 22 日
For one definition of "minimum distance from all":
function [xvmin, minD] = mindistance_driver
sources = readtable('Data.xlsx','Sheet','PROJECT');
xcoordinates = sources{:,3};
ycoordinates = source{:,4};
xvg=[mean(xcoordinates), mean(ycoordinates)];
[xvmin, minD]=fminsearch( @(x) mindistance(x, xcoordinates, ycoordinates), xvg);
end
function distance = mindistance(xv, xcoordinates, ycoordinates)
x=xv(1);
y=xv(2);
distance = sum( sqrt(((x-xcoordinates).^2)+((y-ycoordinates).^2)) );
end
There are other definitions that can be computed much more efficiently. In particular, if you use
distance = sqrt( sum( ((x-xcoordinates).^2)+((y-ycoordinates).^2) ) );
then you can demonstrate that mean(x) and mean(y) are the optimal coordinates, without needing to do any searching.
  1 件のコメント
Berenice Oseguera
Berenice Oseguera 2019 年 12 月 23 日
Thank you! This worked!

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

その他の回答 (1 件)

per isakson
per isakson 2019 年 12 月 22 日
編集済み: per isakson 2019 年 12 月 22 日
Replace
[xvmin,minD]=fminsearch(mindistance,xvg);
by
[xvmin,minD]=fminsearch('mindistance',xvg);
or
[xvmin,minD]=fminsearch(@mindistance,xvg);
  5 件のコメント
per isakson
per isakson 2019 年 12 月 22 日
編集済み: per isakson 2019 年 12 月 22 日
I try to help OP find his/her programming mistakes. To that end I believe that reading documentation and the debugging process are important.
Berenice Oseguera
Berenice Oseguera 2019 年 12 月 23 日
Thank you!

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

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by