Preallocate a variable of unknown size

2 ビュー (過去 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.
  1 件のコメント
Akbar
Akbar 2018 年 5 月 24 日
Thanks a lot, Guillaume!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by