Plotting a for loop
1 view (last 30 days)
Show older comments
I can't get my plot to plot all the variables in my code, it only plots the last variable (ie. 7).How can I fix this?? My code is as follows:
w = 400; %Weight of object (kg);
lp = 8; %Cantilever length (m);
lc = 8; %Cable length (m);
for d=[1,2,3,4,5,6,7]
T(d) = (w*lc*lp)/(d*sqrt((lp^2)-(d^2)))
end
plot(d,T(d),'-or')
[EDITED, Jan, please format your code properly - thanks]
0 Comments
Answers (2)
Geoff Hayes
on 25 Apr 2015
Chris - note how you are calling the plot function
plot(d,T(d),'-or')
you are passing d as the first input and as the indexing variable into T. Since was used as the indexing variable for the for loop, it is a scalar and so that is why your plot only shows that for the last variable. You need to specify all the points that you wish to plot. Try the following instead
w = 400; %Weight of object (kg);
lp = 8; %Cantilever length (m);
lc = 8; %Cable length (m);
N = 7;
for d=1:N
T(d) = (w*lc*lp)/(d*sqrt((lp^2)-(d^2)))
end
plot(1:N,T,'-or')
We use N to specify the number of values that we wish to accumulate (and so plot).
0 Comments
Jan
on 25 Apr 2015
Edited: Jan
on 25 Apr 2015
With this line you ask Matlab explicitly to plot only the last element of T:
plot(d,T(d),'-or')
If you want to see all values, this works:
for d= 1:7 % Nicer than [1,2,3,4,5,6,7]
T(d) = (w*lc*lp)/(d*sqrt((lp^2)-(d^2)));
end
plot(1:7, T, '-or')
This can be "vectorized":
d = 1:7;
T = (w*lc*lp) / (d .* sqrt((lp ^ 2) - (d .^ 2)));
plot(d, T, '-or')
0 Comments
See Also
Categories
Find more on Line Plots 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!