Pre allocate memory for unknown variable size

2 views (last 30 days)
Hello Everyone,
I have a cell array whose dimensions are 1000*1 . These are sensor scans from a laser and always I get a cell array with above dimensions. When the sensor is ON the data gets stored in the above cell array.
So for example in trial 1 laser sensor is ON for 5 seconds then the cell array has data in only first 180 cells,the rest of the cells are empty. In the trial 2 laser sensor maybe ON for 6 seconds and I can get data in 200 cells.
Currently I am using a for loop to iterate through the cell array and check and store data for non-zero elements. But this reduces speed of my code as I am not able to pre allocate memory.
Can anyone suggest an alternative method.
Regards
  1 Comment
Jan
Jan on 22 May 2013
Please post the code you use. Otherwise it is hard to suggest improvements. Perhaps a cellfun('isempty', C) is sufficient already, or an extra list of occupied indices.

Sign in to comment.

Accepted Answer

Iain
Iain on 22 May 2013
Preallocate to the largest size you will ever need, and for the unused elements, you can set them to a known bad value. eg. NaN, Inf, -Inf, or clear those elements with:
Returned(57:end) = [];

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!