首先將陣列排序
如果元素數量是奇數,取最中間那個元素;
如果元素數量是偶數,取最中間兩個元素的算術平均值。
>>editmedian
functiony=median(x,dim)
%MEDIANMedianvalue.
%Forvectors,MEDIAN(X)isthemedianvalueoftheelementsinX.
%Formatrices,MEDIAN(X)isarowvectorcontainingthemedian
%valueofeachcolumn.ForN-Darrays,MEDIAN(X)isthemedian
%valueoftheelementsalongthefirstnon-singletondimension
%ofX.
%
%MEDIAN(X,DIM)takesthemedianalongthedimensionDIMofX.
%Example:IfX=[012
%345]
%thenmedian(X,1)is[1.52.53.5]andmedian(X,2)is[1
%4]
%ClasssupportforinputX:
%float:double,single
%SeealsoMEAN,STD,MIN,MAX,VAR,COV,MODE.
%Copyright1984-2005TheMathWorks,Inc.
%$Revision:5.15.4.6$$Date:2005/05/3116:30:47$
%Calculationmethodforevenlists:b-(b-a)/2.
%Thismethodreducesthelikelihoodofroundingerrors.
nInputs=nargin;
ifisempty(x)
ifnInputs==1
%Theoutputsizefor[]isaspecialcasewhenDIMisnotgiven.
ifisequal(x,[]),y=nan(1,class(x));return;end
%Determinefirstnonsingletondimension
dim=find(size(x)~=1,1);
end
s=size(x);
ifdim<=length(s)
s(dim)=1;%Setsizeto1alongdimension
y=nan(s,class(x));
elseifnInputs==1&&isvector(x)
%Ifinputisavector,calculatesinglevalueofoutput.
x=sort(x);
nCompare=numel(x);
half=floor(nCompare/2);
y=x(half+1);
if2*half==nCompare%Averageifevennumberofelements
y=meanof(x(half),y);
ifisnan(x(nCompare))%ChecklastindexforNaN
y=nan(class(x));
else
ifnInputs==1%Determinefirstnonsingletondimension
ifdim>length(s)%Ifdimensionistoohigh,justreturninput.
y=x;
return
%Sortalonggivendimension
x=sort(x,dim);
nCompare=s(dim);%Numberofelementsusedtogenerateamedian
half=floor(nCompare/2);%Midwaypoint,usedformediancalculation
ifdim==1
%Ifcalculatingalongcolumns,usevectorizedmethodwithcolumn
%indexing.Reshapeatendtoappropriatedimension.
y=x(half+1,:);
if2*half==nCompare
y=meanof(x(half,:),y);
y(isnan(x(nCompare,:)))=NaN;%ChecklastindexforNaN
elseifdim==2&&length(s)==2
%Ifcalculatingalongrows,usevectorizedmethodonlywhenpossible.
%Thisrequirestheinputtobe2-dimensional.Reshapeatend.
y=x(:,half+1);
y=meanof(x(:,half),y);
y(isnan(x(:,nCompare)))=NaN;%ChecklastindexforNaN
%Inallothercases,uselinearindexingtodetermineexactlocation
%ofmedians.Uselinearindicestoextractmedians,thenreshapeat
%endtoappropriatesize.
cumSize=cumprod(s);
total=cumSize(end);%EquivalenttoNUMEL(x)
numMedians=total/nCompare;
numConseq=cumSize(dim-1);%Numberofconsecutiveindices
increment=cumSize(dim);%Gapbetweenrunsofindices
ixMedians=1;
y=repmat(x(1),numMedians,1);%Preallocateappropriatetype
%NestedFORlooptracksdownmediansbytheirindices.
forseqIndex=1:increment:total
forconsIndex=half*numConseq:(half+1)*numConseq-1
absIndex=seqIndex+consIndex;
y(ixMedians)=x(absIndex);
ixMedians=ixMedians+1;
%Averageinsecondvalueifniseven
forconsIndex=(half-1)*numConseq:half*numConseq-1
y(ixMedians)=meanof(x(absIndex),y(ixMedians));
%ChecklastindicesforNaN
forconsIndex=(nCompare-1)*numConseq:nCompare*numConseq-1
ifisnan(x(absIndex))
y(ixMedians)=NaN;
%Nowreshapeoutput.
s(dim)=1;
y=reshape(y,s);
%============================
functionc=meanof(a,b)
%MEANOFthemeanofAandBwithB>A
%MEANOFcalculatesthemeanofAandB.Itusesdifferentformula
%inordertoavoidoverflowinfloatingpointarithmetic.
c=a+(b-a)/2;
k=(sign(a)~=sign(b))|isinf(a)|isinf(b);
c(k)=(a(k)+b(k))/2;
首先將陣列排序
如果元素數量是奇數,取最中間那個元素;
如果元素數量是偶數,取最中間兩個元素的算術平均值。
>>editmedian
functiony=median(x,dim)
%MEDIANMedianvalue.
%Forvectors,MEDIAN(X)isthemedianvalueoftheelementsinX.
%Formatrices,MEDIAN(X)isarowvectorcontainingthemedian
%valueofeachcolumn.ForN-Darrays,MEDIAN(X)isthemedian
%valueoftheelementsalongthefirstnon-singletondimension
%ofX.
%
%MEDIAN(X,DIM)takesthemedianalongthedimensionDIMofX.
%
%Example:IfX=[012
%345]
%
%thenmedian(X,1)is[1.52.53.5]andmedian(X,2)is[1
%4]
%
%ClasssupportforinputX:
%float:double,single
%
%SeealsoMEAN,STD,MIN,MAX,VAR,COV,MODE.
%Copyright1984-2005TheMathWorks,Inc.
%$Revision:5.15.4.6$$Date:2005/05/3116:30:47$
%Calculationmethodforevenlists:b-(b-a)/2.
%Thismethodreducesthelikelihoodofroundingerrors.
nInputs=nargin;
ifisempty(x)
ifnInputs==1
%Theoutputsizefor[]isaspecialcasewhenDIMisnotgiven.
ifisequal(x,[]),y=nan(1,class(x));return;end
%Determinefirstnonsingletondimension
dim=find(size(x)~=1,1);
end
s=size(x);
ifdim<=length(s)
s(dim)=1;%Setsizeto1alongdimension
end
y=nan(s,class(x));
elseifnInputs==1&&isvector(x)
%Ifinputisavector,calculatesinglevalueofoutput.
x=sort(x);
nCompare=numel(x);
half=floor(nCompare/2);
y=x(half+1);
if2*half==nCompare%Averageifevennumberofelements
y=meanof(x(half),y);
end
ifisnan(x(nCompare))%ChecklastindexforNaN
y=nan(class(x));
end
else
ifnInputs==1%Determinefirstnonsingletondimension
dim=find(size(x)~=1,1);
end
s=size(x);
ifdim>length(s)%Ifdimensionistoohigh,justreturninput.
y=x;
return
end
%Sortalonggivendimension
x=sort(x,dim);
nCompare=s(dim);%Numberofelementsusedtogenerateamedian
half=floor(nCompare/2);%Midwaypoint,usedformediancalculation
ifdim==1
%Ifcalculatingalongcolumns,usevectorizedmethodwithcolumn
%indexing.Reshapeatendtoappropriatedimension.
y=x(half+1,:);
if2*half==nCompare
y=meanof(x(half,:),y);
end
y(isnan(x(nCompare,:)))=NaN;%ChecklastindexforNaN
elseifdim==2&&length(s)==2
%Ifcalculatingalongrows,usevectorizedmethodonlywhenpossible.
%Thisrequirestheinputtobe2-dimensional.Reshapeatend.
y=x(:,half+1);
if2*half==nCompare
y=meanof(x(:,half),y);
end
y(isnan(x(:,nCompare)))=NaN;%ChecklastindexforNaN
else
%Inallothercases,uselinearindexingtodetermineexactlocation
%ofmedians.Uselinearindicestoextractmedians,thenreshapeat
%endtoappropriatesize.
cumSize=cumprod(s);
total=cumSize(end);%EquivalenttoNUMEL(x)
numMedians=total/nCompare;
numConseq=cumSize(dim-1);%Numberofconsecutiveindices
increment=cumSize(dim);%Gapbetweenrunsofindices
ixMedians=1;
y=repmat(x(1),numMedians,1);%Preallocateappropriatetype
%NestedFORlooptracksdownmediansbytheirindices.
forseqIndex=1:increment:total
forconsIndex=half*numConseq:(half+1)*numConseq-1
absIndex=seqIndex+consIndex;
y(ixMedians)=x(absIndex);
ixMedians=ixMedians+1;
end
end
%Averageinsecondvalueifniseven
if2*half==nCompare
ixMedians=1;
forseqIndex=1:increment:total
forconsIndex=(half-1)*numConseq:half*numConseq-1
absIndex=seqIndex+consIndex;
y(ixMedians)=meanof(x(absIndex),y(ixMedians));
ixMedians=ixMedians+1;
end
end
end
%ChecklastindicesforNaN
ixMedians=1;
forseqIndex=1:increment:total
forconsIndex=(nCompare-1)*numConseq:nCompare*numConseq-1
absIndex=seqIndex+consIndex;
ifisnan(x(absIndex))
y(ixMedians)=NaN;
end
ixMedians=ixMedians+1;
end
end
end
%Nowreshapeoutput.
s(dim)=1;
y=reshape(y,s);
end
%============================
functionc=meanof(a,b)
%MEANOFthemeanofAandBwithB>A
%MEANOFcalculatesthemeanofAandB.Itusesdifferentformula
%inordertoavoidoverflowinfloatingpointarithmetic.
c=a+(b-a)/2;
k=(sign(a)~=sign(b))|isinf(a)|isinf(b);
c(k)=(a(k)+b(k))/2;