필터 지우기
필터 지우기

Preallocate a variable of unknown size

조회 수: 1 (최근 30일)
Akbar
Akbar 2018년 5월 24일
댓글: Akbar 2018년 5월 24일
Please help to preallocate the variable "D". Its size is unknown.
clc;
D = {};
Di = [];
r = 1;
N = length(nodes.PrtCtyAll);
DstBlocks = cell(N,1);
for i = 1:N % Iterate through PrtCtyAll
for j = 1 : length(nodes.PrtCtyAll{i})
DstBlocks{i}{j,1} = nodes.PrtCtyAll{i}(j).DstBlock;
end
for k = 1 : length(DstBlocks{i})
if (~isempty(DstBlocks{i}{k}) && length(DstBlocks{i}{k})==1)
D{end+1,1} = DstBlocks{i}{k};
r = r + 1;
else
for z = 1:length(DstBlocks{i}{k})
D{end+1,1} = DstBlocks{i}{k}(z);
end
end
end
% Get Indices
for a = 1:length(D)
Di(a) = find(abs(nodes.Handles-D{a}) < 0.1);
end
Si = find(abs(nodes.Handles-nodes.Handles(i)) < 0.1);
Di = [];
D = {};
end
clear i j k r z a N D Di Si

채택된 답변

Guillaume
Guillaume 2018년 5월 24일
That's some overly complicated code there. For example,
for j = 1 : length(nodes.PrtCtyAll{i})
DstBlocks{i}{j,1} = nodes.PrtCtyAll{i}(j).DstBlock;
end
is simply
DstBlocks{i} = {nodes.PrtCtyAll{i}.DstBlock}.'; %no need for a loop
but even that is a waste of time. You're converting a structure array into a cell array for the sole purpose of iterating over its elements. Just iterate directly over the structure.
There is absolutely no point in making D a cell array since each cell is only going to contain a scalar. The whole calculation of D can be simplified into
D = [nodes.PrtCtyAll{i}.DstBlock].';
which does not require preallocation as the array is created and filled at the same time.
But even creating D is probably a waste of time. I don't really understand what you're trying to do with your a loop. What is sure is that at some point it's going to error since find will return more than one index which won't fit into Di(a). In any case, Di is never used and emptied shortly after.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by