Search code examples
matlabanonymous

Matlab define a function


I have a physical equation P=(n R T/V - nb)-(an^2/V^2)

which n,b,a,R are constants and V,T are independent variables

the question said to construct an anonymous function (pressure)>P and then create a script function called (vanderWall) which return P,V,T and make mesh contour plot of (P,V,T) and plot of (P,V) for 10 values of T.

the function should generate T with limits T1 to T2 with nT steps, also generate V with limits V1 to V2 with nV steps

using these values for practical output T1=77, T2=800, nT=10, V1=35, V2=200, nV=150, n=1, a=55.37, b=30.4.

I tried this code put no usefull answer

%constants
n=1;
a=55.37;
b=30.4;
R=8.314;

%anonymous function of independent variables V and T
Pressure=@(V,T) ((n*R.*T)./(V-n*b))-((a*n^2)./V.^2);

[P,V,T]=vanderWall(Pressure,77,800,10,35,200,150,1,55.37,30.4);

%function to return Pressure,Volume and Temperature
function[P,V,T]=vanderWall(Pressure,T1,T2,nT,V1,V2,nV,varargin)

%Volume and temperature generatd by function
T=T1:nT:T2;
V=V1:nV:V2;
P=Pressure(V,T);

%mesh contour plot between T,V and P
meshc(T,V,P)

%plot of V and P (isotherms)
plot(V,P)

end

Solution

  • Maybe you can try the following code for function vanderWall, where [T,V]=meshgrid(t,v) is the key step to make your code fly

    function[P,V,T]=vanderWall(Pressure,T1,T2,nT,V1,V2,nV,varargin)
    
    %Volume and temperature generatd by function
    t = T1:nT:T2;
    v = V1:nV:V2;
    [T,V]=meshgrid(t,v);
    
    P=Pressure(V,T);
    
    %mesh contour plot between T,V and P
    meshc(T,V,P)
    
    %plot of V and P (isotherms)
    plot(V,P)
    end
    

    Or you can apply the implicit singleton expansion (thanks for advice @CrisLuengo), i.e.,

    function[P,V,T]=vanderWall(Pressure,T1,T2,nT,V1,V2,nV,varargin)
    
    %Volume and temperature generatd by function
    T = T1:nT:T2;
    V = V1:nV:V2;
    
    P=Pressure(V,T.')';
    
    %mesh contour plot between T,V and P
    meshc(T,V,P)
    
    %plot of V and P (isotherms)
    plot(V,P)
    end