csss
csss

Reputation: 1997

Removing unwanted elements from tail of array?

I have an 100x1 array that starts with 100 zeros,

roots = zeros(100, 1);

I then have a loop in which an element this array gets filled on every iteration.

for iRoots = 1:100
    roots(iRoots) = a;

However if a certain condition is met the loop terminates early and I am left with a lot of unneccessary zeros in the array. For example I might be end up with a roots array like this:

charVals = [ 1  5  2  2  8 0 0 0 ... 0 ]

I only want to keep the first five non zero elements. How do I delete all the zeros from this array?

Upvotes: 0

Views: 58

Answers (1)

user2261062
user2261062

Reputation:

When the loop terminates early you will still have the value of the latest executed index, so just do:

roots(iRoots:end) = [];

Besides if you check for conditions to terminate a loop early, you might consider using a while loop instead of a for loop.

Upvotes: 1

Related Questions