Is my code correct for finding the distance between a point and a surface?
4 views (last 30 days)
Show older comments
Hello
We have a
point, an
(hyper)surface and the distance function like
. The surface in my example is
.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/238929/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/238930/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/238931/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/238932/image.png)
P = [0.4 0.4 0.3]; % the point
f = @(x) sqrt(sum(x)); % the surface
distsq = @(x) sum((x-P(1:end-1)).^2) + (f(x)-P(end)).^2; % the distance function squared,want to minimize
[x,fval] = fmincon(distsq,[0.5 0.5],[],[],[],[],[0 0],[1 1])
I want to go higher in dimensions and see how it performs. I just don't know how can I be somewhat sure that the result from fmincon is correct. I'm interested only in the
hypercube.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/238933/image.png)
0 Comments
Accepted Answer
Matt J
on 19 Sep 2019
Edited: Matt J
on 19 Sep 2019
It's largely correct, except that your function distsq is not differentiable at x=0. So, if there's a chance the solution might lie there (but I think it's impossible if P(n) and at least one other P(i) are greater than zero), then I would make a transformation to get rid of the non-differentiability. In this case, this could be,
distsq = @(x) sum((x-P(1:end-1)).^2) + (f(x).^2-P(end).^2).^2;
Note however that for the specific f in your example, the transformation turns the problem into a linear least squares problem, so that you can use lsqlin instead of fmincon,
C=[speye(n-1);ones(1,n-1)];
d=P; d(end)=d(end)^2;
[x,fval] = lsqlin(C,d,[],[],[],[],[0 0],[1 1]);
This also has the advantage that lsqlin is globally convergent and doesn't require an initial guess.
0 Comments
More Answers (0)
See Also
Categories
Find more on Quadratic Programming and Cone Programming 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!