MATLAB: How to create a table from a for loop

for loopvectors

I need to create a table with 5 columns and 48 rows from a for loop.
for h_k = 0:47
g = 9.80065;
R = 287;
atrop = (-6.5*10^(-3));
astrat = (3*10^(-3));
re = 6371.0008;
h_m = h_k*1000;
h_g = ((h_k*re)/(re-h_k));
if h_k <= 11
T = (288.16+atrop*(h_m-0));
P = (1.01325*10^5)*(T/288.16)^(-g/(atrop*R));
D = (1.225)*(T/288.16)^(-g/(atrop*R)-1);
elseif h_k <= 25
T = (288.16+atrop*11000);
P = ((1.01325*10^5)*(T/288.16)^(-g/(atrop*R)))*exp((-g/(R*T))*(h_m-11000));
D = ((1.225)*(T/288.16)^(-g/(atrop*R)-1))*exp((-g/(R*T))*(h_m-11000));
elseif h_k <= 47
T = (288.16+atrop*(11000))+astrat*(h_m-25000);
P = ((1.01325*10^5)*((288.16+atrop*11000)/288.16)^(-g/(atrop*R)))*exp((-g/(R*(288.16+atrop*11000)))*(25000-11000))*((T/(288.16+atrop*11000))^(-g/(astrat*R)));
D = (((1.225)*((288.16+atrop*11000)/288.16)^(-g/(atrop*R)-1))*exp((-g/(R*(288.16+atrop*11000)))*(25000-11000)))*(T/(288.16+atrop*11000))^((-g/(astrat*R))-1);
end
fprintf('%1.0f\n %8.6f\n %6.2f\n %7.3f\n %5.3f\n',h_k, h_g, T, P, D)
end
I want each answer for h_k to be stored in a column and so on and so forth with h_g, T, P, D.

Best Answer

One possibility is to store the results in arrays as you go, then stuff them all into a table at the end. Something like this, maybe:
h_g = zeros(48,1); % Same for T, P, D, etc
for ih_k=1:48
h_k=ih_k-1;
h_g(ih_k) = % your computation for h_g
if ...
T(ih_k) = % your computation for T, P, D, etc
% etc
end
end
tbl = table(h_g,T,P,D);