フィルターのクリア

How do I preallocate memory

24 ビュー (過去 30 日間)
Chuck Dalby
Chuck Dalby 2024 年 7 月 2 日 16:38
回答済み: Rik 2024 年 7 月 2 日 18:23
I get the error message at the end of the first for loop (after code: OutData(ii).hucID = hucID;) that I should consider preallocating memory. How do I do that for the following code:
for ii = 1:length(hucPoly)
hucSub = polyshape(hucPoly(ii).X, hucPoly(ii).Y);
hucID = hucPoly(ii).Name;
OutData(ii).hucID = hucID;
for i = 1:size(inFiles,1)
inShapeOld = shaperead([dataFolder char(inFiles.OldShape(i))]);
inPolyOld = polyshape([inShapeOld.X],[inShapeOld.Y], 'Simplify', false);
inShapeNew = shaperead([dataFolder char(inFiles.NewShape(i))]);
inPolyNew = polyshape([inShapeNew.X],[inShapeNew.Y], 'Simplify', false);
inPolyNewsub = intersect(inPolyNew, hucSub,'KeepCollinearPoints',true);
inPolyOldsub = intersect(inPolyOld, hucSub);
[OutData(ii).intsecArea(i).Data, S] = polyIntersect(CoRegErrData, inPolyNewsub, inPolyOldsub);
OutData(ii).intsecArea(i).ID = char(inFiles.NewShape(i));
if ~isnan(S(1).X(1))
shapewrite(S, [dataFolder 'outShapes_S\' hucID '_outInt_' char(inFiles.NewShape(i))])
end
T = table(OutData(ii).intsecArea(i).Data, 'VariableNames', {'outInt_acres1' });
writetable(T, [dataFolder 'outTables_S\' hucID '_outInt_' char(inFiles.NewShape(i)) '.txt'])
end
end

採用された回答

Voss
Voss 2024 年 7 月 2 日 17:04
編集済み: Voss 2024 年 7 月 2 日 17:05
One way is to do this before the outer loop:
clear OutData
OutData(length(hucPoly)) = struct();
  1 件のコメント
Voss
Voss 2024 年 7 月 2 日 17:07
Another way is to do this before the outer loop:
OutData = struct('hucID',num2cell(zeros(1,length(hucPoly))),'intsecArea',[]);

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

その他の回答 (1 件)

Rik
Rik 2024 年 7 月 2 日 18:23

A third way to do it: loop backwards.

for ii = numel(hucPoly):-1:1

This also replaces the call to the length function. I have yet to see a situation where people actually mean max(size(A)) instead of the number of elements.

But the main point is that for a struct it is much less important to pre-allocate properly.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by