MATLAB: Speeding up a loop

for loopvectorization

I have made a simple loop that works fine when dealing with small datasets, but takes ages to run when L is 10^6 in size – which unfortunately is the size I need to work with. I'm sure you can tell by the code itself I'm a matlab newbie, so any ideas on how this can be sped up would be very much appreciated. I've read about vectorisation but cannot work out how to vectorise this code.
C=cumsum(S);
L=length(C);
X=zeros(1,L)';
for i=1:L;
if C(i)>min(C(i:L));
X(i);
else
X(i)=1;
end
end

Best Answer

The main work is done in the repeated determination of the minimum. But this can be avoided easily:
% Cummumaltive minimum in backward direktion:
minC = zeros(size(C));
v = C(end);
for ii = numel(C):-1:1
if C(ii) < v
v = C(ii);
end
minC(ii) = v;
end
X = zeros(L, 1);
X(C <= minC) = 1;
Sorry, I cannot test this currently and I have the feeling that the logic is not correct. But at least the general idea could be helpful.
Btw.: This line wastes time only:
X(i);