Last active
December 21, 2015 11:28
-
-
Save rysk-t/d0fdef20df146b5902c1 to your computer and use it in GitHub Desktop.
matlab関数フィッティング (正弦波フィット) ref: http://qiita.com/rysk-t/items/62c74367e9614de9c027
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| x = pi*(0:30:360)/180; | |
| y = 2*rand(1)*sin(x-randn(1)*pi+pi/2)+0.2; | |
| yraw = y+0.17*randn(size(x)); % 正規乱数を足す.このデータにフィッティングする. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| sinfunc = @(v, x) (v(1)*sin(x-v(2))+v(3)); % 関数ハンドル | |
| %フィッテイングの際の初期値 | |
| vinit(1) = max(y)+mean(y); | |
| vinit(2) = 0; | |
| vinit(3) = max(y); | |
| % フィッティングアルゴリズムなどのオプション | |
| options = optimoptions('lsqnonlin', 'MaxIter', 10000,... | |
| 'Algorithm', 'trust-region-reflective', 'Tolx', 10^-15, 'TolFun', 10^-15,... | |
| 'ScaleProblem', 'none', 'MaxFunEvals', length(x)*200, 'Display', 'off'); | |
| % 変数の上限と下限 | |
| ub = [vinit(1)*2, 2*pi, vinit(1)]; | |
| lb = [0, 0, min(y)]; | |
| % 最適化する関数 | |
| efunc = @(v) abs((sinfunc(v,x) - y)); | |
| % 正弦波フィットの場合は位相の初期値を色々試す方が良い | |
| % (y の最大値をから初期値をもとめても良い) | |
| initphz = [0:30:360]*pi/180; | |
| for i = 1:length(initphz) | |
| vinit(2) = initphz(i); | |
| [params{i}, f(i), flag{i}, lamb{i}] = ... | |
| lsqnonlin(efunc, vinit, lb, ub,options); | |
| end | |
| [~, o] = min(f); | |
| optparam = params{o}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| figure; hold on | |
| xopt = 0:0.1:2*pi; | |
| plot(x,yraw,'d') | |
| plot(xopt, sinfunc(optparam, xopt), 'k-') | |
| plot(x, y, 'r-ーo') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment