how to initialise a struct array with pairs?

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?

 채택된 답변

Guillaume
Guillaume 2015년 10월 6일

2 개 추천

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

Mr M.
Mr M. 2015년 10월 7일
I wonder the syntax pairs(:, 1). Isn't it pairs{:, 1}?
Guillaume
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
Thorsten 2015년 10월 6일

1 개 추천

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
Andrei Bobrov
Andrei Bobrov 2015년 10월 6일
편집: Andrei Bobrov 2015년 10월 6일

1 개 추천

out = num2cell(reshape(struct2cell(data),2,[])',2)

카테고리

도움말 센터File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

질문:

2015년 10월 6일

댓글:

2015년 10월 8일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by