preallocating memory without storing numbers
古いコメントを表示
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 件のコメント
Stephen23
2022 年 7 月 8 日
Perhaps preallocate using NAN() ?
Philine Baumert
2022 年 7 月 8 日
Steven Lord
2022 年 7 月 8 日
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
2022 年 7 月 8 日
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
2022 年 7 月 14 日
採用された回答
その他の回答 (1 件)
Jeffrey Clark
2022 年 7 月 9 日
@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);
カテゴリ
ヘルプ センター および File Exchange で Operators and Elementary Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!