How to use fminsearch with a function containing vectors of symbols
7 views (last 30 days)
Show older comments
Hello Matlab community,
Firstly, I apologise for my lack of knowledge when asking this question – I am a new Matlab user taking on a task that is quite likely out of my depth.
I have a cost function (f) that I wish to minimise using fminsearch (I believe this is what I should use for a sum of squared errors minimisation).
My function is
f = norm(h1 .x k1) – norm(h2 .x k2)
Where:
h1 and h2 are nx3 matrices of known values; and
k1 = [cos(x1)*cos(y1), cos(x1)*sin(y1), sin(x1)].’ ;
k2 = [cos(x2)*cos(y2), cos(x2)*sin(y2), sin(x2)].’
This is where I am a bit stuck, I am wanting to find the values of x1, x2, y1, y2 for which the cost function is minimised, however I am unsure of how to do this (i.e. get it in a form which I can use fminsearch) for a function (f) containing symbolic values.
I have tried a number of different approaches based on Googling (what I think may be) relevant search terms but due to my basic knowledge in Matlab I seem to have got myself pretty confused.
Does anyone have any hints or suggestions for which I can use to do this or any more search terms you suggest for me to Google? Once again, apologies for the broad question but any help would fantastic!
Many thanks in advance!
Kind Regards,
Ben
5 Comments
Accepted Answer
Torsten
on 14 Jan 2019
Edited: Torsten
on 14 Jan 2019
Write a function for f:
function main
h1 = ...:
h2 = ...;
x0 = [x10,x20,y10,y20]; % initial guess for solution
x = fminsearch(@(x)f(x,h1,h2),x0)
end
function obj = f(x,h1,h2)
x1 = x(1);
x2 = x(2);
y1 = x(3);
y2 = x(4);
k1 = [cos(x1)*cos(y1), cos(x1)*sin(y1), sin(x1)].' ;
k2 = [cos(x2)*cos(y2), cos(x2)*sin(y2), sin(x2)].';
obj = norm(h1*k1)-norm(h2*k2);
end
3 Comments
Taicheng Tsao
on 13 Sep 2019
I have a question. The result just display in the Command Window without being assigned in the 'x', so I want to know how I can use the result in the subsequent process. Thanks very much.
Torsten
on 13 Sep 2019
After the line
x = fminsearch(@(x)f(x,h1,h2),x0)
x is available for further use.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!