Preallocate a variable of unknown size
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!