Preallocate a variable of unknown size
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Guillaume
le 24 Mai 2018
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!