preallocating memory without storing numbers
Show older comments
Hi all,
I have several vectors that grow duing a for loop. I know that you should preallocate the size using zeros for speed. My problem is that filling the vectors with zeros interferes with how the elements of the vectors are created; essentially, the vectors have to be empty for it to do what I need.
Is there a way to preallocate memory but have the vectors contain any values/ elements?
Thanks in advance!
5 Comments
Stephen23
on 8 Jul 2022
Perhaps preallocate using NAN() ?
Philine Baumert
on 8 Jul 2022
Steven Lord
on 8 Jul 2022
Can you show us a small example of how you're creating and working with this data? If we see what you're doing now, we may be able to offer suggestions for the right approach to work with your code (or alternate approaches that may work better for your specific problem.)
David Goodmanson
on 8 Jul 2022
Hi Philine,
Just for fun here is a 0x100 empty vector of doubles:
a = find(3<(1:2)')
a = 0×1 empty double column vector
b = repmat(a,1,100)
b = 0×100 empty double matrix
(Not that you could actually use it for anything, since its first dimension is 0).
Philine Baumert
on 14 Jul 2022
Accepted Answer
More Answers (1)
Jeffrey Clark
on 9 Jul 2022
@Philine Baumert, keeping others in the dark doesn't shed any more light on finding what's hidden. So an answer doesn't seem possible, except maybe this:
myData = zeros(10,20); % dimensions as needed for your expected calculations
isData = false(size(myData)); % critical to keep these dimensions the same
%Do your work here and always set isData true when setting myData
while sum(isData,'all')<numel(myData)/2
i = randi([1 size(myData,1)]);
j = randi([1 size(myData,2)]);
myData(i,j) = randn;
isData(i,j) = true;
end
% Valid results in myData(isData) - note tha regardless of myData being a
% vector, matrix or higher dimension, myData(isData) is a vector. if you
% really need to know the indexs of where the data is (e.g., matrix or
% higher and you really need to know), something like this:
[wasi,wasj] = find(isData);
Categories
Find more on Operators and Elementary Operations 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!