[討論] fmincon出現error

看板MATLAB作者 ( )時間10年前 (2015/07/29 22:26), 編輯推噓2(202)
留言4則, 2人參與, 最新討論串1/1
我要寫一個找四個變數的最佳化程式 以下是主程式 ============================= x0 = [7 7 30 -0.17453292] options=optimset('LargeScale','off') [x,fval] = fmincon(@(x)myfun(x),x0,[],[],[],[],[5 5 20 -pi/4],[10 10 35 pi/4],[],options) ============================= 接著寫myfun ========================================= function f = myfun(x) %UNTITLED3 Summary of this function goes here syms k r1 r2 r3 r4 th1 th2 ac BCA DCA BCD bd CBD BDC BCE thDIP; r2=28 x = [r1 r3 r4 th1] for i=1:110 th2=((90-i)*pi)/180; thDIP = k*((pi/2)-th2) ac=sqrt(r1*r1+r2*r2-2*r1*r2*cos(th1-th2)); BCA=acos((r3*r3+ac*ac-r4*r4)/(2*r3*ac)); DCA=acos((r2*r2+ac*ac-r1*r1)/(2*r2*ac)); BCD=BCA-DCA; bd=sqrt(r3*r3+r2*r2-2*r3*r2*cos(BCD)); CBD=acos((r3*r3+bd*bd-r2*r2)/(2*r3*bd)); BDC=acos((r2*r2+bd*bd-r3*r3)/(2*r2*bd)); BCE=CBD+BDC; alpha(:,i)=[(BCE+thDIP)] %k=2/3 end; for i=1:109 diff(:,i)=[((alpha(i)-alpha(i+1))^2)] end; % Detailed explanation goes here f= sum(diff) end ============================================= 跑到後面卻出現 Error using fmincon (line 783) FMINCON requires all values returned by user functions to be of data type double. 請問這是甚麼原因呢? 急需版上大大解惑QAQ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.240.135.168 ※ 文章網址: https://www.ptt.cc/bbs/MATLAB/M.1438179971.A.26C.html

07/29 22:35, , 1F
我沒在用syms的不太確定 但你確定你f出來是double嗎?
07/29 22:35, 1F

07/29 22:41, , 2F
然後我既的之前給他input的x是個N*1的向量 然後在myfun
07/29 22:41, 2F

07/29 22:41, , 3F
中是用var1=x(1); var2=x(2); 類似這樣去弄的
07/29 22:41, 3F

07/30 08:18, , 4F
f是syms 你要先用double做轉換
07/30 08:18, 4F
文章代碼(AID): #1LkEA39i (MATLAB)
文章代碼(AID): #1LkEA39i (MATLAB)