Plotting a for loop

3 visualizaciones (últimos 30 días)
Chris Jordan
Chris Jordan el 25 de Abr. de 2015
Editada: Jan el 25 de Abr. de 2015
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]

Respuestas (2)

Geoff Hayes
Geoff Hayes el 25 de Abr. de 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).

Jan
Jan el 25 de Abr. de 2015
Editada: Jan el 25 de Abr. de 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')

Categorías

Más información sobre Graphics Performance en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by