how to calculate the average?

55 views (last 30 days)
Lilya
Lilya on 19 Oct 2021
Commented: Lilya on 19 Oct 2021
Hi,
I have a matrix that has a dimension of 200*59. I want to calculate the average of the first 6 rows for each column to get 1*59
I've written this loop
for i=1:59
Tavg(i)=nanmean(squeeze(temp(1:6,i)));
end
I am not sure if the loop is correct or not!
any help is appreciated

Accepted Answer

Kevin Holly
Kevin Holly on 19 Oct 2021
Edited: Kevin Holly on 19 Oct 2021
Lilya,
You do not need to create a for loop (see vectorization)
I would also suggest using the mean function instead.
temp = rand(200,59);%random matrix for demonstration purposes
Tavg = mean(temp(1:6,:)) %The first input is a vector of the rows 1 through 6 and the second input is a colon (:), which includes all elements (in this case all columns).
Tavg = 1×59
0.3738 0.6747 0.5105 0.5482 0.4596 0.3234 0.5693 0.2417 0.6018 0.6705 0.4275 0.6520 0.5644 0.3968 0.6870 0.4599 0.5968 0.5243 0.3118 0.4044 0.4199 0.4204 0.2583 0.6455 0.5059 0.5478 0.5277 0.6005 0.5665 0.3599
if you have NaN values that you want to ignore:
Tavg = mean(temp(1:6,:),'omitnan')
Tavg = 1×59
0.3738 0.6747 0.5105 0.5482 0.4596 0.3234 0.5693 0.2417 0.6018 0.6705 0.4275 0.6520 0.5644 0.3968 0.6870 0.4599 0.5968 0.5243 0.3118 0.4044 0.4199 0.4204 0.2583 0.6455 0.5059 0.5478 0.5277 0.6005 0.5665 0.3599
  1 Comment
Lilya
Lilya on 19 Oct 2021
Thank you very much!! that was helpful

Sign in to comment.

More Answers (0)

Categories

Find more on Multidimensional Arrays 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!