Plot with linspace and for loop - what is wrong with this code?

조회 수: 10 (최근 30일)
Aimee Talbot
Aimee Talbot 2019년 3월 27일
답변: Catalytic 2019년 3월 27일
c = 9000
k = 30000
m = 1100
w_n = sqrt(k/m)
z = c/(2*m*w_n)
Yo = 0.1
v = linspace(0,10);
for i = 1:length(v)
w = 3.14*v(i);
r = w/w_n
X = Yo*((1-r^2)^2+(2*z*r)^2))^(1/2)
f1=figure(1);
hold on
title('Accel vs r')
plot(r,X);
xlabel('r')
ylabel('accel')
end
hold off
this code is supposed to create a plot of X as a function of r. V cannot exceed 10, and the variables w and r depend on this value of v.
The code is producing a blank plot when it should be some singular line.
any input would be extremeley helpful, thanks!

답변 (2개)

Star Strider
Star Strider 2019년 3월 27일
You need to subscript ‘r’ and ‘X’ to create vectors from them, then put the plot call after the loop:
c = 9000
k = 30000
m = 1100
w_n = sqrt(k/m)
z = c/(2*m*w_n)
Yo = 0.1
v = linspace(0,10);
for i = 1:length(v)
w = 3.14*v(i);
r(i) = w/w_n;
X(i) = Yo*sqrt((1-r(i)^2)^2+(2*z*r(i))^2);
end
f1=figure(1);
hold on
title('Accel vs r')
plot(r,X);
xlabel('r')
ylabel('accel')
hold off
The plot function plots lines, not individual values (unless you tell it to plot markers), so plotting individual points in each iteration will result in a blank plot.
Your code could easily be vectorised to make it more efficient, and eliminate the loop.

Catalytic
Catalytic 2019년 3월 27일
plot(r,X,'o');

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by