how to make a for loop into a table

2 visualizaciones (últimos 30 días)
Josh Werner
Josh Werner el 29 de Mzo. de 2017
Comentada: Peter Perkins el 31 de Mzo. de 2017
I am new to mat lab so this might sound like a dumb question but how do i make a for loop into a table this is how the teacher said to do it but it does not work the way she wants it
%%Part1
for ounces=1:16;
grams(ounces)=(ounces*28.3495) %grams;
end
T = table(ounces,grams)

Respuesta aceptada

Star Strider
Star Strider el 29 de Mzo. de 2017
You need to give them to table as column vectors:
ounces=1:16;
for oz = 1:length(ounces)
grams(oz)=(ounces(oz)*28.3495); %grams;
end
T = table(ounces(:),grams(:))
T =
16×2 table
Var1 Var2
____ ______
1 28.349
2 56.699
3 85.048
4 113.4
5 141.75
6 170.1
7 198.45
8 226.8
9 255.15
10 283.5
11 311.84
12 340.19
13 368.54
14 396.89
15 425.24
16 453.59
I also created a separate array for ‘ounces’ because you need to use it later, and created an index into it. This approach will prevent indexing error problems if ‘ounces’ had fractional elements.
  3 comentarios
Star Strider
Star Strider el 30 de Mzo. de 2017
My pleasure.
Use the 'VariableNames' name-value pair:
T = table(ounces(:),grams(:), 'VariableNames',{'Ounces','Grams'})
With that change, ‘T’ now becomes:
T =
16×2 table
Ounces Grams
______ ______
1 28.349
2 56.699
3 85.048
4 113.4
5 141.75
6 170.1
7 198.45
8 226.8
9 255.15
10 283.5
11 311.84
12 340.19
13 368.54
14 396.89
15 425.24
16 453.59
Peter Perkins
Peter Perkins el 31 de Mzo. de 2017
If you preallocate ounces and grams as columns, and call table as
T = table(ounces,grams)
you don't even have to set the var names. table picks them up automatically.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by