Plotting a for loop

1 次查看(过去 30 天)
Chris Jordan
Chris Jordan 2015-4-25
编辑: Jan 2015-4-25
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]

回答(2 个)

Geoff Hayes
Geoff Hayes 2015-4-25
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).

Jan
Jan 2015-4-25
编辑:Jan 2015-4-25
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')

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by