"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <i11dmt$1ee$1@fred.mathworks.com>...
>       
> It seems to me that you would save yourself a lot of grief by starting your forloop at the far end.
>
> for k = length(x)1:1:1
> if x(k) <= x(k+1)
> x(k) = [];
> end
> end
>
> That way when you do a delete it doesn't mess up the indexed positions of the elements yet to be tested and it requires only one pass through x.
All of the methods offered so far suffer from data copying. Every time you do the x(k) = [] operation MATLAB has to copy the entire dataset to a new memory location ... this is the same penalty you pay for increasing the size of an array incrementally in a loop, but here you are decreasing the size. To avoid this potentially massive time waste for large vectors, better to just remember the good spots and shrink all at once at the end. e.g.,
m = numel(x);
y = true(m,1); % everybody starts out OK
n = m;
for k = m1:1:1
if x(k) <= x(n)
y(k) = false; % this kth one gets deleted
else
n = k; % new max
end
end
x = x(y); % only one data set copy here
Comparing the for loop above (ltdelete) and the logical indexed loop (ltdelete2) gives, for example,
>> z = floor(rand(1,100000)*100);
>> x = z;
>> tic;ltdelete;toc
Elapsed time is 127.483428 seconds.
>> x
x =
99 97 96 65
>> x = z;
>> tic;ltdelete2;toc
Elapsed time is 0.004626 seconds.
>> x
x =
99 97 96 65
That's a lot of wasted time moving data around, and 100000 is only a moderately large array size.
James Tursa
