Borrar filtros
Borrar filtros

Find average for each year

10 visualizaciones (últimos 30 días)
akk
akk el 9 de Dic. de 2018
Comentada: dpb el 18 de Dic. de 2018
Hi,
I have a column of years (yr) and a column of temperatures (temp). Both columns are 100000 data points long. I would like to circulate through all the data to find an average temp for each year (1996-2018). Im still learning how to write for loops. This is what I have so far:
k=1996;
for j=[1996:2018]; %years range from 1996-2018
k=k+1;
idx=find(yr==j);
meanT=mean(temp(idx));
end
Thanks for your help!

Respuesta aceptada

dpb
dpb el 9 de Dic. de 2018
That should work fine excepting you didn't allocate for the different means by year and overwrote the variable meanT on each iteration so all you have in the end is the last year average.
You could do something like:
yr1=min(yr); yr2=max(yr); % find first, last year in vector
meanT=zeros(yr2-yr1+1,1); % allocate vector for each year mean
k=0; % initialize mean storage counter
for j=yr1:yr2 % iterate over the year range found
k=k+1; % increment counter
meanT(k)=mean(temp(yr==j)); % compute mean for the year
end
NB: don't need find, the logical addressing vector works to return those locations w/o computing the indices explicitly.
This is fine for learning; the "Matlab way" is to use vector operations instead of loops -- investigate putting your data into a timetable and use the retime function to do this almost automagically.
  2 comentarios
akk
akk el 17 de Dic. de 2018
This worked perfect. Thank you! Now, say I wanted to find the monthly averages during each year. For example, Jan 1996, Jan 1997...Jan 2018.
dpb
dpb el 18 de Dic. de 2018
See the above comments re: retime and also check out findgroups and splitapply. TMW has done the heavy lifting already...

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by