Error with using fminsearch
古いコメントを表示
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);
採用された回答
その他の回答 (1 件)
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 件のコメント
Berenice Oseguera
2019 年 12 月 22 日
per isakson
2019 年 12 月 22 日
In my answer https://se.mathworks.com/matlabcentral/answers/497619-how-to-loop-over-a-customized-function#answer_407307 I've described a debugging session that is similar to the one you need to do.
The documentation on fminsearch says: "[...] returns a real scalar f (the objective function evaluated at x)"
I guess that the function, mindistance, may return a vector of complex numbers and that's the cause of the error.
Add
if not( isreal(distance) && isscalar(distance) )
keyboard
end
as the last statements of mindistance. If I'm right the execution will halt at keyboard and you can inspect the variables of mindistance.
Walter Roberson
2019 年 12 月 22 日
If the coordinates in the Data.xlsx are real-valued, then sqrt(((x-xcoordinates).^2)+((y-ycoordinates).^2)) will be strictly real valued given those real-valued initial conditions. The problem is that it is a vector of distances, and you need to go from the vector to "minimum distance from all", which could mean several different things. For example it might correspond to max() of the distances, or it might be the sum of the distances, or it might be sum-of-squared distances.
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
2019 年 12 月 23 日
カテゴリ
ヘルプ センター および File Exchange で Programming についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!