From: Sean on
"Sean " <sean.dewolski(a)nospamplease.umit.maine.edu> wrote in message <i43itl$r5n$1(a)fred.mathworks.com>...

> You would want a while loop
> ix = 1;
> while ix < length(x)
> %would be stable
> if(mod(100,ix)==0)
> x(ix) = []; %This will cause an error at some point
> else
> ix = ix+1;
> end
> end

That was a bad example since it's using an unchanging ix for its criterion to delete. Thus it would delete the whole thing.
I meant something like this:
if(mod(100,x(ix))==0)
From: James Tursa on
"Akim " <aaa(a)bbb.ccc> wrote in message <i43bor$n7h$1(a)fred.mathworks.com>...
> Dear all,
>
> I know that growing with indexing,
>
> clear x
> for i=1:10
> x(i)=1;
> end,
>
> is not recommended.
>
> My question: does shrinking with indexing,
>
> x=ones(1,10);
> for i=1:10
> x(1)=[];
> end,
>
> cause memory problems? I.e. does Matlab reallocate memory for variable x every time x(1)=[]; is executed?

Yes. Shrinking an array with [] inside a loop is exactly the same problem as growing an array inside a loop. In both cases MATLAB will be forced to copy the array at each iteration. There *is* a way to delete the *last* column of an array without a data copy involved using a mex routine, but that is likely beyond the scope of this thread.


James Tursa
From: Andy on
Sean, I see your point. Since the while loop recalculates length(x) on each loop iteration, you won't accidentally index outside the bounds of x. I would argue, however, that both of these loops are quite dangerous in that they present a silent error: it seems the intent is to eliminate every 100th element of x. But of course this is not what either loop does.

It should be pointed out that shrinking an array in a loop did not give a warning in m-lint:

for ix = 1:100
x(ix) = rand; % warning
end

for ix = 100:-1:1
x(ix) = []; % no warning
end