2

I have an array that increases in size in a loop. the solution for that in matlab is pre-allocation with zeros using x = zeros(1, 9); my problem is that sometimes the array will have some zeros at the start and at the end of the array. those zeros are part of my data. and I need to work with the array when it's size is 5,later when it's 7, and finally when it has 9 elements. How do I work with them without confusing em with the pre-allocation zeros?

UPDATE The use of NANs is the easiest way, it worked well for me. altho Prashant posted a more complex solution that will work well for other requirements. (my function is quite simple.)

3 Answers 3

5

The easiest way is to pre-allocate it to NaN

dataArray = nan(nRows, nColumns) 

You can also just make sure that the rest of your code keeps track of your indexes, but NaNs are awfully easy.

Sign up to request clarification or add additional context in comments.

2 Comments

You can try NaN(nrows, ncols) or repmat(NaN, nrows, ncols) if you want to find out which one is faster.
I agree that nan(nRows, nColumns) is a better, clearer answer. Update made.
1

Track the size with a variable.
I'd need to know more about your usage to give you a specific answer, but consider something like this:

Preallocate max space for mem While looping over data sets Set k = 1 While looping over data set elements Add element to mem(k) Set k = k + 1 End Extract the data you want with mem(1:k-1) Use the extracted data End 

Matlab likes preallocated data because usually, you can know how big your set is going to be.

While looping over data sets Determine size of data set, and preallocate mem here with that size Set k = 1 While looping over data set elements Add element to mem(k) Set k = k + 1 End mem already has exactly the data you need, so begin using it End 

And of course, we prefer vector commands to get rid of loops and counter variables:

While looping over data sets Use vector calculation with only the input you need to produce only the output you need mem already has exactly the data you need, so begin using it End 

1 Comment

thanks for the answer. it seems good but way to complex for what i want to do. perhaps it could be better for more complex applications.
1

You could initialize the matrix in many ways including with NaN values, like x = nan * ones(1, 9); (or any other value you want to start with, if you replace nan with a value, depending on how you plan to fill it up).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.