Getting cetral weighted value in an Array

Hi there,
Suppose I have an Array
a = [0 0 1 1 1 2 3 5 6 7 7 99 100]
It's median value is 3 for sure, but center weighted value is 5 as if we assign weights to the array, then the weight matrix become
weight_a = [1 1 2 2 2 3 4 5 6 7 7 8 9]
whose center weight is 5. Is there any efficient way in Matlab to find the center weight? one way is to use unique function which discards duplicate values and give you an array with unique element, from that unique array, median value is the center weighted. But unique function is time consuming if you apply tic toc to it.
So is there any other way to find center weighted element.

Antworten (1)

Andrei Bobrov
Andrei Bobrov am 13 Aug. 2013
Bearbeitet: Andrei Bobrov am 14 Aug. 2013

0 Stimmen

a1 = sort(a(:));
out = median(a1([true;diff(a1)~=0]));
ADD
a1 = sort(a(:));
ii = find([true;diff(a1)~=0]);
i2 = ceil(numel(ii)/2);
out = a1(ii(i2));
or
i1 = unique(a);
out = i1(ceil(numel(i1)/2));

3 Kommentare

Sajid Khan
Sajid Khan am 13 Aug. 2013
It doesn't work when I have the following value of a.
a = [0 0 0 0 0 0 0 0 0 164 164 164 164 164 164 164 164 165 165 165 165 165 165 165 165 165 165 165 165 165 165 166 166 166 166 166 166 166 166 166 167 167 167 167 168 168 168 168 168 170 170 170 170 170 170 170 170 170 170 170 170 170 170 170 170 170 170 171 171 171 171 171 171 171 171 171 172 172 172 172 172 172 172 173 173 173 173 173 173 173 173 173 173 174 174 174 174 174 174 174 174 174 174 174 174 174 174 174 174 174 174 174 174 255 255 255 255 255 255 255 255];
in such case the value of "out" comes to be 169, which is not even a part of a.
Sajid Khan
Sajid Khan am 13 Aug. 2013
I think it's problem with median function that if I try to find median of following variable a = [ 0 164 165 166 167 168 170 171 172 173 174 255], it give me wrong value
Andrei Bobrov
Andrei Bobrov am 14 Aug. 2013
see ADD in this answer

Melden Sie sich an, um zu kommentieren.

Gefragt:

am 13 Aug. 2013

Community Treasure Hunt

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

Start Hunting!

Translated by