Create a struct from two cell arrays

21 visualizaciones (últimos 30 días)
Deepa Maheshvare
Deepa Maheshvare el 22 de Ag. de 2021
Editada: Awais Saeed el 22 de Ag. de 2021
I've the following cell arrays
keys =
4×1 cell array
{'n' }
{'key12'}
{'key13'}
{'key14'}
values =
4×1 cell array
{[ 10]}
{[ 1]}
{[ 1]}
{'Hello'}
When I try to create a struct in the following manner
args=[names;values];
structure = struct(args{:})
the below error occurs
Error using struct
Field names must be non-empty character vectors or a string scalars.
Error in setting.load_setting (line 19)
structure = struct(args{:})
Could someone please have a look?

Respuesta aceptada

Awais Saeed
Awais Saeed el 22 de Ag. de 2021
keys = {'n', 'key12', 'key13','key14'};
values = {10, 1 1 , 'Hello'};
names = {'f1', 'f2', 'f3', 'f4'};
args=[names;values];
structure = struct(args{:})
Seems to work for me
  1 comentario
Awais Saeed
Awais Saeed el 22 de Ag. de 2021
Editada: Awais Saeed el 22 de Ag. de 2021
Perhaps you are trying with
names = {'f1', 'f2', '', ''};
This will cause problems. If you must proceed this way I think it would be better to replace those empty cells with some string
keys = {'n', 'key12', 'key13','key14'};
values = {10, 1 1 , 'Hello'};
names = {'f1', 'f2', '', ''};
% get locations of empty cell elements
idx = cellfun('isempty',names);
[row, col] = find(idx);
% replace those empty cells with some string
for jj = 1:1:size(col,2)
idx = col(jj);
names{idx} = ['skip' num2str(jj)];
end
% Now concatenate cells
args=[names;values]
% convert to struct
P = struct(args{:});
struct2table(P)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by