how to calculate the average?

41 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by