필터 지우기
필터 지우기

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