how to make a for loop into a table
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Josh Werner
am 29 Mär. 2017
Kommentiert: Peter Perkins
am 31 Mär. 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 Kommentare
Akzeptierte Antwort
Star Strider
am 29 Mär. 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 Kommentare
Star Strider
am 30 Mär. 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
am 31 Mär. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!