using load instead of other I/O command

Posted by Amadou on Stack Overflow See other posts from Stack Overflow or by Amadou
Published on 2010-05-01T00:55:29Z Indexed on 2010/05/01 1:17 UTC
Read the original article Hit count: 283

Filed under:

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]=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

© Stack Overflow or respective owner

Related posts about matlab