Dynamic Array
Version 1.0.0.2 (8.56 KB) by
Serhan Yilmaz
Efficiently handle array resizing on the fly by dynamic allocation. Great for applications with unknown array sizes
DynamicArray is a versatile function that enables dynamic memory allocation for arrays with unknown sizes. It offers a convenient and efficient solution for scenarios where preallocating the array size is not feasible. By utilizing a factor growth strategy, the class dynamically expands the array by a certain percentage factor (default 2) whenever necessary, reducing the frequency of memory reallocation. This approach, with a theoretical cost of N·log(N) that is practically linear, strikes a good balance between performance and memory utilization.
The DynamicArray class provides flexibility by supporting two array types: numeric and cell arrays. Numeric arrays are initialized with zeros, while cell arrays are initialized with empty cells. The initial capacity of the array can be specified during instantiation, with a default value of 100 if not provided.
The class offers seamless methods for adding and inserting elements into the array. When the current capacity is insufficient, the array is automatically enlarged according to the factor growth strategy. The 'add' and 'insert' methods accept vector inputs and handle both numeric and cell arrays.
In the end, the 'finalize' method returns a trimmed version of the array, excluding any unused capacity. This feature is particularly useful when the final array needs to be passed to other parts of the program, ensuring that only relevant elements are included.
In summary, the DynamicArray class seamlessly combines the benefits of dynamic memory allocation and on-the-fly preallocation. It can offer convenience, relative efficiency, and flexibility for managing arrays with dynamic sizes, making it a valuable asset in a broad range of applications.
Example Usage:
myArray = DynamicArray(100);
% Generate and add 1000 random numbers to the array
for i = 1:10000
randomNumber = randi([1, 100]);
myArray.add(randomNumber);
end
myArray = myArray.finalize();
Example for cell arrays:
myCellArray = DynamicArray(100, 'cell');
% Generate and add 1000 random strings to the array
availableFruits = {'apple', 'banana', 'orange', 'grape'};
for i = 1:10000
randomNumber = randi([1, 4]);
str = availableFruits{randomNumber};
myCellArray.add(str);
end
myCellArray = myCellArray.finalize();
Cite As
Serhan Yilmaz (2024). Dynamic Array (https://www.mathworks.com/matlabcentral/fileexchange/129704-dynamic-array), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with
R2022b
Compatible with any release
Platform Compatibility
Windows macOS LinuxTags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.