how to calculate the average?

조회 수: 55 (최근 30일)
Lilya
Lilya 2021년 10월 19일
댓글: Lilya 2021년 10월 19일
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

채택된 답변

Kevin Holly
Kevin Holly 2021년 10월 19일
편집: Kevin Holly 2021년 10월 19일
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
Lilya
Lilya 2021년 10월 19일
Thank you very much!! that was helpful

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by