clear;clc;close all format compact %% 正態分布的擬合 % 生成隨機數 num = 50; y = randn(1000,1); x = 1:num; y = hist(y,num); xx = x(:); yy = y(:); % Set up fittype and options. ft = fittype('y0+(a/(w*sqrt(pi/2)))*exp(-2*((x-xc)/w).^2)', 'independent', 'x', 'dependent', 'y'); opts = fitoptions(ft); opts.Display = 'Off'; opts.Lower = [0 0 0 0]; opts.StartPoint = [1.1 1.1 1.1 1.1]; % Fit model to data. [fitresult, gof] = fit( xx, yy, ft, opts ); % Plot fit with data. figure; plot(fitresult) hold on plot(xx, yy,'b*'); legend('原始數據', '擬合曲線', 'Location', 'NorthEast'); title(['正態分布擬合,num=',num2str(num)]) xlabel('x'); ylabel('y'); grid on saveas(gcf,'pic.png') %% 輸出擬合參數 a = fitresult.a w = fitresult.w xc = fitresult.xc y0 = fitresult.y0 %% 計算均方誤差 yyy = y0+(a/(w*sqrt(pi/2)))*exp(-2*((xx-xc)/w).^2); rmse = 1/length(yyy)*norm(yyy-yy); fprintf('num = %d, rmse = %.2f\n',num,rmse)
得到對應的參數為
a = 992.6775 w = 14.3208 xc = 28.0562 y0 = 0.1646
均方誤差為
mse = 0.69