tags:

views:

43

answers:

1

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
A: 

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)])
Sanjay Manohar
I used the following text file: test_input.txt1.1 1.12.2 2.23.3 3.34.4 4.45.5 5.56.6 6.67.7 7.7it's a simple example where all points fall into the line and the intercept should be 0
Amadou
it's a 7x2 matrix representing (x,y) coordinates in a plan. By the way do I get rid of the loop?
Amadou
OK if ascii file is formatted in a matrix, then you don't need the reshape. You certainly don't need loops - Matlab is designed to eliminate them. All Your code reduces to the 2 lines as I have added at the end.
Sanjay Manohar
If you don't have the statistics toolbox, you can use the \ operator instead of calling `regress`. `out=[x(:,1),ones(size(x(:,1))]\x(:,2);` `out(1)` is the slope, `out(2)` is the intercept.
Jonas
Thanx Sanjay and Jonas. I am getting more than one result for each output
Amadou

related questions