Store a number of calculations within a matrix

Hi All
I am writing a small script with some functions to calculate 3 things. Velocity, acceleration and distance of a particle.
I use a while loop to increment the variable "time".
Each run through the loop, velocity, acceleration and distance are calculated using functions (i.e. I pass variables to a function and get the answer back).
This works fine. However, each loop overwrites the last. Ideally I would like to store each of the variables with time. i.e. a 2 column, n row matrix of [time, V], [time, a], [time, s]. Even better would be to have them all in one matrix ie [time, V, a, s], though I am unsure then how I would plot separate graphs for each.
Once I have that done I would then be aiming to save that matrix to a data file to open in Origin Labs. But that is another question (when I get to it!). This is my simple script:
D = 1e-6
R = D/2
Vol = (4/3)*pi*(D/2)^3
ro = 2000
mass = Vol*ro
viscosity = 1.81e-5
gravity = 9.81
time = 0
while(time<1)
V = Velocity(mass, viscosity, gravity, time, R);
a = Acceleration(mass, viscosity, gravity, time, R);
s = Distance(mass, viscosity, gravity, time, R);
time = time+1e-6;
percent = (time/1)*100
end
So before the time is stepped, I need to have stored my calculations with the time in a matrix of some sort. It is probably a simple thing to do but I am not a big user of matlab and I just can't see how it might be done.

 Accepted Answer

Store all results in variable R
i = 1;
while(time<1)
R(i, 1 ) = time;
R(i, 2) = Velocity(mass, viscosity, gravity, time, R);
R(i, 3) = Acceleration(mass, viscosity, gravity, time, R);
R(i, 4) = Distance(mass, viscosity, gravity, time, R);
time = time+1e-6;
percent = (time/1)*100
i = i + 1;
end
To plot
plot(R(:, 1), R(:, 2))
Write to file
dlmwrite('mydata.txt', R)

3 Comments

Ok I can see how that works.
I just tried it and I think, due to the time step I am using (1e-6, so there will be about 1 million rows) that this will not work. I got to 15% and could visibly see the process getting slower and slower with each loop.
Not sure there is any other way to do it. I may have to reduce my time step.
Pre-allocate R; if this does not speed up the computation, reduce stepsize.
stepsize = 1e-6;
R = nan(1/stepsize, 4); % preallocate to speed up
while...
Great thanks that works a treat!
Quick question re plotting. It is not critical but I cannot get Matlab to plot 3 separate graphs. I tried doing:
figure(1) plot.... figure(2) plot....
as I have seen elsewhere on the net, but matlab just produces a single figure with whichever plot was processed last. What is more is that it seems to like plotting a line between the first and last points. Not sure what is going on there, but I am intending to import the data into OriginLabs anyway.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!