how to initialise a struct array with pairs?

6 visualizaciones (últimos 30 días)
Mr M.
Mr M. el 6 de Oct. de 2015
Comentada: Guillaume el 8 de Oct. de 2015
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?

Respuesta aceptada

Guillaume
Guillaume el 6 de Oct. de 2015
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 comentarios
Mr M.
Mr M. el 7 de Oct. de 2015
I wonder the syntax pairs(:, 1). Isn't it pairs{:, 1}?
Guillaume
Guillaume el 8 de Oct. de 2015
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

Iniciar sesión para comentar.

Más respuestas (2)

Thorsten
Thorsten el 6 de Oct. de 2015
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 el 6 de Oct. de 2015
Editada: Andrei Bobrov el 6 de Oct. de 2015
out = num2cell(reshape(struct2cell(data),2,[])',2)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by