how to preallocate a matrix in Matlab for a 'while' loop?

496 Views Asked by At

I want to preallocate a matrix in matlab to get rid of out of memory error, but how can i use preallocating for a while loop? we use preallocating for a for loop like this:

m=10000;
x=zeros(m,1)

for i = 1:m
    x(i) = i
end

but what if i want to do this for a while loop

m = 10000
x = 1
i=0
some_criteria = 10
while x<some_criteria
     i = i+1
     x(i) = i
     some_criteria = f(x)
end
1

There are 1 best solutions below

2
CuriousCat11 On

try this:

 m = 10000
x=zeros([],1);
i=0
some_criteria = 10
while x<some_criteria
     i = i+1
     x(i,1) = i
     some_criteria = f(x)
end

if you write x(i) instead of x(i,1), the result will be a row vector.