How to extract value at a given time in ode 45
Show older comments
I have solved an ode numerically for tspan [0 5] so an array is created for values of x at different t. The question is hoe can I extract value of x near say 2 and print it. I am asking this because I need to plot x(2.3) against a parameter.
Accepted Answer
More Answers (1)
KALYAN ACHARJYA
on 18 Jan 2021
Edited: KALYAN ACHARJYA
on 18 Jan 2021
Hope I have understood your question, if not, please do not hesitate to correct me.
Lets understand with an example, say t as array with range 0 to 5
t=0:5;
t =[0 1 2 3 4 5]
And you have evaluated the x, which is function of t, lets say x=t^2
>> x=t.^2
x=[0 1 4 9 16 25]
Now, you want to get the x value at t = 2.3, right? Lets plot the original data
t=0:5;
x=t.^2;
plot(t,x,'*');
hold on;
p=polyfit(t,x,7);
%7>Use polyfit to fit a 7th-degree polynomial to the points.
% Please see the other Polynomial order also
Create the data range as fiting datapoints
t1=linspace(0,5);
x1=polyval(p,t1);
plot(t1,x1);
See the results, original data points and fiting datapoints

Next, you want to get the x value the same as t = 2.3, x(2.3), In MATLAB or any other languages, you have to carefully deals with floating points numbers. Most cases 1.0 is not equal to 1. Refer the links, for more details Link1, Link2
Next the task is, get the indix position (idx) of t1, where t1 value is nearest to 2.3, hence I have used absolate (irrespective of sign) and get the minimum, please check the near_val, which is still not zero in subtraction cases, which menas the t1 datapoints is not exactly as 2.3, see other poly order and practice more.
t_req=2.3;
[near_val,idx]=min(abs(t1-t_req))
Results:
near_val =
0.0232
idx =
47
Once you get the idx, get the corresponding x values from the fitting data points, hence x1 value at idx index position
x1(idx)
Result:
ans =
5.4222
Hope this helps, I know, the answer is quite long, but it is a very important issue in the number of cases, so that it can help others too (novices).
Categories
Find more on Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!