# Pre allocation do not work ...

조회 수: 6(최근 30일)
Gauthier Briere 2020년 2월 3일
댓글: Raj 2020년 2월 3일
Hi everyone,
I am a bit lost,
I ran a code this morning and the pre allocation do not work, it changes the size of my matrices with any reason,
So I did a small try like this :
n=3
x = zeros(1,n);
for ii=1:10
x( ii ) = ( ii );
end
%
Before I got an error because the size just exceeds... now it works, it changes the size of x, how to avoid that ?
Best regards,
##### 댓글 수: 1표시숨기기 없음
Adam 2020년 2월 3일
Pre-size it correctly! You pre-size it to 3 then put it in a for loop up to 10 assignging values to it. Where do you expect the next 7 elements to come from? You didn't pre-allocate those so the array grows in the loop.

댓글을 달려면 로그인하십시오.

### 채택된 답변

Raj 2020년 2월 3일
Question is not clear. What exactly are you trying to do here?The pre allocation works fine. You can check it by putting breakpoints in your code. The loop simply overwrites the pre allocated matrix. If you want to stop the loop when the execution reaches the preallocated matrix size then use something like this:
n=3
x = zeros(1,n);
temp=length(x);
for ii=1:10
x( ii ) = ( ii );
if ii==temp
break
end
end
%
##### 댓글 수: 4표시숨기기 이전 댓글 수: 3
Raj 2020년 2월 3일
Thanks for the explanation!

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

Gauthier Briere 2020년 2월 3일
That's my point ! before I got normally an error saying that the indices exceed the size of the matrice.
If I do this example
n=3;
m=9;
x = zeros(n,m);
for ii=1:n
for jj=1:m
x(ii,jj) = ii;
end
end
and you change by :
n=3;
m=9;
x = zeros(n,m);
for ii=1:n
for jj=1:240151
x(ii,jj) = ii;
end
end
It will change the size of x which is really weird because before it never changed the size....
##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
Gauthier Briere 2020년 2월 3일
Ok I think I got it, thanks for your help, I just misunderstood

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!