MATLAB Answers

Derivative from ode45

4 views (last 30 days)
jep
jep on 17 Apr 2020
Answered: madhan ravi on 17 Apr 2020
I have a code that solves a second order differential equation denoted in a function called dfq
clear all
close all
y0 = [0;0];
tspan = [0 15];
[t,y] = ode45(@dfq,tspan,y0);
xresp = y(:,1);
plot(t,xresp)
title('Solution Plot')
xlabel('t(s)')
ylabel('x(m)')
grid on
where the response x(t) is delivered and plotted through xresp. I need to plot the derivative of xresp, or x(t), and attempted to use diff to do this but it shortened the size of the vector and could not be plotted. I am wondering if there is a better way to graph the derivative. I also tried to use gradient on xresp, which did not give the correct derivative plot either.

  0 Comments

Sign in to comment.

Answers (2)

Peter
Peter on 17 Apr 2020
Edited: Peter on 17 Apr 2020
Generally I send the result of ode45 back through my function as a post-processing step.
[t,x] = ode45(@myDerivFcn,tspan,x0)
You just need to be a little cautious of the problem dimensionality. arrayfun can be a neat trick if you've got a one-dimensional system or don't mind manipulating the cell array after the fact. Otherwise, a venerable for loop works:
dx = nan(n_dims_x,length(t))
for ix=1:length(t)
dx(:,ix) = myDerivFcn(t(ix),x(ix,:).') % Col major fill
end
dx = dx.' % Now it matches the dimensionality of x and has length(t) rows

  0 Comments

Sign in to comment.


madhan ravi
madhan ravi on 17 Apr 2020
y(:,2)

  0 Comments

Sign in to comment.

Tags


Translated by