From: Akim on
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?

Thanks.
From: Andy on
It would appear so:

n = 10000;
x=rand(1,n); % data
y=x; % copies
z=x;

tic
for ix=n:-1:500
x(ix) = []; % deleting from the end
end
toc

tic
for ix=1:n-499
y(1) = []; % deleting from the beginning
end
toc

tic
z(500:end) = []; % deleting all at once
toc

% displays:

Elapsed time is 0.517248 seconds.
Elapsed time is 0.516376 seconds.
Elapsed time is 0.001210 seconds.
From: Sean on
"Andy " <myfakeemailaddress(a)gmail.com> wrote in message <i43df8$ba6$1(a)fred.mathworks.com>...
> It would appear so:
>
> n = 10000;
> x=rand(1,n); % data
> y=x; % copies
> z=x;
>
> tic
> for ix=n:-1:500
> x(ix) = []; % deleting from the end
> end
> toc
>
> tic
> for ix=1:n-499
> y(1) = []; % deleting from the beginning
> end
> toc
>
> tic
> z(500:end) = []; % deleting all at once
> toc
>
> % displays:
>
> Elapsed time is 0.517248 seconds.
> Elapsed time is 0.516376 seconds.
> Elapsed time is 0.001210 seconds.

You also have to be careful with a for loop since the total length may not be as long at the end (after removing spots) when it was when you initialized the loop.
From: Andy on
> You also have to be careful with a for loop since the total length may not be as long at the end (after removing spots) when it was when you initialized the loop.

I don't follow you. The total length at the end will NECESSARILY be less than the length when you initialized the loop, since you're using the loop to remove elements from the array. Are you saying to be careful not to do the following?:

n = 1000;
x = rand(1,n);
for ix = 1:800
x(ix) = []; % will seem to work for a while, then will break
end
From: Sean on
"Andy " <myfakeemailaddress(a)gmail.com> wrote in message <i43hvm$rc0$1(a)fred.mathworks.com>...
> > You also have to be careful with a for loop since the total length may not be as long at the end (after removing spots) when it was when you initialized the loop.
>
> I don't follow you. The total length at the end will NECESSARILY be less than the length when you initialized the loop, since you're using the loop to remove elements from the array. Are you saying to be careful not to do the following?:
>
> n = 1000;
> x = rand(1,n);
> for ix = 1:800
> x(ix) = []; % will seem to work for a while, then will break
> end

I meant more like this:
x = rand(1,1000);
for ix = 1:length(x)
if(mod(100,ix)==0)
x(ix) = []; %This will cause an error at some point
end
end

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