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

11 views (last 30 days)
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!

Answers (2)

Star Strider
Star Strider on 27 Mar 2019
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 on 27 Mar 2019
plot(r,X,'o');

Community Treasure Hunt

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

Start Hunting!