MATLAB: Using ode45 and plot

codeerrorode45plot

I am working on 1. I am having trouble coding the function so that I can use the ode45 function. This is what my code looks like :
function xp=F(t,x)
xp=zeros(2,1); % since output must be a column vector
xp(2)=-(x(1)+(0*(x(1)^3)));
xp(3)=-(x(1)+(0.1*(x(1)^3)));
xp(4)=-(x(1)+(0.2*(x(1)^3)));
xp(5)=-(x(1)+(0.4*(x(1)^3)));
xp(6)=-(x(1)+(0.6*(x(1)^3)));
xp(7)=-(x(1)+(0.8*(x(1)^3)));
xp(8)=-(x(1)+(1.0*(x(1)^3)));
then in the command window I am inputting :
[t,x]=ode45('F',[0,20],[0,1]); plot(t,x(:,1))
I know I probably messed up the code . Any ideas?

Best Answer

Don’t do everything at once!
Otherwise, you’re almost there! This is how I would do it:
F = @(t,x,e) [x(2); -(x(1)+(e.*(x(1).^3)))]; % Spring ODE
ev = 0:0.2:1.0; % ‘epsilon’ Vector
ts = linspace(0,10, 50); % Time Vector
for k1 = 1:length(ev)
[~, x{k1}]=ode45(@(t,x) F(t,x,ev(k1)), ts, [0,1]);
end
figure(1)
for k1 = 1:length(ev)
subplot(length(ev), 1, k1)
plot(ts,x{k1})
legend(sprintf('\\epsilon = %.1f', ev(k1)))
grid
axis([xlim -2 +2])
end
xlabel('Time')
I stored ‘x’ as a cell array because it’s easier than storing it as a multi-dimensional array. The first variable, ‘x(:,1)’ is blue and ‘x(:,2)’ is red in each plot. I used subplots because it’s easier to compare the plots that way. I also specified the time argument, ‘ts’ as a vector so that all the integrated values would be the same size. These choices are for convenience, and not required.