how to make a for loop into a table
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Josh Werner
il 29 Mar 2017
Commentato: Peter Perkins
il 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)
0 Commenti
Risposta accettata
Star Strider
il 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 Commenti
Star Strider
il 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
il 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!