开发者

using load instead of other I/O command

How can I modify this program using load-ascii command to read (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]=fsca开发者_开发技巧nf(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


If I get you right, perhaps you want this:

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);

Also try these

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

Also do you know that there is a function

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

which might obviate your work :)

edit

Given what you have put below, it appears that your data is not in separate rows, and consists of numbers separated by spaces only. So if this is correct, after the load statement, you should insert the line

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

Note that when reading an ASCII file, the exact format is important! Please note that this will fail if you have an odd number of numbers, and will give incorrect values if you have any newline characters in your file.

I think that all the rest of the code you have written reduces to:

x=load('-ascii',filename);
[slope,int]=regress(x(:,2), [x(:,1) ones(size(x,1),1)])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜