Store a number of calculations within a matrix

3 views (last 30 days)
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

Thorsten
Thorsten on 22 Jan 2013
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
Thorsten
Thorsten on 22 Jan 2013
Edited: Thorsten on 22 Jan 2013
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...
Alex Mason
Alex Mason on 22 Jan 2013
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)

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!