How do I create a table from a for loop?

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.

 Respuesta aceptada

Jeff Miller
Jeff Miller el 8 de Feb. de 2018
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);

2 comentarios

This worked, but now it's bringing up an error message with one of my equations.
P(ih_k) =(1.01325*10^5)*(T/288.16)^(-g/(atrop*R));
Error using ^ One argument must be a square matrix and the other must be a scalar. Use POWER (.^) for elementwise power.
I tried using the element by element power operator but it brings up this error message.
In an assignment A(:) = B, the number of elements in A and B must be the same.
Jeff Miller
Jeff Miller el 8 de Feb. de 2018
In this line (and others), switch from T to T(ih_k) so you are just referring to the corresponding element of T.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 8 de Feb. de 2018

Comentada:

el 8 de Feb. de 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by