Plot with linspace and for loop - what is wrong with this code?
3 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(2 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!