Calculate median with accumarray

5 visualizaciones (últimos 30 días)
franky
franky el 4 de Oct. de 2018
Respondida: Bruno Luong el 4 de Oct. de 2018
Hello,
I have an array with two columns. The rows are sorted by the values of the first column and then indexed by the use of histc. Now I want to calculate the median of every interval for the columns. Procedure for the first column is clear with accumarray but before calculating the median for the second column I have to sort every interval, right? How can I do this?
groupMedian = accumarray(ID,Measurement(:,2),[],@median);

Respuesta aceptada

Walter Roberson
Walter Roberson el 4 de Oct. de 2018
Editada: Walter Roberson el 4 de Oct. de 2018
No, you do not need to sort each interval. Just make sure that each interval is given a distinct ID vector row.
[unique_col1, ~, ID] = unique(Measurement(:,1));
group_median = accumarray(ID, Measurement(:,2), [], @median);
output = [unique_col1, group_median];
No sorting by column 1 beforehand is needed (unless you happen to need that output for a different purpose.)

Más respuestas (2)

Bruno Luong
Bruno Luong el 4 de Oct. de 2018
Internally the median command "sort" input data and take a middle element of the sorted array (or average of two left and right for even length array). Some other technique exists, such as partial-sorting which has better complexity than SORT (I don't think MATLAB use it however the last time I check it)
You, as user don't have to sort it when calling median, that's how the function like this exists at the first hand.

franky
franky el 4 de Oct. de 2018
I read in some statistic books that it is necessary to sort the values before calculating the median. After indexing the columns column 1 is sorted but values with the same ID in column 2 are not necessary sorted. So I think this is a problem or does Matlab sort the values in the median function automatically?
  1 comentario
Walter Roberson
Walter Roberson el 4 de Oct. de 2018
It is not required to sort the values before calling median()
data = randi(20, 1, 1000);
>> median(data)
ans =
11
>> median(data(randperm(length(data))))
ans =
11

Iniciar sesión para comentar.

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Productos


Versión

R2012b

Community Treasure Hunt

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

Start Hunting!

Translated by