Last active
September 16, 2020 16:08
-
-
Save MarcinKonowalczyk/dbe5f33200868a05cf24c324f480c867 to your computer and use it in GitHub Desktop.
[Matlab] p'th percentile of vector x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function y = percentile(x,p) | |
%% y = percentile(x,p) | |
% Get p'th percentiles of vector x | |
% x must not have any NaNs or Infs | |
x = x(:); % Make sure x is a collumn | |
N = numel(x); | |
x = sort(x,1); | |
%% Fast median | |
if isequal(p,50) | |
if mod(N,2) % N is odd | |
y = x((N+1)/2,:); | |
else | |
y = (x(N/2,:) + x(N/2+1,:))/2; | |
end | |
return | |
end | |
%% Linearly interpolate between two points | |
p = p(:); % Make sure p is a collumn | |
r = (p/100)*(N-1)+1; % Fractional index into | |
k1 = floor(r); % Index before point | |
k2 = min(k1+1,N); % Index after point (+ overflow protection) | |
alpha = max(r-k1,0); % Lerp ratio (+ underflow protection) | |
y = (1-alpha).*x(k1) + alpha.*x(k2); % Linear interpolation (lerp) | |
y = reshape(y,size(p)); | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment