Asked by Andrew Craddick
on 14 Sep 2019

I have a set of data points giving me the values for the second virial coefficient, for various values of T, of the virial expansion which is an equation that corrects the ideal gas law for empirical deviations:

I'm trying to do a least squares fit to determine how well the van der Waals equation predicts using MATLAB.

The equation you derive for B using van der Waals' equation ends up being:

where a and b are unknown constants I need to determine and R is just the ideal gas constant.

Now my data points for true values are here:

B = [-160 -35 -4.2 9 16.9 21.3]*10^-6 ;

T = [100 200 300 400 500 600]; (kelvin)

How can I write some code which will use the least squares method to generate estimates for a and b using the given data points?

My problem is that this is essentially a equation which I'm not sure how to represent in MATLAB.

I can only find options for quadratic, cubic, polynomial fit etc.

Answer by Star Strider
on 15 Sep 2019

Edited by Star Strider
on 15 Sep 2019

Accepted Answer

This is actually a linear problem, so a linear approximation will estimate the parameters correctly:

R = 8.314462; % J K^−1 mol

B = [-160 -35 -4.2 9 16.9 21.3];

T = [100 200 300 400 500 600];

ab = [ones(size(B(:))) - 1./(R*T(:))] \ B(:); % Linear Approximation Parameter Estimation

Bfit = [ones(size(B(:))) - 1./(R*T(:))] * ab; % Linear Fit

figure

plot(T, B, 'pg')

hold on

plot(T, Bfit,'-r')

hold off

grid

xlabel('T')

ylabel('B')

legend('Data','Linear Least-Squares Fit', 'Location','E')

The parameters are:

a = 64.2001320479734

b = 182307.574287957

EDIT —

Added plot figure:

Star Strider
on 15 Sep 2019

My pleasure!

Note that your equation is linear because it is linear in the parameters. That is because the partial derivatives of ‘B’ with respect to either parameter are not functions of that parameter or other parameters. So a linear approximation is appropriate, and provides the correct result.

Andrew Craddick
on 15 Sep 2019

got it. Thanks for the clarification!

Star Strider
on 15 Sep 2019

My pleasure!

Sign in to comment.

Answer by Jackson Burns
on 15 Sep 2019

Attached is code generated by cftool using a custom equation. Hope this helps!

Andrew Craddick
on 15 Sep 2019

Pardon my ignorance but I'm having trouble implimenting the command:

[result,~] = createFit(T,B)

its telling me that "result" is unused. Is there something I need to link to that spot? Thanks again

Jackson Burns
on 15 Sep 2019

Andrew Craddick
on 15 Sep 2019

got it. Thanks!

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.