MATLAB: Iterating final temperature minus initial temperature in density calculation

iterationsvectorization

Hello all, Basically i have a matrix of temperatures, ranging from 223.15K to 3273.15K, and i am trying to calculate the final density of air. The formula i have for the change in density is: ρ1 = ρ0 / (1 + β (t1 – t0)) where ρ1 = final density (kg/m3) ρ0 = initial density (kg/m3) β = volumetric temperature expansion coefficient (m3/m3 K) t1 = final temperature t0 = initial temperature
So what i want to do is input the second element for my temperature matrix into t1, and the first element into t0. Then the next calculation i want to use the third element minus the second element and so on until the last element. Also, use the final density from the first calculation and input it into the initial density into the second equation and so on. Ive been trying to set it up with for and while loops and have gotten nowhere. Any help with the code would greatly be appreciated.

Best Answer

There are likely more efficient ways to do this, but if you want to use a loop, this would be my approach to your problem:
beta = 0.5; % Beta (Obviously)
T = linspace(223.15, 3273.15); % Temperature Vector
DT = T(2:end) - T(1:end-1); % Temperature Difference Vector
p(1) = 1.5; % Initial Air Density (‘rho’) At T(1)
for k1 = 2:length(DT)-1
p(k1) = p(k1-1)/(1 + beta*DT(k1));
end
figure(1)
semilogy(T(2:end-1), p)
grid
I’m obviously guessing at the data you didn’t provide, and making some assumptions.