how to make a for loop into a table

2 vues (au cours des 30 derniers jours)
Josh Werner
Josh Werner le 29 Mar 2017
Commenté : Peter Perkins le 31 Mar 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)

Réponse acceptée

Star Strider
Star Strider le 29 Mar 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 commentaires
Star Strider
Star Strider le 30 Mar 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 le 31 Mar 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by