problem related to for loop

I am trying to plot x and v equation for different value of m ... please take alook and kindly guid me through this
m = [10,20,30,40];
k = 50;
x0=0.01;
v0=0.2;
d=size(m);
dt = 0.001;
t = 0:dt:10;
for l=0:d
wn(l) = sqrt(k(l)/m(l));
s1(l) = 1i*sqrt(k(l)/m(l));
s2(l) = -1i*sqrt(k(l)/m(l));
C1(l) = (-v0+x0*s2(l))/(s2(l)-s1(l));
C2(l) = (v0-x0*s1(l))/(s2(l)-s1(l));
x(l) = C1(l)*exp(s1(l)*t)+C2(l)*exp(s2(l)*t);
v(l) = C1(l)*s1(l)*exp(s1(l)*t)+C2(l)*s2(l)*exp(s2(l)*t);
end
figure;
subplot(211),plot(t,x,'r--'); xlabel('Time'), ylabel('Displacement')
subplot(212),plot(t,v,'r--'); xlabel('Time'), ylabel('Displacement')

 采纳的回答

the cyclist
the cyclist 2015-10-14
编辑:the cyclist 2015-10-14
You have at least three problems with your code that I can see.
First, in the line
wn(l) = sqrt(k(l)./m(l));
you are trying to access the "0th" element of the array wn, but that does not exist. MATLAB uses 1-based indexing, so you need to start from 1.
Second, you are using the "/" and "*" operators, but those are for matrix division and multiplication. You probably want "./" and ".*" for all of those.
Third, I think you want to use "t(l)" instead of "t" in your for loop.

更多回答(1 个)

Chad Greene
Chad Greene 2015-10-14

0 个投票

You can't start indexing with zero. You'll have to do for l = 1:length(m)

1 个评论

thanks ... but there is a problem with loop and this error ''the number of elements in B and I must be the same''

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by