2016-09-19 12 views
1

データセットの1つの列の値に基づいて構造体に分類して格納するデータセットがあります。構造体のフィールド名を数値の配列から作成する

%The labels I would like are based on the dataset 
example_data = [repmat(100,1,100),repmat(200,1,100),repmat(300,1,100)]; 
data_names = unique(example_data); 

%create a cell array of strings for the structure fieldnames 
for i = 1:length(data_names) 
    cell_data_names{i}=sprintf('label_%d', data_names(i)); 
end 

%create a cell array of data (just 0's for now) 
others = num2cell(zeros(size(cell_data_names))); 

%try and create the structure 
data = struct(cell_data_names{:},others{:}) 

これは失敗し、私は次のようなエラーメッセージが出ます::

「エラーを私は下記の試みとして例えば、データは、要素「label_100」、「label_200」または「label_300」に分類することができます構造体を使用する フィールド名は文字列でなければなりません。

(また、私は上記のやろうとしています何を達成するために、より直接的な方法はありますか?)

+0

'cell2struct(その他、cell_data_names)'の代わりに 'struct'のを使用する:これには、各フィールド名フィルが直ちに対応する値が続く、列優先順でセルの内容を与えます。 –

答えて

2

documentation of structによると、

S = struct('field1',VALUES1,'field2',VALUES2,...)は、指定されたフィールドを持つ 構造体配列を作成します値。

フィールド名の直後に各値を設定する必要があります。あなたは今structを呼び出す方法は、あなたが垂直cell_data_namesothersを連結して、コンマ区切りのリストを生成するために{:}を使用してそれを解決することができます代わりに、正しい

S = struct('field1',VALUES1,'field2',VALUES2,...). 

S = struct('field1','field2',VALUES1,VALUES2,...) 

です。

cell_data_names_others = [cell_data_names; others] 
data = struct(cell_data_names_others{:}) 
関連する問題