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!