how to initialise a struct array with pairs?
6 ビュー (過去 30 日間)
古いコメントを表示
I want to keep pairs next to each other during initialisation.
The result what I want is something like this:
data(1).shortname = 'TJ';
data(1).longname = 'Tom Jones';
data(2).shortname = 'JS';
data(2).longname = 'John Smith';
...
But I want to initialise this struct array similar to the following method somehow:
data = ... 'TJ', 'Tom Jones', 'JS', 'John Smith', ...
or
data = ... {'TJ', 'Tom Jones'}, {'JS', 'John Smith'}, ...
Is it possible?
0 件のコメント
採用された回答
Guillaume
2015 年 10 月 6 日
One possible way:
pairs = {'TJ', 'Tom Jones';
'JS', 'John Smith'};
data = struct('shortname', pairs(:, 1), 'longname', pairs(:, 2))
Alternatively:
pairs = {'TJ', 'Tom Jones';
'JS', 'John Smith'};
data = cell2struct(pairs, {'shortname', 'longname'}, 2);
In any case, start with a cell array and convert to structure.
2 件のコメント
Guillaume
2015 年 10 月 8 日
Definitively () and not {}. You want to pass a cell array to struct, not the content of the cell array, particularly as in this case the {} would expand the cell array into a comma separated list
その他の回答 (2 件)
Thorsten
2015 年 10 月 6 日
Initialise
data(1).name = {'TJ', 'Tom Jones'};
data(2).name = {'JS', 'John Smith'};
Get entries
data(1).name{1}
ans =
TJ
>> data(1).name{2}
ans =
Tom Jones
0 件のコメント
Andrei Bobrov
2015 年 10 月 6 日
編集済み: Andrei Bobrov
2015 年 10 月 6 日
out = num2cell(reshape(struct2cell(data),2,[])',2)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!