preallocating memory without storing numbers
Mostrar comentarios más antiguos
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 comentarios
Stephen23
el 8 de Jul. de 2022
Perhaps preallocate using NAN() ?
Philine Baumert
el 8 de Jul. de 2022
Steven Lord
el 8 de Jul. de 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
el 8 de Jul. de 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
el 14 de Jul. de 2022
Respuesta aceptada
Más respuestas (1)
Jeffrey Clark
el 9 de Jul. de 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);
Categorías
Más información sobre Operators and Elementary Operations en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!