74

私の質問は次のように簡単に要約できます。

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for i=1:numel(fields)
  fields(i)
  teststruct.(fields(i))
end

出力:

ans = 'a'

??? Argument to dynamic structure reference must evaluate to a valid field name.

特に機能するteststruct.('a') ので。とfields(i)出力しans = 'a'ます。

私はそれを理解することができません。

4

4 に答える 4

95

この関数は文字列のセル配列を返すため、{}にアクセスするには中かっこ ( ) を使用する必要があります。fieldsfieldnames

for i = 1:numel(fields)
  teststruct.(fields{i})
end

かっこを使用して cell 配列内のデータにアクセスすると、別の cell 配列が返されるだけで、文字配列とは異なる方法で表示されます。

>> fields(1)  % Get the first cell of the cell array

ans = 

    'a'       % This is how the 1-element cell array is displayed

>> fields{1}  % Get the contents of the first cell of the cell array

ans =

a             % This is how the single character is displayed
于 2010-05-10T15:41:25.967 に答える
15

またははセル配列であるため、セルの内容、つまり文字列にアクセスするには、中かっこでインデックスを付ける必要がfieldsあります。fns{}

数値をループする代わりに、fields直接ループすることもできます。これにより、任意の配列をループできる優れたMatlab機能を利用できます。反復変数は、配列の各列の値を取ります。

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end
于 2010-05-10T15:47:49.600 に答える
5

fns は cellstr 配列です。単一の文字列を char として取得するには、() の代わりに {} を使用してインデックスを作成する必要があります。

fns{i}
teststruct.(fns{i})

() でそれにインデックスを付けると、長さ 1 の cellstr 配列が返されます。これは、".(name)" 動的フィールド参照が必要とする char 配列と同じ形式ではありません。特に表示出力のフォーマットは、混乱を招く可能性があります。違いを確認するには、これを試してください。

name_as_char = 'a'
name_as_cellstr = {'a'}
于 2010-05-10T15:41:51.407 に答える
1

http://www.mathworks.com/matlabcentral/fileexchange/48729-for-eachの for each ツールボックスを使用できます。

>> signal
signal = 
sin: {{1x1x25 cell}  {1x1x25 cell}}
cos: {{1x1x25 cell}  {1x1x25 cell}}

>> each(fieldnames(signal))
ans = 
CellIterator with properties:

NumberOfIterations: 2.0000e+000

使用法:

for bridge = each(fieldnames(signal))
   signal.(bridge) = rand(10);
end

私はそれがとても好き。もちろん、ツールボックスを開発した Jeremy Hughes の功績によるものです。

于 2016-02-29T13:36:21.743 に答える