I am trying to convert a cell into a structure:
A = {'p1', 10, 'ny'; 'p2', 12, 'nj'};
I would like a structure with 3 fields where
A.person = {'p1';'p2'}
A.age = [10;12]
A.state = {'ny', 'nj'}
I tried cell2struct but was getting in format I did not want. I know I am missing something simple. Any thoughts?
What's wrong with cell2struct
? Let
>> fields = {'person','age','state'}; %// field names
You could use either of the following three versions:
>> S = cell2struct(A, fields, 2); %// fold 2nd dim into fields
S =
2x1 struct array with fields:
person
age
state
(gives a 2x1 struct array).
>> S = cell2struct(mat2cell(A.', ones(1,size(A,2))), fields, 1)
S =
person: {'p1' 'p2'}
age: {[10] [12]}
state: {'ny' 'nj'}
(gives a 1x1 struct array, with a row cell array in each field).
>> S = cell2struct(mat2cell(A, size(A,1), ones(1,size(A,2))), fields, 2)
S =
person: {2x1 cell}
age: {2x1 cell}
state: {2x1 cell}
>> S.person
ans =
'p1'
'p2'
(gives a 1x1 struct array, with a column cell array in each field)