MATLAB: More efficient way to create a moving Quartile

avoiding loopsmatrix calculationquartilestime series

I've written a brief function to assign a quartile value to a number within any vector of numerical values (matrices are handled as column vectors). It is as follows:
function matrix = movQuantile( TS ) % Organizes a time series into an anchored Quartile
num_col = size(TS,2);
%define output dimensions matrix = NaN(length(TS),num_col);
for j = 1:num_col
for i = 1 :length(TS)
%Create a times series of from 1 to i, to create an anchored quartile
metric
temp =TS(1:i,j);
Q2=median(temp);
Q1 = median(temp(temp<Q2));
Q3 = median(temp(temp>Q2));
if TS(i,j)< Q1
x=1;
elseif TS(i,j) <Q2
x=2;
elseif TS(i,j) < Q3
x=3;
else
x=4;
end
matrix (i,j) = x;
end
end
end
My question is: is there a way to avoid the secondary loop from 1:length(TS) by using a matrix calculation? The program is slower than I'd like it to be, and this is the most intensive calculation point (especially since temp is getting longer with each iteration of i).
I'm somewhat new to matlab programming, so any help to increase processing time would be appreciated!
Thanks!
Jason

Best Answer

Did you know this (from the help): "numberOfElements = length(array) finds the number of elements along the largest dimension of an array. " So "for i = 1 :length(TS)" might not be doing what you think it does. Better to use
[rows columns] = size(TS);
for k = 1 : column % or rows, which ever you want.
By the way, don't use i (the imaginary variable) as a loop index.
And I don't see what's "Quartile" about it. You're going down each column one element at a time, calculating the median from the top row to the current row, then getting secondary medians of elements above, and below, the overall median. What about this is doing anything with quarters?
I don't see how this could be vectorized because the length of the strip that you're processing changes each time you move down a pixel. It's 1 the first time through, 2 long the second time through, 3 long the third time through, etc. So, of course, that explains why it takes longer with each iteration of i.
What effect does this have on the data anyway? What's its purpose?