Plotting a for loop
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (2 件)
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).
0 件のコメント
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')
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!