How to Preallocate a Matrix in Matlab for a 'While' Loop?

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

1 Answer

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest