我总是出现错误:索引超出矩阵维度。
rhs错误(第13行) xdot_2 = - (b / m)* x(2) - (k / m)* x(1)+ force(t)/ m;
FinalProject2中的错误(第20行) 结果= rhs(100,x0);
我有一个质量弹簧阻尼系统,以实现:
这是我的代码:
clc, close all, clear *
t_start = 0;
t_end = 1000; %final time in seconds.
t =t_start:0.001:t_end;
k = 1500.0; % as spring constant N/m,
b = 30; %the damping constant Ns/m,
m = 10.0; %the mass of the device,
F = 0.0; %as the input force N
g = 9.81; %as the gravity constant m/s^2
initial_position = 0;
initial_speed = 0;
x0 = [initial_position initial_speed];
result = rhs(100,x0);
将此作为我的rhs函数:
function xdot=rhs(t,x)
k = 1500.0; % as spring constant N/m,
b = 30; %the damping constant Ns/m,
m = 10.0; %the mass of the device,
force = 0.0; %as the input force N
%g = 9.81; %as the gravity constant m/s^2
xdot_1 = x(2);
xdot_2 = -(b/m)*x(2) - (k/m)*x(1) + force(t)/m;
xdot = [xdot_1 ; xdot_2 ];
end
所以我做错了什么?有人可以通过计算这些值来帮助我吗?会有很大帮助:))
编辑:我的RK功能:
% Classical fourth-order Runge-Kutta method
function [t,y] = rk(yprime, tspan, y0, h)
t0 = tspan(1); tfinal = tspan(end);
% set up the t values at which we will approximate the solution
t = [t0:h:tfinal]';
% include tfinal even if h does not evenly divide tfinal-t0
if t(end)~=tfinal, t=[t tfinal]; end
m = length(t);
y = [y0 zeros(length(y0), length(t)-1)];
for i=1:(m-1)
k1 = feval(yprime,t(i),y(:,i));
k2 = feval(yprime,t(i)+0.5*h, y(:,i)+(h.*k1)/2);
k3 = feval(yprime,t(i)+0.5*h, y(:,i)+(h.*k2)/2);
k4 = feval(yprime,t(i)+h, y(:,i)+h.*k3);
y(:,i+1) = y(:,i)+(h*(k1+2*k2+2*k3+k4))/6;
end
我称之为:
yprime=rk(@(t,x) rhs(t,x,force));
tspan = [0 10];
y0 = 0;
h = 0.1;
[t,y] = rk(yprime, tspan, y0, h);
figure(1), clf
plot(t,y,'b.','markersize',15);