how to calculate the average?

55 visualizzazioni (ultimi 30 giorni)
Lilya
Lilya il 19 Ott 2021
Commentato: Lilya il 19 Ott 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

Risposta accettata

Kevin Holly
Kevin Holly il 19 Ott 2021
Modificato: Kevin Holly il 19 Ott 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

Più risposte (0)

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by