how to make a for loop into a table
2 views (last 30 days)
Show older comments
Josh Werner
on 29 Mar 2017
Commented: Peter Perkins
on 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 Comments
Accepted Answer
Star Strider
on 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 Comments
Star Strider
on 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
on 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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!