Create a struct from two cell arrays

19 vues (au cours des 30 derniers jours)
Deepa Maheshvare
Deepa Maheshvare le 22 Août 2021
Modifié(e) : Awais Saeed le 22 Août 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?

Réponse acceptée

Awais Saeed
Awais Saeed le 22 Août 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 commentaire
Awais Saeed
Awais Saeed le 22 Août 2021
Modifié(e) : Awais Saeed le 22 Août 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)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by