MATLAB Help with ODE45 and Plotting in MATLAB Loop

AI Thread Summary
The discussion focuses on using MATLAB's ODE45 function within a loop to solve ordinary differential equations and plot the results. The user seeks assistance in saving multiple outputs of time and solution vectors from each iteration of the loop, as well as plotting them without overwriting previous graphs. A suggested solution includes preallocating matrices for time and solution vectors and using the "hold on" command to maintain previous plots. However, the user encounters an issue with varying lengths of the output vectors, leading to dimension mismatch errors. The conversation emphasizes the need for consistent data handling to successfully plot all results simultaneously.
FlvD
Messages
4
Reaction score
0
Hey i need help in ODE45...i'm new to PF...pls help me

i have the following code

>>for i=1:5
>>tspan=[0 30]
>>h0=Hv(i)
>>[t,h]=ode45['a ODEfunction',tspan,h0]
>>plot(t,h)
>>end

in this loop how can i save 5 values of [t,h],
as t, h produces each loop run like follows
t=
1
2
3
4
.
.
.
h=
5
6
7
8..

also i need to plot all of them n i could view the 5 graphs them..pls help..
 
Physics news on Phys.org
You can add a line in the loop, after [t,h] = ode...

that goes:

ts(i,:) = t;
hs(i,:) = h;

but you might want to preallocate those vectors before the loop:

ts = zeros(5,n);
hs = zeros(5,n);

where n is the number of points in each set.The way you're plotting now, you wipe out your last plot every time. You can either add a "hold on" command that keeps the old data up when it plots the new data, or you can plot the whole set at once (hs).

also, ts, might won't be different every time as is, so you would have plot(t,hs) at the end OUTSIDE the for loop and it will plot all five cases at once, each a different color
 
Thanks for the replies..

@ Pythagoran..I tried the same way...But another problem arises

As in each go through the loop the length(t) & length(h) varies in the for loop.
Hence the command t(i,:) produces one result but then shows error as :

'Subscripted assignment dimension mismatch'...What to do..pls help me...?
 

Similar threads

Replies
5
Views
2K
Replies
2
Views
3K
Replies
1
Views
2K
Replies
4
Views
1K
Replies
8
Views
2K
Replies
4
Views
2K
Back
Top