0

如何使用 load-ascii 命令修改此程序以读取 (x,y)?

n=0;
sum_x = 0;
sum_y = 0;
sum_x2 = 0;
sum_xy = 0;
disp('This program performs a least-squares fit of an');
disp('input data set to a straight line. Enter the name');
disp('of the file containing the input (x,y) pairs:  ');
filename = input('   ','s');
[fid,msg] = fopen(filename,'rt');
if fid<0
    disp(msg);
else
    [in,count]=fscanf(fid, '%g %g',2);
    while ~feof(fid)
        x=in(1);
        y=in(2);
        n=n+1;
        sum_x=sum_x+x;
        sum_y=sum_y+y;
        sum_x2=sum_x2+x.^2;
        sum_xy=sum_xy+x*y;
        [in,count] = fscanf(fid, '%f',[1 2]);
    end
    fclose(fid);
    x_bar = sum_x / n;
    y_bar = sum_y / n;
    slope = (sum_xy - sum_x*y_bar) / (sum_x2 - sum_x*x_bar);
    y_int = y_bar - slope * x_bar;
    fprintf('Regression coefficients for the least-squares line:\n');
    fprintf('Slope (m)      =%12.3f\n',slope);
    fprintf('Intercept (b)  =%12.3f\n',y_int);
    fprintf('No of points   =%12d\n',n);
end
4

1 回答 1

0

如果我说对了,也许你想要这个:

x=load('-ascii',filename);
sumx =sum(x(:,1));
sumy =sum(x(:,2));
sumx2=sum(x(:,1).^2);
sumy2=sum(x(:,2).^2);
sumxy=sum(x(:,1).*x(:,2));
n    =size(x,1);

也试试这些

sums =sum(x);
sum2s=sum(x.^2);
sumxy=sum(prod(x,2));
means=mean(x);

你也知道有一个功能

[slope,int]=regress(x(:,2), [x(:,1) ones(n,1)])

这可能会妨碍你的工作:)

编辑

鉴于您在下面放置的内容,您的数据似乎不在单独的行中,并且仅由空格分隔的数字组成。因此,如果这是正确的,则在load语句之后,您应该插入该行

x=reshape(x, 2, length(x)/2);

请注意,在读取 ASCII 文件时,准确的格式很重要!请注意,如果您有奇数个数字,这将失败,如果您的文件中有任何换行符,则会给出不正确的值。

我认为您编写的所有其余代码都简化为:

x=load('-ascii',filename);
[slope,int]=regress(x(:,2), [x(:,1) ones(size(x,1),1)])
于 2010-05-01T01:15:31.737 回答