How to use fminsearch with a function containing vectors of symbols

8 次查看(过去 30 天)
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 个评论
Benjamin9119
Benjamin9119 2019-1-14
Thanks Torsten,
This is probably where my understanding lets me down. If I have:
f = @(h1, h2, k1, k2) norm(h1.*k1)-norm(h2.*k2)
How do i pass the variables x1, x2, y1, y2 into this function which contains the vectors k1 and k2?
Stephen23
Stephen23 2019-1-14
编辑:Stephen23 2019-1-14
Note simpler syntax:
k1 = [cos(x1)*cos(y1); cos(x1)*sin(y1); sin(x1)];
k2 = [cos(x2)*cos(y2); cos(x2)*sin(y2); sin(x2)];

请先登录,再进行评论。

采纳的回答

Torsten
Torsten 2019-1-14
编辑:Torsten 2019-1-14
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 个评论
Taicheng Tsao
Taicheng Tsao 2019-9-13
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
Torsten 2019-9-13
After the line
x = fminsearch(@(x)f(x,h1,h2),x0)
x is available for further use.

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by