Loop not returning all values
显示 更早的评论
Below is the code for my matlab file that is only returning u(1) and u(2):
%% Clear MATLAB
clear;
clc;
%% Parameters
tlength=16.74; % time (s)
h=0.02; % time step (s)
N=1:ceil(tlength/h);
t=0.02:h:tlength; % time steps
w0=31.416; % Natural circular freq
zeta0=0.05;
eta=2;
tau=0.12;
m=7;
R=eta*m*w0^2;
v=zeros(1,837);
y3=zeros(1,837);
%% Initial Conditions
v(1)=1; % Velocity at t=0.02s
y3(1)=1; % Displacement of EDD at t=0s
ag(1)=-0.1; % Ground Acceleration at t=0s
a(1)=-1; % Acceleration of frame
u(1)=1; % Displacement of frame
%% Define Equations
f1=@(t,u,v) v;
f2=@(t,v,y3) v-y3/tau;
%% RK4 Loop
for i=1:N
t(i+1)=t(i)+h;
k1=h*f1(t(i),u(i),v(i));
l1=h*f2(t(i),v(i),y3(i));
k2=h*f1(t(i)+h/2,u(i)+k1*h/2,v(i)+l1*h/2);
l2=h*f1(t(i)+h/2,v(i)+k1*h/2,y3(i)+l1*h/2);
k3=h*f1(t(i)+h/2,u(i)+k2*h/2,v(i)+l2*h/2);
l3=h*f1(t(i)+h/2,v(i)+k2*h/2,y3(i)+l2*h/2);
k4=h*f1(t(i)+h,u(i)+k3*h,v(i)+l3*h);
l4=h*f1(t(i)+h,v(i)+k3*h,y3(i)+l3*h);
v(i+1)=v(i)+h/6*(k1+2*k2+2*k3+k4);
y3(i+1)=y3(i)+h/6*(l1+2*l2+2*l3+l4);
end
plot(t,v)
5 个评论
Torsten
2022-11-25
I don't see any line in your code where you compute u(i+1) as you do for v. Maybe y3 is u ? We don't know.
joe brady
2022-11-25
Torsten
2022-11-25
As said, u(i) is undefined for i>1 in the expressions
k1=h*f1(t(i),u(i),v(i));
k2=h*f1(t(i)+h/2,u(i)+k1*h/2,v(i)+l1*h/2);
k3=h*f1(t(i)+h/2,u(i)+k2*h/2,v(i)+l2*h/2);
k4=h*f1(t(i)+h,u(i)+k3*h,v(i)+l3*h);
Thus k1, k2, k3 and k4 cannot be evaluated for i > 1.
Torsten
2022-11-25
Thanks for your reply, i have now added a definition for u and i am still struggling - the same error is happening:
Can you show me the line of the above code where you define u(i) for i>1 ? u(i) is undefined for i>1.
The same for y3. y3(i) is nowhere defined for i>1.
And N must be a scalar, not an array. Thus you will have to replace
N=1:ceil(tlength/h);
by
N=ceil(tlength/h);
回答(0 个)
类别
在 帮助中心 和 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!
