MATLAB: Taking the median of the same matrix index over a series of matrices

digital image processingfiltermedian subtraction

I am trying to calculate the median of each matrix index over multiple matrices. For example:
A = [1 2 3; 4 5 6; 7 8 9];
B = [9 8 7; 6 5 4; 3 2 1];
C = [3 3 5; 6 7 4; 8 6 5];
All are 3×3 matrices and what I would like to do is to calculate the median of A(i,j), B(i,j), and C(i,j).
What I was thinking is to convert all matrices into an array, and compose a large matrix out of the strings. Like this:
A = A'; A = A(:)'
B = B'; B = B(:)'
C = C'; C = C(:)'
X = [A; B; C];
Med = median(X,'c');
Is there is a better way to do this? I am trying to do this to a series of 2048×2048 images and I would like to avoid unnecessarily large matrix operations.
Thanks in advance!

Best Answer

Manu - consider using cat to concatenate the three matrices into a 3D array as
D = cat(3,A,B,C);
where D(:,:,1) == A, D(:,:,2) == B and D(:,:,3) == C.
Now compute the median of D along the third dimension as
median(D,3)
which returns
3 3 5
6 5 4
7 6 5
which should be the median for A(i,j), B(i,j), and C(i,j).