如何避免Matlab錯(cuò)誤Too many output arguments
最優(yōu)化方法與理論這本書(shū)的代碼中有很多印刷錯(cuò)誤的地方,大家平時(shí)要留意下復(fù)制最優(yōu)化理論書(shū)上的源代碼,在使用Matlab編譯時(shí)可能會(huì)出現(xiàn)類似以下錯(cuò)誤:`Error using gt; qmin Too ma
最優(yōu)化方法與理論這本書(shū)的代碼中有很多印刷錯(cuò)誤的地方,大家平時(shí)要留意下復(fù)制最優(yōu)化理論書(shū)上的源代碼,在使用Matlab編譯時(shí)可能會(huì)出現(xiàn)類似以下錯(cuò)誤:`Error using gt; qmin Too many output arguments.` 這種錯(cuò)誤通常是由于代碼中輸出參數(shù)數(shù)量不匹配導(dǎo)致的。比如書(shū)上的代碼示例如下:
```matlab
function [s, phis, ds, dphi, S] qmin (phi, a, b, delta, epsilon)
s0 1;
maxj 20;
maxk 30;
big 1e6;
err 1;
k 1;
S(k) s0;
cond 0;
h 1;
ds 0.00001;
if (abs(s0) > 1e4), h abs(s0) * (1e-4);
end
while (k < maxk err > epsilon cond ~ 5)
f1 (feval(phi, s0 ds) - feval(phi, s0 - ds)) / (2 * ds);
if(f1 > 0), h -abs(h);
end
s1 s0 h;
s2 s0 2 * h;
bars s0;
phi0 feval(phi, s0);
phi1 feval(phi, s1);
phi2 feval(phi, s2);
barphi phi0;
cond 0;
j 0;
while (j < maxj abs(h) > delta cond 0)
if (phi0 < phi1), s2 s1; phi2 phi1; h 0.5 * h; s1 s0 h; phi1 feval(phi, s1);
else if (phi2 < phi1), s1 s2; phi1 phi2; h 2 * h; s2 s0 2 * h; phi2 feval(phi, 2);
else cond -1;
end
end
j j 1;
if (abs(h) > big || abs(s0) > big), cond 5;
end
end
if (cond 5), bars s1; barphi feval(phi, s1);
else d 2 * (2 * phi1 - phi0 - phi2);
if (d < 0), barh h * (4 * phi1 - 3 * phi0 - phi2)/d;
else barh h / 3; cond 4;
end
bars s0 barh; barphi feval(phi, bars);
h abs(h); h0 abs(barh); h1 abs(barh - h); h2 abs(barh - 2 * h);
if (h0 < h), h h0;
end
if (h1 < h), h h1;
end
if (h2 < h), h h2;
end
if(h 0), h barh;
end
if (h < delta), cond 1;
end
if (abs(h) > big || abs(bars) > big), cond 5;
end
err abs(phi1 - barphi);
s0 bars; k k 1; S(k) s0;
end
if (cond 2 h < delta), cond 3;
end
end
ends s0; phis feval(phi, s); ds h; dphi err;
```
解決方法
在Matlab中新建一個(gè)M文件,命名為qmin。如果在編譯時(shí)遇到類似"Too many output arguments"的錯(cuò)誤提示,仔細(xì)檢查代碼發(fā)現(xiàn)命令語(yǔ)句的輸出參數(shù)中多了一個(gè)不必要的參數(shù)k。為了解決這個(gè)問(wèn)題,只需將命令語(yǔ)句中的k參數(shù)刪除,然后再次運(yùn)行程序即可成功輸出結(jié)果。
注意事項(xiàng)
除了代碼中可能出現(xiàn)的編譯錯(cuò)誤外,最優(yōu)化方法與理論這本書(shū)的代碼中還存在許多印刷錯(cuò)誤。因此,在復(fù)制書(shū)上的源代碼時(shí),需要注意并及時(shí)糾正可能存在的錯(cuò)誤,以確保代碼能夠順利運(yùn)行。避免類似"Too many output arguments"這樣的簡(jiǎn)單但影響編譯的錯(cuò)誤。
通過(guò)以上方法和注意事項(xiàng),可以更好地處理Matlab代碼中可能出現(xiàn)的錯(cuò)誤,并確保順利編譯和執(zhí)行程序。這樣可以有效提高工作效率,減少不必要的麻煩。