Search code examples
mathoctaveinterpolationleast-squares

Least squares interpolation in Octave


I did a physics experiment, and got the following data:

R=[2.91 2.19 1.76 1.43 1.20 1.01 0.88 0.77 0.67 0.6 0.52 0.46 0.41 0.37];
t=[35:5:100];
T=t+273.15;

Now I need to do a least squares interpolation for the formula ln R = f(1 / T). I tried several methods from the web, but could get none of them to work.


Solution

  • Apparently, you are using linear lease square interpolation. The problem exists at the code for calculating coefficients.

    This operation

    A \ y
    

    works when the column size of A matches with the row size of y.

    But in your code, horizontal concatenation of ones(n,1) with x in the statement

    A = [x ones(n,1)]
    

    is not being allowed because the size of x is 1*14 and that of ones(n,1) is 14*1. Clearly, you are getting a dimensions mismatch error.

    Here is a working code:

    R=[2.91 2.19 1.76 1.43 1.20 1.01 0.88 0.77 0.67 0.6 0.52 0.46 0.41 0.37];
    t=[35:5:100];
    T=t+273.15;
    
    
    function coeff = least_square (x,y)
        n = length(x);
        A = [ones(n,1) x];
        coeff = A \ y;
        plot(x,y,'x');
        hold on
        interv = [min(x) max(x)];
        plot(interv,coeff(1)*interv+coeff(2));
    end
    
    
    least_square(R', T');