how to calculate the average?

56 次查看(过去 30 天)
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

更多回答(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