Using ODE, several errors with a spring system and function

조회 수: 1 (최근 30일)
Julia Russo
Julia Russo 2016년 7월 12일
답변: Mischa Kim 2016년 7월 13일
I am attempting to set up a function file for the following differential equation: (u''+ u + epsilon*u^3 = 0) with initial conditions: u(0) = 0, u'(0) = 1.
My variables are t, epsilon, and u, so my code for my function is:
function [ du ] = fu( t,e,u )
du= zeros(2,1);
du(1)= u(2);
du(2)= -(u(1))-e*(u(1))^3;
end
saved as 'F1'
when I run:
e=[0.0:.2:1.0]
t=[1 20]
ic=[0 1]
[T, U]=ode45('F1',t,e,ic)
I get a huge series of errors starting with: Attempted to access u(2); index out of bounds because numel(u)=0.
Error in F1 (line 3)
du(1)= u(2);
Please help me! I have no clue why this is not working and I'm extremely stuck.
  댓글 수: 2
James Tursa
James Tursa 2016년 7월 12일
What is the purpose of e being a vector? Are you trying to solve the ODE multiple times for multiple values of epsilon? Do you need help with how to pass that epsilon value into your F1 routine?
Robert Fennis
Robert Fennis 2016년 7월 12일
Have you saved all of your latest files? Also make sure the function fu has the same name as your file. I don't know if this causes the problem but you are not supposed to mix those up. Also, I see that they use a different syntax in the examples:
[t,y] = ode45(@vdp1,[0 20],[2; 0]);

댓글을 달려면 로그인하십시오.

답변 (1개)

Mischa Kim
Mischa Kim 2016년 7월 13일
Julia, use
function myODE()
e = 0.0:.2:1.0; % no brackets, the colons are used to define the vector
t = [1 20];
ic = [0; 1]; % column (not row) vector
for ii = 1:numel(e) % I guess you want to solve for different e?
[T, U] = ode45(@fu,t,ic,[],e(ii));
hold on
plot(T,U)
end
end
function [du] = fu(~,u,e)
du = [u(2); -(u(1))-e*(u(1))^3]; % like above, column not row vector
end
Put the code above into one .m file, name it myODE.m and run.

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by