あなたの例の構造体が適切に初期化されない理由は、使用している構文が構造体配列の最後の要素のみを扱うためです。存在しない配列の場合、残りの部分は暗黙のうちにすべてのフィールドにデフォルト値 []
を持つ構造体で埋められます。
この動作を明確にするには、 clear edgesを使用して短い配列を試してください。 edges(1)
、 edges(2)
、および edge(1:3)= struct( 'weight'、1.0) code> edges(3)
をクリックします。 edges(3)
要素のウェイトは 1.0
です。他は []
を持っています。
構造体の配列を効率的に初期化するための構文は、これらのうちの1つです。
% Using repmat and full assignment
edges = repmat(struct('weight', 1.0), [1 1000]);
% Using indexing
% NOTE: Only correct if variable is uninitialized!!!
edges(1:1000) = struct('weight', 1.0); % QUESTIONABLE
初期化されていないエッジ配列にインデックスを付けるときは 1000
ではなく 1:1000
に注意してください。
edges(1:1000)
フォームに問題があります。 edges
が既に初期化されている場合、この構文は選択された要素の値を更新します。エッジの要素数が1000を超える場合、残りの要素は変更されず、コードはバグになります。または、 edges
が異なるタイプの場合、既存のデータ型に応じてエラーまたは奇妙な動作が発生する可能性があります。安全のためには、インデックス構文を使用して初期化する前にエッジをクリア
する必要があります。だから、 repmat
フォームを使って完全に代入する方が良いでしょう。
BUT: Regardless of how you initialize it, an array-of-structs like this is always going to be inherently slow to work with for larger data sets. You can't do real "vectorized" operations on it because your primitive arrays are all broken up in to separate mxArrays inside each struct element. That includes the field assignment in your question – it is not possible to vectorize that. Instead, you should switch a struct-of-arrays like Brian L's answer suggests.