Using ode45 and plot
8 次查看(过去 30 天)
显示 更早的评论

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?
0 个评论
采纳的回答
Star Strider
2015-7-10
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.
9 个评论
Star Strider
2015-7-12
My pleasure!
I’m not quite sure what you mean by ‘green function’. (I am using R2015a, and it uses the parula colormap as its default. The lines were blue and red when I plotted them.) In my code, I plotted both the function ‘x(:,1)’ and the first derivative, ‘x(:,2)’.
To plot only the function and not the derivative, just plot ‘x(:,1)’, or equivalently (in my latest code that also detects the first zero-crossing), the ‘xv’ variable. Since I saved them as cells, it will probably be easier to create and plot ‘xv’.
saddam mollah
2018-7-9
编辑:saddam mollah
2018-7-9
Can you plot this problem in 3dimension as: t along x-axis, ev along y-axis and x1 along z-axis? Thank you in advance.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!