6

tab = value の形式でネストされた構造配列 t があります。ここで、a と b はランダムな文字列です。t はフィールド名として任意の数の a を持つことができ、各 a はフィールド名として任意の数の b を持つことができます。x という名前の t のコピーを作成する必要がありますが、すべて xab = 0 に設定します。さらに、t 内のすべての a に対して ya = 0 の形式で別の構造体配列を作成する必要があります。現在、ネストされた for ループ ソリューションを使用していますが、a と b が多すぎると遅すぎます。このコードをより高速に実行するために、このネストされたループまたはこのコード内の他の操作をベクトル化する方法があるかどうか誰かに教えてもらえますか? ありがとう。

names1 = fieldnames(t);
x = t;
y = {};
for i=1:length(names1)
  y.(names1{i}) = 0;
  names2 = fieldnames(x.(names1{i}));
  for j=1:length(names2)
      x.(names1{i}).(names2{j}) = 0;
  end
end 

サンプル:

if t is such that
t.hello.world = 0.5
t.hello.mom = 0.2
t.hello.dad = 0.8
t.foo.bar = 0.7
t.foo.moo = 0.23
t.random.word = 0.38

then x should be:
x.hello.world = 0
x.hello.mom = 0
x.hello.dad = 0
x.foo.bar = 0
x.foo.moo = 0
x.random.word = 0

and y should be:
y.hello = 0
y.foo = 0
y.random = 0
4

2 に答える 2

2

structfunを使用して、すべてのループを取り除くことができます

function zeroed = always0(x)
  zeroed = 0;
endfunction

function zeroedStruct = zeroSubfields(x)
   zeroedStruct = structfun(@always0, x, 'UniformOutput', false);
endfunction

y = structfun(@always0, t, 'UniformOutput', false);
x = structfun(@zeroSubfields, t, 'UniformOutput', false); 

フィールドの任意のネストがある場合、zeroSubfieldsを次のように拡張できます。

function zeroedStruct = zeroSubfields(x)
   if(isstruct(x))
     zeroedStruct = structfun(@zeroSubfields, x, 'UniformOutput', false);
   else
     zeroedStruct = 0;
   endif
endfunction
于 2013-03-04T01:59:04.347 に答える
0

を構築yするには、次のようなことを行うことができます。

>> t.hello.world = 0.5;
>> t.hello.mom = 0.2;
>> t.hello.dad = 0.8;
>> t.foo.bar = 0.7;
>> t.foo.moo = 0.23;
>> t.random.word = 0.38;
>> f = fieldnames(t);
>> n = numel(f);
>> fi = cell(1,n*2);
>> fi(1:2:(n*2-1)) = f;
>> fi(2:2:(n*2)) = num2cell(zeros(n,1))
fi = 
    'hello'    [0]    'foo'    [0]    'random'    [0]
>> y = struct(fi{:})
y = 
     hello: 0
       foo: 0
    random: 0

基本的には、フィールド名を取得し、セル配列にゼロをインターリーブしてから、そのセル配列からフィールド名と値のコンマ区切りリストを使用して構造を直接構築します。

の場合x、フィールド名の最初のレベルをループする必要があると思います。ただし、各ループの反復内で上記と同様のことができるはずです。

于 2013-03-01T11:13:47.987 に答える