Preallocate variables with unkown size

2 ビュー (過去 30 日間)
Waseem AL Aqqad
Waseem AL Aqqad 2022 年 5 月 23 日
編集済み: Waseem AL Aqqad 2022 年 5 月 25 日
I pre allocate the two variables phi and phiPrime by setting a maximum size and then crop them afterwards. The thing is that both of them depend on vector b which changes its size in every ii.
I did something like the following but not sure if it is quite correct and computational effective.
but I'm not sure whether the way I preallocated the variables lead into wrong results or not.
function [G_dmg, G_orig, phic, inActiveSorted] = SH_decision(G_dmg, G_orig, phic)
N = numnodes(G_dmg);
inActive = find(degree(G_dmg)==0);
impact = -1* ones(1,length(inActive));
phi = zeros(N, 1);
phiPrime = zeros(N, 1);
phidPrime = zeros(N, 1);
lastIdx = 0;
numNeighborsPernode = [];
activeNeighbors = [];
for ii = 1:length(inActive)
b = neighbors(G_orig, inActive(ii));
if ~isempty (b)
degreeOrig = degree(G_orig, b);
degreeDmg = degree(G_dmg, b);
phi(lastIdx + 1: length(b)+lastIdx) = degreeDmg./degreeOrig;
phiPrime(lastIdx + 1: length(b)+lastIdx) = degreeRestoration./degreeOrig ;
impact(ii) = nnz(phi(lastIdx + 1: length(b)+lastIdx)<=phi & phiP(lastIdx + 1: length(b)+lastIdx)>phi);
phidPrime = phiPrime - phi;
lastIdx = lastIdx + length(b);
end
end
phi = phi(1:lastIdx, :);
phiPrime = phiPrime(1:lastIdx, :);
phidPrime = phidPrime(1:lastIdx, :);
end
  2 件のコメント
KSSV
KSSV 2022 年 5 月 23 日
Is phi and phiPrime are vectors at the end?
Why you are using (lastIdx + 1: length(b)+lastIdx) as the index while saving inside loop?
Waseem AL Aqqad
Waseem AL Aqqad 2022 年 5 月 23 日
編集済み: Waseem AL Aqqad 2022 年 5 月 23 日
Thanks for your reply.
Yes, I'm getting them as vectors.

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

採用された回答

Bruno Luong
Bruno Luong 2022 年 5 月 23 日
編集済み: Bruno Luong 2022 年 5 月 23 日
You can compute exactly the size needed for your vectors
A = G_orig.adjacency;
A(inActive,:) = 0;
m = nnz(A(:,inActive));
phi = zeros(m, 1);
phiPrime = zeros(m, 1);
...
  13 件のコメント
Bruno Luong
Bruno Luong 2022 年 5 月 25 日
編集済み: Bruno Luong 2022 年 5 月 25 日
If you need it, yes.
Waseem AL Aqqad
Waseem AL Aqqad 2022 年 5 月 25 日
Thanks, Bruno.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by