trouble coding for ODE's

1 view (last 30 days)
C
C on 17 Dec 2021
Answered: Star Strider on 17 Dec 2021
Given 𝑚𝑥̈+ 𝑐𝑥̇ + 𝑘𝑥 = 𝑠𝑖𝑛(𝜔𝑡) I need to write a code that prompts the user to input values for m, c, k and 𝜔, then to find the general solution of the ODE. Then it needs to find the exact solution of the ODE using time array between 0s and 10s with a step of 0.1 s, given that 𝑥(0) = 0 and 𝑥̇(0) = 1.
  2 Comments
C
C on 17 Dec 2021
syms x(t) m c k w % these are the terms in the ode
ode=m.*diff(diff(x(t),t))+c.*diff(x(t),t)+k.*x(t)== sin(w.*t); % this is the given ode
gen_sol=dsolve(ode) % this provides the general solution
M=input('Enter a value for the mass: ');
C=input('Enter a value for the damping coefficient: ');
K=input('Enter a value for the spring constant: ');
W=input('Enter a value for the frequency: ');
new_soln=subs(gen_sol,{'m' 'c' 'k' 'w'},{M,C,K,W}) % subs input values for variables
t=0:.1:10
exact_soln=dsolve(new_soln, 'x(0)=0','diff(x(0))=1')

Sign in to comment.

Answers (2)

Mitchell Thurston
Mitchell Thurston on 17 Dec 2021
this is definintely an inefficient way of doing it, but this accomplishes everything
syms dx(t) x(t) m c k w % these are the terms in the ode
dx = diff(x);
ode=m.*diff(diff(x(t),t))+c.*diff(x(t),t)+k.*x(t)== sin(w.*t); % this is the given ode
M=input('Enter a value for the mass: ');
C=input('Enter a value for the damping coefficient: ');
K=input('Enter a value for the spring constant: ');
W=input('Enter a value for the frequency: ');
new_eqn=subs(ode,{'m' 'c' 'k' 'w'},{M C K W})
new_sol=dsolve(new_eqn, x(0)==0, dx(0)==1)
fplot(new_sol, [0,10])
% to get the exact value at the timestep
t = 0:.1:10;
xt = zeros(size(t));
for i =1:length(t)
xt(i) = sym2poly(subs(new_sol,'t',t(i)));
end

Star Strider
Star Strider on 17 Dec 2021
The code works as far as it goes. The code needs to include initial conditions for and as separate parameters (call them and or something else appropriate), include them in the dsolve call as arguments, and use the simplify function to simplify the resulting expression, with 'steps',500 to be certain it simplifies as much as possible. Then use the matlabFunction function (use the name-value pair 'Vars' argument, and provide it appropriate associated values) to produce an anonymous function that can be executed numerically. Then, supply the appropriate arguments to the anonymous function and the appropriate time vector to complete the assignment.
.

Community Treasure Hunt

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

Start Hunting!