⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 e414.m

📁 学习Matlab循环语句的好例子
💻 M
字号:
% Script file: lsqfit.m
%  Purpose:
%   To perform a least-squares fit of an input data set and intercept
%   values.The input data for this fit is input from the keyboard.
%
% Record of revision
%   Date            Programmer      Description of changes
% =========         ===========     =======================
%   01/03/99        S.J.Chapman     Original code
%   03/06/08        ZMW             Modified code once
%
%  Define variables:
%   ii           --- Loop index
%   n_points     --- Number in input [x,y] points
%   slope        --- Slope of the line
%   sum_x        --- sum of all input x values
%   sum_x2       --- sum of all input x values squared
%   sum_xy       --- sum of all input x*y values
%   sum_y        ---- sum of all input y values
%  temp          --- Variable to read user input
%  input1        -----load filename
%  x             ----Array of x values
% x_bar          ------Average x value
% y              ------Array of y values
% y_bar          -----------Average y value
% y_int          ---y-axis intercept of the line

disp('This program performs a least-squares fit of an ');
disp('inpute data set to a straight line.');
% n_points=input('Enter the number of input [x,y] points:');
% 
% % Read the input data
% for ii=1:n_points
%     temp=input('Enter [x y] pair: ');
%     x(ii)=temp(1);
%     y(ii)=temp(2);
% end
clear;
% n_points=0;
% ii=1;
% temp=[0 0];
% while ~isempty(temp)
%     n_points=n_points+1;
%     x(ii)=temp(1);
%     y(ii)=temp(2);
%     ii=ii+1;
%     temp=input('Please Enter [x y] data pairs:');
% end 
% 采用文件操作
load input1.dat
[n_points,col]=size(input1);
for ii=1:n_points
    x(ii)=input1(ii,1);
    y(ii)=input1(ii,2);
end
    



% Accumulate statistics
sum_x=0;
sum_y=0;
sum_x2=0;
sum_xy=0;
for ii=1:n_points
    sum_x=sum_x+x(ii);
    sum_y=sum_y+y(ii);
    sum_x2=sum_x2+x(ii)^2;
    sum_xy=sum_xy+x(ii)*y(ii);
end 

% Now calculate the slope and intercept
x_bar=sum_x/n_points;
y_bar=sum_y/n_points;
slope=(sum_xy-sum_x*y_bar)/(sum_x2-sum_x*x_bar);
y_int=y_bar-slope*x_bar;

% Tell user
disp('Regression coefficients for the least_squares line:');
fprintf('   slope(m)   =%8.3f\n',slope);
fprintf('   Intercept(b)=%8.3f\n',y_int);
fprintf('   No of points=%8d\n',n_points);

%plot the data points as blue circles with no
% connecting lines
plot(x,y,'bo');
hold on;
%Create the fitted line
xmin=min(x);
xmax=max(x);
ymin=slope*xmin+y_int;
ymax=slope*xmax+y_int;

% plot a solid red line with no markers
plot([xmin xmax],[ymin ymax],'r-','LineWidth',2);
hold off;

% Add a title and legend
title('\bfLeast-Squares Fit');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted Line');
grid on 




⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -