average value of group of cells in a matrix
12 views (last 30 days)
Show older comments
Commented: Mohammad Aljarrah on 1 Jun 2021
hi, i have a question that might souund silly, but i am a beginner in MATLAB. i have a matrix that is 20x20. i want to find the average values for each 4 rows and columns, for example (1:4,1:4) then (1:4, 5:8), ... , (1:4,16:20), then proceed to the next group for until i find the average of the final group which is for (16:20,16:20), and then i want to put them in a list. i know this can be easily done in a for loop (or maybe two for loops), but i am still confused on how to do it. appreciate any help. i put a figure to ease imagining the problem.
what i have so far is:
but this gives the average only for the diagonal groups!
Sulaymon Eshkabilov on 1 Jun 2021
Take a look this help discussion on mean calcs of cell arrays:
Jakob B. Nielsen on 1 Jun 2021
Edited: Jakob B. Nielsen on 1 Jun 2021
You are on the right track! You do, indeed, want to use two for loops, because you are trying to perform operations in two dimensions.
A for loop can be specified to take steps of any size. You want steps of 4, and you specify it by saying for i=1:4:17 which means for i starting at 1, taking steps of 4 every increment until you reach 17. 17 you say? Yes, because if you start at 17 and then add 3 within the loop, you hit 20 :) (note that you can also write for i=1:4:20 but it will stop at 17, so stopping it at 17 in the script just looks prettier).
The obvious challenge now is that you lose the ability to dynamically index your results within the loop, since the loop counter jumps by 4. I am sure more clever people than me have a clever way to go about this, but I usually just make my own counter which I can then increase by 1 every loop iteration...
x=rand(20,20); %An example of just a 20 by 20 with random numbers
counter1=1; %my loop counters, starting at 1
for i=1:4:20 %this gives you one dimension - so either along rows, or along columns
for j=1:4:20 %and here you get the second dimension
%You can now perform operations in steps of 4, and index them to
%your custom counters. You go from j to j+3, which gives you from 1
%to 4 the first go, 5 to 8 the next go and so on.
counter1=counter1+1; %increase the counter by one - but just in the
% "j" direction inside the j loop
%After we are done with the first full j loop, reset the "j" counter to
%1, and increment the "i" counter by 1:
More Answers (0)
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!