How to average over different length vectors without excessive for loops?
Show older comments
Hi there,
My problem involves running lots of different stochastic simulations (imagine some sort of Brownian motion) and then averaging over all of these different histories to compute quantites such as mean, variance etc
At the moment for each run I do have an output vector that that e.g. could be
X1 = [0 1 4 6 8]
where each new entry in the vector represents the position of a particle after a standard time increment. Here we have 5 elements of the vector so there have been 4 time increments. Although in practice these would be much longer. The problem is that each run ends when a certain condition is met (say X = 8) and this generically happens after differnt times. This means the next run might be something like
X2 = [0 4 8]
Which is only 3 elements long and thus only 2 time increments. I have done this for R number of runs. If each Xi vector had the same length I know I could simply collect them in one object X like so:
X = [X1; X2; ... XR]
and then compute the mean using the mean function in the appropriate direction. However unfortunately this wouldn't work in this case as the vectors are of different lengths.
For example if all I had was X1 and X2 I want some process that would calculate the mean at each timestep like so
mean1 = (X1(1)+X2(1))/2; mean2 = (X1(2)+X2(2))/2; mean3 = (X1(3)+X2(3))/2; %data at each timestep for X1 and X2 runs so average over both
mean4 = X1(4); mean5 = X1(5); %no X2 data for these timesteps so only averaging over X1 run
meanX = [mean1 mean2 mean3 mean4 mean5]
But obviously in a way that is scaleable without doing this process thousands of times using lots of for loops. In my actual code I have several thousand runs with each run having several hundred elements so this needs to be reasonably scaleable.
Thanks for any help people can offer and I'm obviously happy to try and clarify anything I have poorly explained
Accepted Answer
More Answers (2)
David Hill
on 1 Dec 2020
I would use a cell array.
for k=1:100
x{k}=randi(100,1,randi(1000));%simulate your outputs
end
Mean=zeros(1,100);
for k=1:100
Mean(k)=mean(x{k});%calculate the mean and whatever else you want
end
1 Comment
Categories
Find more on Loops and Conditional Statements 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!