Clear Filters
Clear Filters

Combine rows generated in for loop

1 view (last 30 days)
Patrick
Patrick on 10 Feb 2015
Edited: Patrick on 10 Feb 2015
I use for loop to generate a row matrix of 1x3 per loop. For every three consecutive rows generated, I want to calculate the mean of each column of the 3 row matrices. It will give a result of one 1x3 row matrix. Let's say the for loop runs 210 times, there should be 70 rows, which are the row matrices of mean. Then, I want to group these 70 rows into one matrix.
How can I compute the mean of each column of every 3 generated row matrices? Then, combine row matrices of mean? Thanks for all advice!

Accepted Answer

dpb
dpb on 10 Feb 2015
Wait until you're done, then use the "magic" of Matlab internal storage order and rearranging...let's do a small example to show the idea--
>> x=rand(6,3) % generate small sample data set...
x =
0.7094 0.1190 0.7513
0.7547 0.4984 0.2551
0.2760 0.9597 0.5060
0.6797 0.3404 0.6991
0.6551 0.5853 0.8909
0.1626 0.2238 0.9593
>> reshape(x,3,[]) % reshape based on number to average
ans =
0.7094 0.6797 0.1190 0.3404 0.7513 0.6991
0.7547 0.6551 0.4984 0.5853 0.2551 0.8909
0.2760 0.1626 0.9597 0.2238 0.5060 0.9593
>> mean(ans) % and take the mean; Matlab works by column by default
ans =
0.5800 0.4991 0.5257 0.3832 0.5041 0.8498
>> reshape(ans,2,[]) % reshape back to three columns and voila!!!
ans =
0.5800 0.5257 0.5041
0.4991 0.3832 0.8498
>> [mean(x(1:3,:)); mean(x(4:6,:))] % check it's right...
ans =
0.5800 0.5257 0.5041
0.4991 0.3832 0.8498
>>
OK, so to do the above in general
nAvg=3;
N=length(x);
nAvgMeans=reshape(mean(reshape(x,nAvg,[])),N/nAvg,[]);
  1 Comment
Patrick
Patrick on 10 Feb 2015
Edited: Patrick on 10 Feb 2015
Really a nice flow! Thanks for your help!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!